Path: blob/master/src/hotspot/share/opto/doCall.cpp
64441 views
/*1* Copyright (c) 1998, 2022, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "ci/ciCallSite.hpp"26#include "ci/ciMethodHandle.hpp"27#include "ci/ciSymbols.hpp"28#include "classfile/vmSymbols.hpp"29#include "compiler/compileBroker.hpp"30#include "compiler/compileLog.hpp"31#include "interpreter/linkResolver.hpp"32#include "opto/addnode.hpp"33#include "opto/callGenerator.hpp"34#include "opto/castnode.hpp"35#include "opto/cfgnode.hpp"36#include "opto/mulnode.hpp"37#include "opto/parse.hpp"38#include "opto/rootnode.hpp"39#include "opto/runtime.hpp"40#include "opto/subnode.hpp"41#include "prims/methodHandles.hpp"42#include "runtime/sharedRuntime.hpp"4344void trace_type_profile(Compile* C, ciMethod *method, int depth, int bci, ciMethod *prof_method, ciKlass *prof_klass, int site_count, int receiver_count) {45if (TraceTypeProfile || C->print_inlining()) {46outputStream* out = tty;47if (!C->print_inlining()) {48if (!PrintOpto && !PrintCompilation) {49method->print_short_name();50tty->cr();51}52CompileTask::print_inlining_tty(prof_method, depth, bci);53} else {54out = C->print_inlining_stream();55}56CompileTask::print_inline_indent(depth, out);57out->print(" \\-> TypeProfile (%d/%d counts) = ", receiver_count, site_count);58stringStream ss;59prof_klass->name()->print_symbol_on(&ss);60out->print("%s", ss.as_string());61out->cr();62}63}6465CallGenerator* Compile::call_generator(ciMethod* callee, int vtable_index, bool call_does_dispatch,66JVMState* jvms, bool allow_inline,67float prof_factor, ciKlass* speculative_receiver_type,68bool allow_intrinsics) {69assert(callee != NULL, "failed method resolution");7071ciMethod* caller = jvms->method();72int bci = jvms->bci();73Bytecodes::Code bytecode = caller->java_code_at_bci(bci);74ciMethod* orig_callee = caller->get_method_at_bci(bci);7576const bool is_virtual_or_interface = (bytecode == Bytecodes::_invokevirtual) ||77(bytecode == Bytecodes::_invokeinterface) ||78(orig_callee->intrinsic_id() == vmIntrinsics::_linkToVirtual) ||79(orig_callee->intrinsic_id() == vmIntrinsics::_linkToInterface);8081// Dtrace currently doesn't work unless all calls are vanilla82if (env()->dtrace_method_probes()) {83allow_inline = false;84}8586// Note: When we get profiling during stage-1 compiles, we want to pull87// from more specific profile data which pertains to this inlining.88// Right now, ignore the information in jvms->caller(), and do method[bci].89ciCallProfile profile = caller->call_profile_at_bci(bci);9091// See how many times this site has been invoked.92int site_count = profile.count();93int receiver_count = -1;94if (call_does_dispatch && UseTypeProfile && profile.has_receiver(0)) {95// Receivers in the profile structure are ordered by call counts96// so that the most called (major) receiver is profile.receiver(0).97receiver_count = profile.receiver_count(0);98}99100CompileLog* log = this->log();101if (log != NULL) {102int rid = (receiver_count >= 0)? log->identify(profile.receiver(0)): -1;103int r2id = (rid != -1 && profile.has_receiver(1))? log->identify(profile.receiver(1)):-1;104log->begin_elem("call method='%d' count='%d' prof_factor='%f'",105log->identify(callee), site_count, prof_factor);106if (call_does_dispatch) log->print(" virtual='1'");107if (allow_inline) log->print(" inline='1'");108if (receiver_count >= 0) {109log->print(" receiver='%d' receiver_count='%d'", rid, receiver_count);110if (profile.has_receiver(1)) {111log->print(" receiver2='%d' receiver2_count='%d'", r2id, profile.receiver_count(1));112}113}114if (callee->is_method_handle_intrinsic()) {115log->print(" method_handle_intrinsic='1'");116}117log->end_elem();118}119120// Special case the handling of certain common, profitable library121// methods. If these methods are replaced with specialized code,122// then we return it as the inlined version of the call.123CallGenerator* cg_intrinsic = NULL;124if (allow_inline && allow_intrinsics) {125CallGenerator* cg = find_intrinsic(callee, call_does_dispatch);126if (cg != NULL) {127if (cg->is_predicated()) {128// Code without intrinsic but, hopefully, inlined.129CallGenerator* inline_cg = this->call_generator(callee,130vtable_index, call_does_dispatch, jvms, allow_inline, prof_factor, speculative_receiver_type, false);131if (inline_cg != NULL) {132cg = CallGenerator::for_predicated_intrinsic(cg, inline_cg);133}134}135136// If intrinsic does the virtual dispatch, we try to use the type profile137// first, and hopefully inline it as the regular virtual call below.138// We will retry the intrinsic if nothing had claimed it afterwards.139if (cg->does_virtual_dispatch()) {140cg_intrinsic = cg;141cg = NULL;142} else if (IncrementalInline && should_delay_vector_inlining(callee, jvms)) {143return CallGenerator::for_late_inline(callee, cg);144} else {145return cg;146}147}148}149150// Do method handle calls.151// NOTE: This must happen before normal inlining logic below since152// MethodHandle.invoke* are native methods which obviously don't153// have bytecodes and so normal inlining fails.154if (callee->is_method_handle_intrinsic()) {155CallGenerator* cg = CallGenerator::for_method_handle_call(jvms, caller, callee, allow_inline);156return cg;157}158159// Attempt to inline...160if (allow_inline) {161// The profile data is only partly attributable to this caller,162// scale back the call site information.163float past_uses = jvms->method()->scale_count(site_count, prof_factor);164// This is the number of times we expect the call code to be used.165float expected_uses = past_uses;166167// Try inlining a bytecoded method:168if (!call_does_dispatch) {169InlineTree* ilt = InlineTree::find_subtree_from_root(this->ilt(), jvms->caller(), jvms->method());170bool should_delay = false;171if (ilt->ok_to_inline(callee, jvms, profile, should_delay)) {172CallGenerator* cg = CallGenerator::for_inline(callee, expected_uses);173// For optimized virtual calls assert at runtime that receiver object174// is a subtype of the inlined method holder. CHA can report a method175// as a unique target under an abstract method, but receiver type176// sometimes has a broader type. Similar scenario is possible with177// default methods when type system loses information about implemented178// interfaces.179if (cg != NULL && is_virtual_or_interface && !callee->is_static()) {180CallGenerator* trap_cg = CallGenerator::for_uncommon_trap(callee,181Deoptimization::Reason_receiver_constraint, Deoptimization::Action_none);182183cg = CallGenerator::for_guarded_call(callee->holder(), trap_cg, cg);184}185if (cg != NULL) {186// Delay the inlining of this method to give us the187// opportunity to perform some high level optimizations188// first.189if (should_delay_string_inlining(callee, jvms)) {190return CallGenerator::for_string_late_inline(callee, cg);191} else if (should_delay_boxing_inlining(callee, jvms)) {192return CallGenerator::for_boxing_late_inline(callee, cg);193} else if (should_delay_vector_reboxing_inlining(callee, jvms)) {194return CallGenerator::for_vector_reboxing_late_inline(callee, cg);195} else if ((should_delay || AlwaysIncrementalInline)) {196return CallGenerator::for_late_inline(callee, cg);197} else {198return cg;199}200}201}202}203204// Try using the type profile.205if (call_does_dispatch && site_count > 0 && UseTypeProfile) {206// The major receiver's count >= TypeProfileMajorReceiverPercent of site_count.207bool have_major_receiver = profile.has_receiver(0) && (100.*profile.receiver_prob(0) >= (float)TypeProfileMajorReceiverPercent);208ciMethod* receiver_method = NULL;209210int morphism = profile.morphism();211if (speculative_receiver_type != NULL) {212if (!too_many_traps_or_recompiles(caller, bci, Deoptimization::Reason_speculate_class_check)) {213// We have a speculative type, we should be able to resolve214// the call. We do that before looking at the profiling at215// this invoke because it may lead to bimorphic inlining which216// a speculative type should help us avoid.217receiver_method = callee->resolve_invoke(jvms->method()->holder(),218speculative_receiver_type);219if (receiver_method == NULL) {220speculative_receiver_type = NULL;221} else {222morphism = 1;223}224} else {225// speculation failed before. Use profiling at the call226// (could allow bimorphic inlining for instance).227speculative_receiver_type = NULL;228}229}230if (receiver_method == NULL &&231(have_major_receiver || morphism == 1 ||232(morphism == 2 && UseBimorphicInlining))) {233// receiver_method = profile.method();234// Profiles do not suggest methods now. Look it up in the major receiver.235receiver_method = callee->resolve_invoke(jvms->method()->holder(),236profile.receiver(0));237}238if (receiver_method != NULL) {239// The single majority receiver sufficiently outweighs the minority.240CallGenerator* hit_cg = this->call_generator(receiver_method,241vtable_index, !call_does_dispatch, jvms, allow_inline, prof_factor);242if (hit_cg != NULL) {243// Look up second receiver.244CallGenerator* next_hit_cg = NULL;245ciMethod* next_receiver_method = NULL;246if (morphism == 2 && UseBimorphicInlining) {247next_receiver_method = callee->resolve_invoke(jvms->method()->holder(),248profile.receiver(1));249if (next_receiver_method != NULL) {250next_hit_cg = this->call_generator(next_receiver_method,251vtable_index, !call_does_dispatch, jvms,252allow_inline, prof_factor);253if (next_hit_cg != NULL && !next_hit_cg->is_inline() &&254have_major_receiver && UseOnlyInlinedBimorphic) {255// Skip if we can't inline second receiver's method256next_hit_cg = NULL;257}258}259}260CallGenerator* miss_cg;261Deoptimization::DeoptReason reason = (morphism == 2262? Deoptimization::Reason_bimorphic263: Deoptimization::reason_class_check(speculative_receiver_type != NULL));264if ((morphism == 1 || (morphism == 2 && next_hit_cg != NULL)) &&265!too_many_traps_or_recompiles(caller, bci, reason)266) {267// Generate uncommon trap for class check failure path268// in case of monomorphic or bimorphic virtual call site.269miss_cg = CallGenerator::for_uncommon_trap(callee, reason,270Deoptimization::Action_maybe_recompile);271} else {272// Generate virtual call for class check failure path273// in case of polymorphic virtual call site.274miss_cg = (IncrementalInlineVirtual ? CallGenerator::for_late_inline_virtual(callee, vtable_index, prof_factor)275: CallGenerator::for_virtual_call(callee, vtable_index));276}277if (miss_cg != NULL) {278if (next_hit_cg != NULL) {279assert(speculative_receiver_type == NULL, "shouldn't end up here if we used speculation");280trace_type_profile(C, jvms->method(), jvms->depth() - 1, jvms->bci(), next_receiver_method, profile.receiver(1), site_count, profile.receiver_count(1));281// We don't need to record dependency on a receiver here and below.282// Whenever we inline, the dependency is added by Parse::Parse().283miss_cg = CallGenerator::for_predicted_call(profile.receiver(1), miss_cg, next_hit_cg, PROB_MAX);284}285if (miss_cg != NULL) {286ciKlass* k = speculative_receiver_type != NULL ? speculative_receiver_type : profile.receiver(0);287trace_type_profile(C, jvms->method(), jvms->depth() - 1, jvms->bci(), receiver_method, k, site_count, receiver_count);288float hit_prob = speculative_receiver_type != NULL ? 1.0 : profile.receiver_prob(0);289CallGenerator* cg = CallGenerator::for_predicted_call(k, miss_cg, hit_cg, hit_prob);290if (cg != NULL) return cg;291}292}293}294}295}296297// If there is only one implementor of this interface then we298// may be able to bind this invoke directly to the implementing299// klass but we need both a dependence on the single interface300// and on the method we bind to. Additionally since all we know301// about the receiver type is that it's supposed to implement the302// interface we have to insert a check that it's the class we303// expect. Interface types are not checked by the verifier so304// they are roughly equivalent to Object.305// The number of implementors for declared_interface is less or306// equal to the number of implementors for target->holder() so307// if number of implementors of target->holder() == 1 then308// number of implementors for decl_interface is 0 or 1. If309// it's 0 then no class implements decl_interface and there's310// no point in inlining.311if (call_does_dispatch && bytecode == Bytecodes::_invokeinterface) {312ciInstanceKlass* declared_interface =313caller->get_declared_method_holder_at_bci(bci)->as_instance_klass();314ciInstanceKlass* singleton = declared_interface->unique_implementor();315316if (singleton != NULL) {317assert(singleton != declared_interface, "not a unique implementor");318319ciMethod* cha_monomorphic_target =320callee->find_monomorphic_target(caller->holder(), declared_interface, singleton);321322if (cha_monomorphic_target != NULL &&323cha_monomorphic_target->holder() != env()->Object_klass()) { // subtype check against Object is useless324ciKlass* holder = cha_monomorphic_target->holder();325326// Try to inline the method found by CHA. Inlined method is guarded by the type check.327CallGenerator* hit_cg = call_generator(cha_monomorphic_target,328vtable_index, !call_does_dispatch, jvms, allow_inline, prof_factor);329330// Deoptimize on type check fail. The interpreter will throw ICCE for us.331CallGenerator* miss_cg = CallGenerator::for_uncommon_trap(callee,332Deoptimization::Reason_class_check, Deoptimization::Action_none);333334ciKlass* constraint = (holder->is_subclass_of(singleton) ? holder : singleton); // avoid upcasts335CallGenerator* cg = CallGenerator::for_guarded_call(constraint, miss_cg, hit_cg);336if (hit_cg != NULL && cg != NULL) {337dependencies()->assert_unique_implementor(declared_interface, singleton);338dependencies()->assert_unique_concrete_method(declared_interface, cha_monomorphic_target, declared_interface, callee);339return cg;340}341}342}343} // call_does_dispatch && bytecode == Bytecodes::_invokeinterface344345// Nothing claimed the intrinsic, we go with straight-forward inlining346// for already discovered intrinsic.347if (allow_intrinsics && cg_intrinsic != NULL) {348assert(cg_intrinsic->does_virtual_dispatch(), "sanity");349return cg_intrinsic;350}351} // allow_inline352353// There was no special inlining tactic, or it bailed out.354// Use a more generic tactic, like a simple call.355if (call_does_dispatch) {356const char* msg = "virtual call";357if (C->print_inlining()) {358print_inlining(callee, jvms->depth() - 1, jvms->bci(), msg);359}360C->log_inline_failure(msg);361if (IncrementalInlineVirtual && allow_inline) {362return CallGenerator::for_late_inline_virtual(callee, vtable_index, prof_factor); // attempt to inline through virtual call later363} else {364return CallGenerator::for_virtual_call(callee, vtable_index);365}366} else {367// Class Hierarchy Analysis or Type Profile reveals a unique target, or it is a static or special call.368CallGenerator* cg = CallGenerator::for_direct_call(callee, should_delay_inlining(callee, jvms));369// For optimized virtual calls assert at runtime that receiver object370// is a subtype of the method holder.371if (cg != NULL && is_virtual_or_interface && !callee->is_static()) {372CallGenerator* trap_cg = CallGenerator::for_uncommon_trap(callee,373Deoptimization::Reason_receiver_constraint, Deoptimization::Action_none);374cg = CallGenerator::for_guarded_call(callee->holder(), trap_cg, cg);375}376return cg;377}378}379380// Return true for methods that shouldn't be inlined early so that381// they are easier to analyze and optimize as intrinsics.382bool Compile::should_delay_string_inlining(ciMethod* call_method, JVMState* jvms) {383if (has_stringbuilder()) {384385if ((call_method->holder() == C->env()->StringBuilder_klass() ||386call_method->holder() == C->env()->StringBuffer_klass()) &&387(jvms->method()->holder() == C->env()->StringBuilder_klass() ||388jvms->method()->holder() == C->env()->StringBuffer_klass())) {389// Delay SB calls only when called from non-SB code390return false;391}392393switch (call_method->intrinsic_id()) {394case vmIntrinsics::_StringBuilder_void:395case vmIntrinsics::_StringBuilder_int:396case vmIntrinsics::_StringBuilder_String:397case vmIntrinsics::_StringBuilder_append_char:398case vmIntrinsics::_StringBuilder_append_int:399case vmIntrinsics::_StringBuilder_append_String:400case vmIntrinsics::_StringBuilder_toString:401case vmIntrinsics::_StringBuffer_void:402case vmIntrinsics::_StringBuffer_int:403case vmIntrinsics::_StringBuffer_String:404case vmIntrinsics::_StringBuffer_append_char:405case vmIntrinsics::_StringBuffer_append_int:406case vmIntrinsics::_StringBuffer_append_String:407case vmIntrinsics::_StringBuffer_toString:408case vmIntrinsics::_Integer_toString:409return true;410411case vmIntrinsics::_String_String:412{413Node* receiver = jvms->map()->in(jvms->argoff() + 1);414if (receiver->is_Proj() && receiver->in(0)->is_CallStaticJava()) {415CallStaticJavaNode* csj = receiver->in(0)->as_CallStaticJava();416ciMethod* m = csj->method();417if (m != NULL &&418(m->intrinsic_id() == vmIntrinsics::_StringBuffer_toString ||419m->intrinsic_id() == vmIntrinsics::_StringBuilder_toString))420// Delay String.<init>(new SB())421return true;422}423return false;424}425426default:427return false;428}429}430return false;431}432433bool Compile::should_delay_boxing_inlining(ciMethod* call_method, JVMState* jvms) {434if (eliminate_boxing() && call_method->is_boxing_method()) {435set_has_boxed_value(true);436return aggressive_unboxing();437}438return false;439}440441bool Compile::should_delay_vector_inlining(ciMethod* call_method, JVMState* jvms) {442return EnableVectorSupport && call_method->is_vector_method();443}444445bool Compile::should_delay_vector_reboxing_inlining(ciMethod* call_method, JVMState* jvms) {446return EnableVectorSupport && (call_method->intrinsic_id() == vmIntrinsics::_VectorRebox);447}448449// uncommon-trap call-sites where callee is unloaded, uninitialized or will not link450bool Parse::can_not_compile_call_site(ciMethod *dest_method, ciInstanceKlass* klass) {451// Additional inputs to consider...452// bc = bc()453// caller = method()454// iter().get_method_holder_index()455assert( dest_method->is_loaded(), "ciTypeFlow should not let us get here" );456// Interface classes can be loaded & linked and never get around to457// being initialized. Uncommon-trap for not-initialized static or458// v-calls. Let interface calls happen.459ciInstanceKlass* holder_klass = dest_method->holder();460if (!holder_klass->is_being_initialized() &&461!holder_klass->is_initialized() &&462!holder_klass->is_interface()) {463uncommon_trap(Deoptimization::Reason_uninitialized,464Deoptimization::Action_reinterpret,465holder_klass);466return true;467}468469assert(dest_method->is_loaded(), "dest_method: typeflow responsibility");470return false;471}472473#ifdef ASSERT474static bool check_call_consistency(JVMState* jvms, CallGenerator* cg) {475ciMethod* symbolic_info = jvms->method()->get_method_at_bci(jvms->bci());476ciMethod* resolved_method = cg->method();477if (!ciMethod::is_consistent_info(symbolic_info, resolved_method)) {478tty->print_cr("JVMS:");479jvms->dump();480tty->print_cr("Bytecode info:");481jvms->method()->get_method_at_bci(jvms->bci())->print(); tty->cr();482tty->print_cr("Resolved method:");483cg->method()->print(); tty->cr();484return false;485}486return true;487}488#endif // ASSERT489490//------------------------------do_call----------------------------------------491// Handle your basic call. Inline if we can & want to, else just setup call.492void Parse::do_call() {493// It's likely we are going to add debug info soon.494// Also, if we inline a guy who eventually needs debug info for this JVMS,495// our contribution to it is cleaned up right here.496kill_dead_locals();497498C->print_inlining_assert_ready();499500// Set frequently used booleans501const bool is_virtual = bc() == Bytecodes::_invokevirtual;502const bool is_virtual_or_interface = is_virtual || bc() == Bytecodes::_invokeinterface;503const bool has_receiver = Bytecodes::has_receiver(bc());504505// Find target being called506bool will_link;507ciSignature* declared_signature = NULL;508ciMethod* orig_callee = iter().get_method(will_link, &declared_signature); // callee in the bytecode509ciInstanceKlass* holder_klass = orig_callee->holder();510ciKlass* holder = iter().get_declared_method_holder();511ciInstanceKlass* klass = ciEnv::get_instance_klass_for_declared_method_holder(holder);512assert(declared_signature != NULL, "cannot be null");513514// Bump max node limit for JSR292 users515if (bc() == Bytecodes::_invokedynamic || orig_callee->is_method_handle_intrinsic()) {516C->set_max_node_limit(3*MaxNodeLimit);517}518519// uncommon-trap when callee is unloaded, uninitialized or will not link520// bailout when too many arguments for register representation521if (!will_link || can_not_compile_call_site(orig_callee, klass)) {522if (PrintOpto && (Verbose || WizardMode)) {523method()->print_name(); tty->print_cr(" can not compile call at bci %d to:", bci());524orig_callee->print_name(); tty->cr();525}526return;527}528assert(holder_klass->is_loaded(), "");529//assert((bc_callee->is_static() || is_invokedynamic) == !has_receiver , "must match bc"); // XXX invokehandle (cur_bc_raw)530// Note: this takes into account invokeinterface of methods declared in java/lang/Object,531// which should be invokevirtuals but according to the VM spec may be invokeinterfaces532assert(holder_klass->is_interface() || holder_klass->super() == NULL || (bc() != Bytecodes::_invokeinterface), "must match bc");533// Note: In the absence of miranda methods, an abstract class K can perform534// an invokevirtual directly on an interface method I.m if K implements I.535536// orig_callee is the resolved callee which's signature includes the537// appendix argument.538const int nargs = orig_callee->arg_size();539const bool is_signature_polymorphic = MethodHandles::is_signature_polymorphic(orig_callee->intrinsic_id());540541// Push appendix argument (MethodType, CallSite, etc.), if one.542if (iter().has_appendix()) {543ciObject* appendix_arg = iter().get_appendix();544const TypeOopPtr* appendix_arg_type = TypeOopPtr::make_from_constant(appendix_arg, /* require_const= */ true);545Node* appendix_arg_node = _gvn.makecon(appendix_arg_type);546push(appendix_arg_node);547}548549// ---------------------550// Does Class Hierarchy Analysis reveal only a single target of a v-call?551// Then we may inline or make a static call, but become dependent on there being only 1 target.552// Does the call-site type profile reveal only one receiver?553// Then we may introduce a run-time check and inline on the path where it succeeds.554// The other path may uncommon_trap, check for another receiver, or do a v-call.555556// Try to get the most accurate receiver type557ciMethod* callee = orig_callee;558int vtable_index = Method::invalid_vtable_index;559bool call_does_dispatch = false;560561// Speculative type of the receiver if any562ciKlass* speculative_receiver_type = NULL;563if (is_virtual_or_interface) {564Node* receiver_node = stack(sp() - nargs);565const TypeOopPtr* receiver_type = _gvn.type(receiver_node)->isa_oopptr();566// call_does_dispatch and vtable_index are out-parameters. They might be changed.567// For arrays, klass below is Object. When vtable calls are used,568// resolving the call with Object would allow an illegal call to569// finalize() on an array. We use holder instead: illegal calls to570// finalize() won't be compiled as vtable calls (IC call571// resolution will catch the illegal call) and the few legal calls572// on array types won't be either.573callee = C->optimize_virtual_call(method(), klass, holder, orig_callee,574receiver_type, is_virtual,575call_does_dispatch, vtable_index); // out-parameters576speculative_receiver_type = receiver_type != NULL ? receiver_type->speculative_type() : NULL;577}578579// Additional receiver subtype checks for interface calls via invokespecial or invokeinterface.580ciKlass* receiver_constraint = NULL;581if (iter().cur_bc_raw() == Bytecodes::_invokespecial && !orig_callee->is_object_initializer()) {582ciInstanceKlass* calling_klass = method()->holder();583ciInstanceKlass* sender_klass = calling_klass;584if (sender_klass->is_interface()) {585receiver_constraint = sender_klass;586}587} else if (iter().cur_bc_raw() == Bytecodes::_invokeinterface && orig_callee->is_private()) {588assert(holder->is_interface(), "How did we get a non-interface method here!");589receiver_constraint = holder;590}591592if (receiver_constraint != NULL) {593Node* receiver_node = stack(sp() - nargs);594Node* cls_node = makecon(TypeKlassPtr::make(receiver_constraint));595Node* bad_type_ctrl = NULL;596Node* casted_receiver = gen_checkcast(receiver_node, cls_node, &bad_type_ctrl);597if (bad_type_ctrl != NULL) {598PreserveJVMState pjvms(this);599set_control(bad_type_ctrl);600uncommon_trap(Deoptimization::Reason_class_check,601Deoptimization::Action_none);602}603if (stopped()) {604return; // MUST uncommon-trap?605}606set_stack(sp() - nargs, casted_receiver);607}608609// Note: It's OK to try to inline a virtual call.610// The call generator will not attempt to inline a polymorphic call611// unless it knows how to optimize the receiver dispatch.612bool try_inline = (C->do_inlining() || InlineAccessors);613614// ---------------------615dec_sp(nargs); // Temporarily pop args for JVM state of call616JVMState* jvms = sync_jvms();617618// ---------------------619// Decide call tactic.620// This call checks with CHA, the interpreter profile, intrinsics table, etc.621// It decides whether inlining is desirable or not.622CallGenerator* cg = C->call_generator(callee, vtable_index, call_does_dispatch, jvms, try_inline, prof_factor(), speculative_receiver_type);623624// NOTE: Don't use orig_callee and callee after this point! Use cg->method() instead.625orig_callee = callee = NULL;626627// ---------------------628// Round double arguments before call629round_double_arguments(cg->method());630631// Feed profiling data for arguments to the type system so it can632// propagate it as speculative types633record_profiled_arguments_for_speculation(cg->method(), bc());634635#ifndef PRODUCT636// bump global counters for calls637count_compiled_calls(/*at_method_entry*/ false, cg->is_inline());638639// Record first part of parsing work for this call640parse_histogram()->record_change();641#endif // not PRODUCT642643assert(jvms == this->jvms(), "still operating on the right JVMS");644assert(jvms_in_sync(), "jvms must carry full info into CG");645646// save across call, for a subsequent cast_not_null.647Node* receiver = has_receiver ? argument(0) : NULL;648649// The extra CheckCastPPs for speculative types mess with PhaseStringOpts650if (receiver != NULL && !call_does_dispatch && !cg->is_string_late_inline()) {651// Feed profiling data for a single receiver to the type system so652// it can propagate it as a speculative type653receiver = record_profiled_receiver_for_speculation(receiver);654}655656JVMState* new_jvms = cg->generate(jvms);657if (new_jvms == NULL) {658// When inlining attempt fails (e.g., too many arguments),659// it may contaminate the current compile state, making it660// impossible to pull back and try again. Once we call661// cg->generate(), we are committed. If it fails, the whole662// compilation task is compromised.663if (failing()) return;664665// This can happen if a library intrinsic is available, but refuses666// the call site, perhaps because it did not match a pattern the667// intrinsic was expecting to optimize. Should always be possible to668// get a normal java call that may inline in that case669cg = C->call_generator(cg->method(), vtable_index, call_does_dispatch, jvms, try_inline, prof_factor(), speculative_receiver_type, /* allow_intrinsics= */ false);670new_jvms = cg->generate(jvms);671if (new_jvms == NULL) {672guarantee(failing(), "call failed to generate: calls should work");673return;674}675}676677if (cg->is_inline()) {678// Accumulate has_loops estimate679C->env()->notice_inlined_method(cg->method());680}681682// Reset parser state from [new_]jvms, which now carries results of the call.683// Return value (if any) is already pushed on the stack by the cg.684add_exception_states_from(new_jvms);685if (new_jvms->map()->control() == top()) {686stop_and_kill_map();687} else {688assert(new_jvms->same_calls_as(jvms), "method/bci left unchanged");689set_jvms(new_jvms);690}691692assert(check_call_consistency(jvms, cg), "inconsistent info");693694if (!stopped()) {695// This was some sort of virtual call, which did a null check for us.696// Now we can assert receiver-not-null, on the normal return path.697if (receiver != NULL && cg->is_virtual()) {698Node* cast = cast_not_null(receiver);699// %%% assert(receiver == cast, "should already have cast the receiver");700}701702ciType* rtype = cg->method()->return_type();703ciType* ctype = declared_signature->return_type();704705if (Bytecodes::has_optional_appendix(iter().cur_bc_raw()) || is_signature_polymorphic) {706// Be careful here with return types.707if (ctype != rtype) {708BasicType rt = rtype->basic_type();709BasicType ct = ctype->basic_type();710if (ct == T_VOID) {711// It's OK for a method to return a value that is discarded.712// The discarding does not require any special action from the caller.713// The Java code knows this, at VerifyType.isNullConversion.714pop_node(rt); // whatever it was, pop it715} else if (rt == T_INT || is_subword_type(rt)) {716// Nothing. These cases are handled in lambda form bytecode.717assert(ct == T_INT || is_subword_type(ct), "must match: rt=%s, ct=%s", type2name(rt), type2name(ct));718} else if (is_reference_type(rt)) {719assert(is_reference_type(ct), "rt=%s, ct=%s", type2name(rt), type2name(ct));720if (ctype->is_loaded()) {721const TypeOopPtr* arg_type = TypeOopPtr::make_from_klass(rtype->as_klass());722const Type* sig_type = TypeOopPtr::make_from_klass(ctype->as_klass());723if (arg_type != NULL && !arg_type->higher_equal(sig_type)) {724Node* retnode = pop();725Node* cast_obj = _gvn.transform(new CheckCastPPNode(control(), retnode, sig_type));726push(cast_obj);727}728}729} else {730assert(rt == ct, "unexpected mismatch: rt=%s, ct=%s", type2name(rt), type2name(ct));731// push a zero; it's better than getting an oop/int mismatch732pop_node(rt);733Node* retnode = zerocon(ct);734push_node(ct, retnode);735}736// Now that the value is well-behaved, continue with the call-site type.737rtype = ctype;738}739} else {740// Symbolic resolution enforces the types to be the same.741// NOTE: We must relax the assert for unloaded types because two742// different ciType instances of the same unloaded class type743// can appear to be "loaded" by different loaders (depending on744// the accessing class).745assert(!rtype->is_loaded() || !ctype->is_loaded() || rtype == ctype,746"mismatched return types: rtype=%s, ctype=%s", rtype->name(), ctype->name());747}748749// If the return type of the method is not loaded, assert that the750// value we got is a null. Otherwise, we need to recompile.751if (!rtype->is_loaded()) {752if (PrintOpto && (Verbose || WizardMode)) {753method()->print_name(); tty->print_cr(" asserting nullness of result at bci: %d", bci());754cg->method()->print_name(); tty->cr();755}756if (C->log() != NULL) {757C->log()->elem("assert_null reason='return' klass='%d'",758C->log()->identify(rtype));759}760// If there is going to be a trap, put it at the next bytecode:761set_bci(iter().next_bci());762null_assert(peek());763set_bci(iter().cur_bci()); // put it back764}765BasicType ct = ctype->basic_type();766if (is_reference_type(ct)) {767record_profiled_return_for_speculation();768}769}770771// Restart record of parsing work after possible inlining of call772#ifndef PRODUCT773parse_histogram()->set_initial_state(bc());774#endif775}776777//---------------------------catch_call_exceptions-----------------------------778// Put a Catch and CatchProj nodes behind a just-created call.779// Send their caught exceptions to the proper handler.780// This may be used after a call to the rethrow VM stub,781// when it is needed to process unloaded exception classes.782void Parse::catch_call_exceptions(ciExceptionHandlerStream& handlers) {783// Exceptions are delivered through this channel:784Node* i_o = this->i_o();785786// Add a CatchNode.787GrowableArray<int>* bcis = new (C->node_arena()) GrowableArray<int>(C->node_arena(), 8, 0, -1);788GrowableArray<const Type*>* extypes = new (C->node_arena()) GrowableArray<const Type*>(C->node_arena(), 8, 0, NULL);789GrowableArray<int>* saw_unloaded = new (C->node_arena()) GrowableArray<int>(C->node_arena(), 8, 0, 0);790791bool default_handler = false;792for (; !handlers.is_done(); handlers.next()) {793ciExceptionHandler* h = handlers.handler();794int h_bci = h->handler_bci();795ciInstanceKlass* h_klass = h->is_catch_all() ? env()->Throwable_klass() : h->catch_klass();796// Do not introduce unloaded exception types into the graph:797if (!h_klass->is_loaded()) {798if (saw_unloaded->contains(h_bci)) {799/* We've already seen an unloaded exception with h_bci,800so don't duplicate. Duplication will cause the CatchNode to be801unnecessarily large. See 4713716. */802continue;803} else {804saw_unloaded->append(h_bci);805}806}807const Type* h_extype = TypeOopPtr::make_from_klass(h_klass);808// (We use make_from_klass because it respects UseUniqueSubclasses.)809h_extype = h_extype->join(TypeInstPtr::NOTNULL);810assert(!h_extype->empty(), "sanity");811// Note: It's OK if the BCIs repeat themselves.812bcis->append(h_bci);813extypes->append(h_extype);814if (h_bci == -1) {815default_handler = true;816}817}818819if (!default_handler) {820bcis->append(-1);821extypes->append(TypeOopPtr::make_from_klass(env()->Throwable_klass())->is_instptr());822}823824int len = bcis->length();825CatchNode *cn = new CatchNode(control(), i_o, len+1);826Node *catch_ = _gvn.transform(cn);827828// now branch with the exception state to each of the (potential)829// handlers830for(int i=0; i < len; i++) {831// Setup JVM state to enter the handler.832PreserveJVMState pjvms(this);833// Locals are just copied from before the call.834// Get control from the CatchNode.835int handler_bci = bcis->at(i);836Node* ctrl = _gvn.transform( new CatchProjNode(catch_, i+1,handler_bci));837// This handler cannot happen?838if (ctrl == top()) continue;839set_control(ctrl);840841// Create exception oop842const TypeInstPtr* extype = extypes->at(i)->is_instptr();843Node *ex_oop = _gvn.transform(new CreateExNode(extypes->at(i), ctrl, i_o));844845// Handle unloaded exception classes.846if (saw_unloaded->contains(handler_bci)) {847// An unloaded exception type is coming here. Do an uncommon trap.848#ifndef PRODUCT849// We do not expect the same handler bci to take both cold unloaded850// and hot loaded exceptions. But, watch for it.851if ((Verbose || WizardMode) && extype->is_loaded()) {852tty->print("Warning: Handler @%d takes mixed loaded/unloaded exceptions in ", bci());853method()->print_name(); tty->cr();854} else if (PrintOpto && (Verbose || WizardMode)) {855tty->print("Bailing out on unloaded exception type ");856extype->klass()->print_name();857tty->print(" at bci:%d in ", bci());858method()->print_name(); tty->cr();859}860#endif861// Emit an uncommon trap instead of processing the block.862set_bci(handler_bci);863push_ex_oop(ex_oop);864uncommon_trap(Deoptimization::Reason_unloaded,865Deoptimization::Action_reinterpret,866extype->klass(), "!loaded exception");867set_bci(iter().cur_bci()); // put it back868continue;869}870871// go to the exception handler872if (handler_bci < 0) { // merge with corresponding rethrow node873throw_to_exit(make_exception_state(ex_oop));874} else { // Else jump to corresponding handle875push_ex_oop(ex_oop); // Clear stack and push just the oop.876merge_exception(handler_bci);877}878}879880// The first CatchProj is for the normal return.881// (Note: If this is a call to rethrow_Java, this node goes dead.)882set_control(_gvn.transform( new CatchProjNode(catch_, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci)));883}884885886//----------------------------catch_inline_exceptions--------------------------887// Handle all exceptions thrown by an inlined method or individual bytecode.888// Common case 1: we have no handler, so all exceptions merge right into889// the rethrow case.890// Case 2: we have some handlers, with loaded exception klasses that have891// no subklasses. We do a Deutsch-Shiffman style type-check on the incoming892// exception oop and branch to the handler directly.893// Case 3: We have some handlers with subklasses or are not loaded at894// compile-time. We have to call the runtime to resolve the exception.895// So we insert a RethrowCall and all the logic that goes with it.896void Parse::catch_inline_exceptions(SafePointNode* ex_map) {897// Caller is responsible for saving away the map for normal control flow!898assert(stopped(), "call set_map(NULL) first");899assert(method()->has_exception_handlers(), "don't come here w/o work to do");900901Node* ex_node = saved_ex_oop(ex_map);902if (ex_node == top()) {903// No action needed.904return;905}906const TypeInstPtr* ex_type = _gvn.type(ex_node)->isa_instptr();907NOT_PRODUCT(if (ex_type==NULL) tty->print_cr("*** Exception not InstPtr"));908if (ex_type == NULL)909ex_type = TypeOopPtr::make_from_klass(env()->Throwable_klass())->is_instptr();910911// determine potential exception handlers912ciExceptionHandlerStream handlers(method(), bci(),913ex_type->klass()->as_instance_klass(),914ex_type->klass_is_exact());915916// Start executing from the given throw state. (Keep its stack, for now.)917// Get the exception oop as known at compile time.918ex_node = use_exception_state(ex_map);919920// Get the exception oop klass from its header921Node* ex_klass_node = NULL;922if (has_ex_handler() && !ex_type->klass_is_exact()) {923Node* p = basic_plus_adr( ex_node, ex_node, oopDesc::klass_offset_in_bytes());924ex_klass_node = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeInstPtr::KLASS, TypeKlassPtr::OBJECT));925926// Compute the exception klass a little more cleverly.927// Obvious solution is to simple do a LoadKlass from the 'ex_node'.928// However, if the ex_node is a PhiNode, I'm going to do a LoadKlass for929// each arm of the Phi. If I know something clever about the exceptions930// I'm loading the class from, I can replace the LoadKlass with the931// klass constant for the exception oop.932if (ex_node->is_Phi()) {933ex_klass_node = new PhiNode(ex_node->in(0), TypeKlassPtr::OBJECT);934for (uint i = 1; i < ex_node->req(); i++) {935Node* ex_in = ex_node->in(i);936if (ex_in == top() || ex_in == NULL) {937// This path was not taken.938ex_klass_node->init_req(i, top());939continue;940}941Node* p = basic_plus_adr(ex_in, ex_in, oopDesc::klass_offset_in_bytes());942Node* k = _gvn.transform( LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeInstPtr::KLASS, TypeKlassPtr::OBJECT));943ex_klass_node->init_req( i, k );944}945_gvn.set_type(ex_klass_node, TypeKlassPtr::OBJECT);946947}948}949950// Scan the exception table for applicable handlers.951// If none, we can call rethrow() and be done!952// If precise (loaded with no subklasses), insert a D.S. style953// pointer compare to the correct handler and loop back.954// If imprecise, switch to the Rethrow VM-call style handling.955956int remaining = handlers.count_remaining();957958// iterate through all entries sequentially959for (;!handlers.is_done(); handlers.next()) {960ciExceptionHandler* handler = handlers.handler();961962if (handler->is_rethrow()) {963// If we fell off the end of the table without finding an imprecise964// exception klass (and without finding a generic handler) then we965// know this exception is not handled in this method. We just rethrow966// the exception into the caller.967throw_to_exit(make_exception_state(ex_node));968return;969}970971// exception handler bci range covers throw_bci => investigate further972int handler_bci = handler->handler_bci();973974if (remaining == 1) {975push_ex_oop(ex_node); // Push exception oop for handler976if (PrintOpto && WizardMode) {977tty->print_cr(" Catching every inline exception bci:%d -> handler_bci:%d", bci(), handler_bci);978}979merge_exception(handler_bci); // jump to handler980return; // No more handling to be done here!981}982983// Get the handler's klass984ciInstanceKlass* klass = handler->catch_klass();985986if (!klass->is_loaded()) { // klass is not loaded?987// fall through into catch_call_exceptions which will emit a988// handler with an uncommon trap.989break;990}991992if (klass->is_interface()) // should not happen, but...993break; // bail out994995// Check the type of the exception against the catch type996const TypeKlassPtr *tk = TypeKlassPtr::make(klass);997Node* con = _gvn.makecon(tk);998Node* not_subtype_ctrl = gen_subtype_check(ex_klass_node, con);999if (!stopped()) {1000PreserveJVMState pjvms(this);1001const TypeInstPtr* tinst = TypeOopPtr::make_from_klass_unique(klass)->cast_to_ptr_type(TypePtr::NotNull)->is_instptr();1002assert(klass->has_subklass() || tinst->klass_is_exact(), "lost exactness");1003Node* ex_oop = _gvn.transform(new CheckCastPPNode(control(), ex_node, tinst));1004push_ex_oop(ex_oop); // Push exception oop for handler1005if (PrintOpto && WizardMode) {1006tty->print(" Catching inline exception bci:%d -> handler_bci:%d -- ", bci(), handler_bci);1007klass->print_name();1008tty->cr();1009}1010merge_exception(handler_bci);1011}1012set_control(not_subtype_ctrl);10131014// Come here if exception does not match handler.1015// Carry on with more handler checks.1016--remaining;1017}10181019assert(!stopped(), "you should return if you finish the chain");10201021// Oops, need to call into the VM to resolve the klasses at runtime.1022// Note: This call must not deoptimize, since it is not a real at this bci!1023kill_dead_locals();10241025make_runtime_call(RC_NO_LEAF | RC_MUST_THROW,1026OptoRuntime::rethrow_Type(),1027OptoRuntime::rethrow_stub(),1028NULL, NULL,1029ex_node);10301031// Rethrow is a pure call, no side effects, only a result.1032// The result cannot be allocated, so we use I_O10331034// Catch exceptions from the rethrow1035catch_call_exceptions(handlers);1036}103710381039// (Note: Moved add_debug_info into GraphKit::add_safepoint_edges.)104010411042#ifndef PRODUCT1043void Parse::count_compiled_calls(bool at_method_entry, bool is_inline) {1044if( CountCompiledCalls ) {1045if( at_method_entry ) {1046// bump invocation counter if top method (for statistics)1047if (CountCompiledCalls && depth() == 1) {1048const TypePtr* addr_type = TypeMetadataPtr::make(method());1049Node* adr1 = makecon(addr_type);1050Node* adr2 = basic_plus_adr(adr1, adr1, in_bytes(Method::compiled_invocation_counter_offset()));1051increment_counter(adr2);1052}1053} else if (is_inline) {1054switch (bc()) {1055case Bytecodes::_invokevirtual: increment_counter(SharedRuntime::nof_inlined_calls_addr()); break;1056case Bytecodes::_invokeinterface: increment_counter(SharedRuntime::nof_inlined_interface_calls_addr()); break;1057case Bytecodes::_invokestatic:1058case Bytecodes::_invokedynamic:1059case Bytecodes::_invokespecial: increment_counter(SharedRuntime::nof_inlined_static_calls_addr()); break;1060default: fatal("unexpected call bytecode");1061}1062} else {1063switch (bc()) {1064case Bytecodes::_invokevirtual: increment_counter(SharedRuntime::nof_normal_calls_addr()); break;1065case Bytecodes::_invokeinterface: increment_counter(SharedRuntime::nof_interface_calls_addr()); break;1066case Bytecodes::_invokestatic:1067case Bytecodes::_invokedynamic:1068case Bytecodes::_invokespecial: increment_counter(SharedRuntime::nof_static_calls_addr()); break;1069default: fatal("unexpected call bytecode");1070}1071}1072}1073}1074#endif //PRODUCT107510761077ciMethod* Compile::optimize_virtual_call(ciMethod* caller, ciInstanceKlass* klass,1078ciKlass* holder, ciMethod* callee,1079const TypeOopPtr* receiver_type, bool is_virtual,1080bool& call_does_dispatch, int& vtable_index,1081bool check_access) {1082// Set default values for out-parameters.1083call_does_dispatch = true;1084vtable_index = Method::invalid_vtable_index;10851086// Choose call strategy.1087ciMethod* optimized_virtual_method = optimize_inlining(caller, klass, holder, callee,1088receiver_type, check_access);10891090// Have the call been sufficiently improved such that it is no longer a virtual?1091if (optimized_virtual_method != NULL) {1092callee = optimized_virtual_method;1093call_does_dispatch = false;1094} else if (!UseInlineCaches && is_virtual && callee->is_loaded()) {1095// We can make a vtable call at this site1096vtable_index = callee->resolve_vtable_index(caller->holder(), holder);1097}1098return callee;1099}11001101// Identify possible target method and inlining style1102ciMethod* Compile::optimize_inlining(ciMethod* caller, ciInstanceKlass* klass, ciKlass* holder,1103ciMethod* callee, const TypeOopPtr* receiver_type,1104bool check_access) {1105// only use for virtual or interface calls11061107// If it is obviously final, do not bother to call find_monomorphic_target,1108// because the class hierarchy checks are not needed, and may fail due to1109// incompletely loaded classes. Since we do our own class loading checks1110// in this module, we may confidently bind to any method.1111if (callee->can_be_statically_bound()) {1112return callee;1113}11141115if (receiver_type == NULL) {1116return NULL; // no receiver type info1117}11181119// Attempt to improve the receiver1120bool actual_receiver_is_exact = false;1121ciInstanceKlass* actual_receiver = klass;1122// Array methods are all inherited from Object, and are monomorphic.1123// finalize() call on array is not allowed.1124if (receiver_type->isa_aryptr() &&1125callee->holder() == env()->Object_klass() &&1126callee->name() != ciSymbols::finalize_method_name()) {1127return callee;1128}11291130// All other interesting cases are instance klasses.1131if (!receiver_type->isa_instptr()) {1132return NULL;1133}11341135ciInstanceKlass* receiver_klass = receiver_type->klass()->as_instance_klass();1136if (receiver_klass->is_loaded() && receiver_klass->is_initialized() && !receiver_klass->is_interface() &&1137(receiver_klass == actual_receiver || receiver_klass->is_subtype_of(actual_receiver))) {1138// ikl is a same or better type than the original actual_receiver,1139// e.g. static receiver from bytecodes.1140actual_receiver = receiver_klass;1141// Is the actual_receiver exact?1142actual_receiver_is_exact = receiver_type->klass_is_exact();1143}11441145ciInstanceKlass* calling_klass = caller->holder();1146ciMethod* cha_monomorphic_target = callee->find_monomorphic_target(calling_klass, klass, actual_receiver, check_access);11471148if (cha_monomorphic_target != NULL) {1149// Hardwiring a virtual.1150assert(!callee->can_be_statically_bound(), "should have been handled earlier");1151assert(!cha_monomorphic_target->is_abstract(), "");1152if (!cha_monomorphic_target->can_be_statically_bound(actual_receiver)) {1153// If we inlined because CHA revealed only a single target method,1154// then we are dependent on that target method not getting overridden1155// by dynamic class loading. Be sure to test the "static" receiver1156// dest_method here, as opposed to the actual receiver, which may1157// falsely lead us to believe that the receiver is final or private.1158dependencies()->assert_unique_concrete_method(actual_receiver, cha_monomorphic_target, holder, callee);1159}1160return cha_monomorphic_target;1161}11621163// If the type is exact, we can still bind the method w/o a vcall.1164// (This case comes after CHA so we can see how much extra work it does.)1165if (actual_receiver_is_exact) {1166// In case of evolution, there is a dependence on every inlined method, since each1167// such method can be changed when its class is redefined.1168ciMethod* exact_method = callee->resolve_invoke(calling_klass, actual_receiver);1169if (exact_method != NULL) {1170return exact_method;1171}1172}11731174return NULL;1175}117611771178