1 /*
   2  * Copyright (c) 1998, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "ci/ciCallSite.hpp"
  27 #include "ci/ciMethodHandle.hpp"
  28 #include "ci/ciSymbols.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "compiler/compileBroker.hpp"
  31 #include "compiler/compileLog.hpp"
  32 #include "interpreter/linkResolver.hpp"
  33 #include "opto/addnode.hpp"
  34 #include "opto/callGenerator.hpp"
  35 #include "opto/castnode.hpp"
  36 #include "opto/cfgnode.hpp"
  37 #include "opto/inlinetypenode.hpp"
  38 #include "opto/mulnode.hpp"
  39 #include "opto/parse.hpp"
  40 #include "opto/rootnode.hpp"
  41 #include "opto/runtime.hpp"
  42 #include "opto/subnode.hpp"
  43 #include "prims/methodHandles.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "utilities/macros.hpp"
  46 #if INCLUDE_JFR
  47 #include "jfr/jfr.hpp"
  48 #endif
  49 
  50 void trace_type_profile(Compile* C, ciMethod *method, int depth, int bci, ciMethod *prof_method, ciKlass *prof_klass, int site_count, int receiver_count) {
  51   if (TraceTypeProfile || C->print_inlining()) {
  52     outputStream* out = tty;
  53     if (!C->print_inlining()) {
  54       if (!PrintOpto && !PrintCompilation) {
  55         method->print_short_name();
  56         tty->cr();
  57       }
  58       CompileTask::print_inlining_tty(prof_method, depth, bci);
  59     } else {
  60       out = C->print_inlining_stream();
  61     }
  62     CompileTask::print_inline_indent(depth, out);
  63     out->print(" \\-> TypeProfile (%d/%d counts) = ", receiver_count, site_count);
  64     stringStream ss;
  65     prof_klass->name()->print_symbol_on(&ss);
  66     out->print("%s", ss.freeze());
  67     out->cr();
  68   }
  69 }
  70 
  71 CallGenerator* Compile::call_generator(ciMethod* callee, int vtable_index, bool call_does_dispatch,
  72                                        JVMState* jvms, bool allow_inline,
  73                                        float prof_factor, ciKlass* speculative_receiver_type,
  74                                        bool allow_intrinsics) {
  75   assert(callee != NULL, "failed method resolution");
  76 
  77   ciMethod*       caller      = jvms->method();
  78   int             bci         = jvms->bci();
  79   Bytecodes::Code bytecode    = caller->java_code_at_bci(bci);
  80   ciMethod*       orig_callee = caller->get_method_at_bci(bci);
  81 
  82   const bool is_virtual_or_interface = (bytecode == Bytecodes::_invokevirtual) ||
  83                                        (bytecode == Bytecodes::_invokeinterface) ||
  84                                        (orig_callee->intrinsic_id() == vmIntrinsics::_linkToVirtual) ||
  85                                        (orig_callee->intrinsic_id() == vmIntrinsics::_linkToInterface);
  86 
  87   // Dtrace currently doesn't work unless all calls are vanilla
  88   if (env()->dtrace_method_probes()) {
  89     allow_inline = false;
  90   }
  91 
  92   // Note: When we get profiling during stage-1 compiles, we want to pull
  93   // from more specific profile data which pertains to this inlining.
  94   // Right now, ignore the information in jvms->caller(), and do method[bci].
  95   ciCallProfile profile = caller->call_profile_at_bci(bci);
  96 
  97   // See how many times this site has been invoked.
  98   int site_count = profile.count();
  99   int receiver_count = -1;
 100   if (call_does_dispatch && UseTypeProfile && profile.has_receiver(0)) {
 101     // Receivers in the profile structure are ordered by call counts
 102     // so that the most called (major) receiver is profile.receiver(0).
 103     receiver_count = profile.receiver_count(0);
 104   }
 105 
 106   CompileLog* log = this->log();
 107   if (log != NULL) {
 108     int rid = (receiver_count >= 0)? log->identify(profile.receiver(0)): -1;
 109     int r2id = (rid != -1 && profile.has_receiver(1))? log->identify(profile.receiver(1)):-1;
 110     log->begin_elem("call method='%d' count='%d' prof_factor='%f'",
 111                     log->identify(callee), site_count, prof_factor);
 112     if (call_does_dispatch)  log->print(" virtual='1'");
 113     if (allow_inline)     log->print(" inline='1'");
 114     if (receiver_count >= 0) {
 115       log->print(" receiver='%d' receiver_count='%d'", rid, receiver_count);
 116       if (profile.has_receiver(1)) {
 117         log->print(" receiver2='%d' receiver2_count='%d'", r2id, profile.receiver_count(1));
 118       }
 119     }
 120     if (callee->is_method_handle_intrinsic()) {
 121       log->print(" method_handle_intrinsic='1'");
 122     }
 123     log->end_elem();
 124   }
 125 
 126   // Special case the handling of certain common, profitable library
 127   // methods.  If these methods are replaced with specialized code,
 128   // then we return it as the inlined version of the call.
 129   CallGenerator* cg_intrinsic = NULL;
 130   if (allow_inline && allow_intrinsics) {
 131     CallGenerator* cg = find_intrinsic(callee, call_does_dispatch);
 132     if (cg != NULL) {
 133       if (cg->is_predicated()) {
 134         // Code without intrinsic but, hopefully, inlined.
 135         CallGenerator* inline_cg = this->call_generator(callee,
 136               vtable_index, call_does_dispatch, jvms, allow_inline, prof_factor, speculative_receiver_type, false);
 137         if (inline_cg != NULL) {
 138           cg = CallGenerator::for_predicated_intrinsic(cg, inline_cg);
 139         }
 140       }
 141 
 142       // If intrinsic does the virtual dispatch, we try to use the type profile
 143       // first, and hopefully inline it as the regular virtual call below.
 144       // We will retry the intrinsic if nothing had claimed it afterwards.
 145       if (cg->does_virtual_dispatch()) {
 146         cg_intrinsic = cg;
 147         cg = NULL;
 148       } else if (IncrementalInline && should_delay_vector_inlining(callee, jvms)) {
 149         return CallGenerator::for_late_inline(callee, cg);
 150       } else {
 151         return cg;
 152       }
 153     }
 154   }
 155 
 156   // Do method handle calls.
 157   // NOTE: This must happen before normal inlining logic below since
 158   // MethodHandle.invoke* are native methods which obviously don't
 159   // have bytecodes and so normal inlining fails.
 160   if (callee->is_method_handle_intrinsic()) {
 161     CallGenerator* cg = CallGenerator::for_method_handle_call(jvms, caller, callee, allow_inline);
 162     return cg;
 163   }
 164 
 165   // Attempt to inline...
 166   if (allow_inline) {
 167     // The profile data is only partly attributable to this caller,
 168     // scale back the call site information.
 169     float past_uses = jvms->method()->scale_count(site_count, prof_factor);
 170     // This is the number of times we expect the call code to be used.
 171     float expected_uses = past_uses;
 172 
 173     // Try inlining a bytecoded method:
 174     if (!call_does_dispatch) {
 175       InlineTree* ilt = InlineTree::find_subtree_from_root(this->ilt(), jvms->caller(), jvms->method());
 176       bool should_delay = AlwaysIncrementalInline;
 177       if (ilt->ok_to_inline(callee, jvms, profile, should_delay)) {
 178         CallGenerator* cg = CallGenerator::for_inline(callee, expected_uses);
 179         // For optimized virtual calls assert at runtime that receiver object
 180         // is a subtype of the inlined method holder. CHA can report a method
 181         // as a unique target under an abstract method, but receiver type
 182         // sometimes has a broader type. Similar scenario is possible with
 183         // default methods when type system loses information about implemented
 184         // interfaces.
 185         if (cg != NULL && is_virtual_or_interface && !callee->is_static()) {
 186           CallGenerator* trap_cg = CallGenerator::for_uncommon_trap(callee,
 187               Deoptimization::Reason_receiver_constraint, Deoptimization::Action_none);
 188 
 189           cg = CallGenerator::for_guarded_call(callee->holder(), trap_cg, cg);
 190         }
 191         if (cg != NULL) {
 192           // Delay the inlining of this method to give us the
 193           // opportunity to perform some high level optimizations
 194           // first.
 195           if (should_delay_string_inlining(callee, jvms)) {
 196             return CallGenerator::for_string_late_inline(callee, cg);
 197           } else if (should_delay_boxing_inlining(callee, jvms)) {
 198             return CallGenerator::for_boxing_late_inline(callee, cg);
 199           } else if (should_delay_vector_reboxing_inlining(callee, jvms)) {
 200             return CallGenerator::for_vector_reboxing_late_inline(callee, cg);
 201           } else if (should_delay) {
 202             return CallGenerator::for_late_inline(callee, cg);
 203           } else {
 204             return cg;
 205           }
 206         }
 207       }
 208     }
 209 
 210     // Try using the type profile.
 211     if (call_does_dispatch && site_count > 0 && UseTypeProfile) {
 212       // The major receiver's count >= TypeProfileMajorReceiverPercent of site_count.
 213       bool have_major_receiver = profile.has_receiver(0) && (100.*profile.receiver_prob(0) >= (float)TypeProfileMajorReceiverPercent);
 214       ciMethod* receiver_method = NULL;
 215 
 216       int morphism = profile.morphism();
 217       if (speculative_receiver_type != NULL) {
 218         if (!too_many_traps_or_recompiles(caller, bci, Deoptimization::Reason_speculate_class_check)) {
 219           // We have a speculative type, we should be able to resolve
 220           // the call. We do that before looking at the profiling at
 221           // this invoke because it may lead to bimorphic inlining which
 222           // a speculative type should help us avoid.
 223           receiver_method = callee->resolve_invoke(jvms->method()->holder(),
 224                                                    speculative_receiver_type);
 225           if (receiver_method == NULL) {
 226             speculative_receiver_type = NULL;
 227           } else {
 228             morphism = 1;
 229           }
 230         } else {
 231           // speculation failed before. Use profiling at the call
 232           // (could allow bimorphic inlining for instance).
 233           speculative_receiver_type = NULL;
 234         }
 235       }
 236       if (receiver_method == NULL &&
 237           (have_major_receiver || morphism == 1 ||
 238            (morphism == 2 && UseBimorphicInlining))) {
 239         // receiver_method = profile.method();
 240         // Profiles do not suggest methods now.  Look it up in the major receiver.
 241         receiver_method = callee->resolve_invoke(jvms->method()->holder(),
 242                                                       profile.receiver(0));
 243       }
 244       if (receiver_method != NULL) {
 245         // The single majority receiver sufficiently outweighs the minority.
 246         CallGenerator* hit_cg = this->call_generator(receiver_method,
 247               vtable_index, !call_does_dispatch, jvms, allow_inline, prof_factor);
 248         if (hit_cg != NULL) {
 249           // Look up second receiver.
 250           CallGenerator* next_hit_cg = NULL;
 251           ciMethod* next_receiver_method = NULL;
 252           if (morphism == 2 && UseBimorphicInlining) {
 253             next_receiver_method = callee->resolve_invoke(jvms->method()->holder(),
 254                                                                profile.receiver(1));
 255             if (next_receiver_method != NULL) {
 256               next_hit_cg = this->call_generator(next_receiver_method,
 257                                   vtable_index, !call_does_dispatch, jvms,
 258                                   allow_inline, prof_factor);
 259               if (next_hit_cg != NULL && !next_hit_cg->is_inline() &&
 260                   have_major_receiver && UseOnlyInlinedBimorphic) {
 261                   // Skip if we can't inline second receiver's method
 262                   next_hit_cg = NULL;
 263               }
 264             }
 265           }
 266           CallGenerator* miss_cg;
 267           Deoptimization::DeoptReason reason = (morphism == 2
 268                                                ? Deoptimization::Reason_bimorphic
 269                                                : Deoptimization::reason_class_check(speculative_receiver_type != NULL));
 270           if ((morphism == 1 || (morphism == 2 && next_hit_cg != NULL)) &&
 271               !too_many_traps_or_recompiles(caller, bci, reason)
 272              ) {
 273             // Generate uncommon trap for class check failure path
 274             // in case of monomorphic or bimorphic virtual call site.
 275             miss_cg = CallGenerator::for_uncommon_trap(callee, reason,
 276                         Deoptimization::Action_maybe_recompile);
 277           } else {
 278             // Generate virtual call for class check failure path
 279             // in case of polymorphic virtual call site.
 280             miss_cg = (IncrementalInlineVirtual ? CallGenerator::for_late_inline_virtual(callee, vtable_index, prof_factor)
 281                                                 : CallGenerator::for_virtual_call(callee, vtable_index));
 282           }
 283           if (miss_cg != NULL) {
 284             if (next_hit_cg != NULL) {
 285               assert(speculative_receiver_type == NULL, "shouldn't end up here if we used speculation");
 286               trace_type_profile(C, jvms->method(), jvms->depth() - 1, jvms->bci(), next_receiver_method, profile.receiver(1), site_count, profile.receiver_count(1));
 287               // We don't need to record dependency on a receiver here and below.
 288               // Whenever we inline, the dependency is added by Parse::Parse().
 289               miss_cg = CallGenerator::for_predicted_call(profile.receiver(1), miss_cg, next_hit_cg, PROB_MAX);
 290             }
 291             if (miss_cg != NULL) {
 292               ciKlass* k = speculative_receiver_type != NULL ? speculative_receiver_type : profile.receiver(0);
 293               trace_type_profile(C, jvms->method(), jvms->depth() - 1, jvms->bci(), receiver_method, k, site_count, receiver_count);
 294               float hit_prob = speculative_receiver_type != NULL ? 1.0 : profile.receiver_prob(0);
 295               CallGenerator* cg = CallGenerator::for_predicted_call(k, miss_cg, hit_cg, hit_prob);
 296               if (cg != NULL)  return cg;
 297             }
 298           }
 299         }
 300       }
 301     }
 302 
 303     // If there is only one implementor of this interface then we
 304     // may be able to bind this invoke directly to the implementing
 305     // klass but we need both a dependence on the single interface
 306     // and on the method we bind to. Additionally since all we know
 307     // about the receiver type is that it's supposed to implement the
 308     // interface we have to insert a check that it's the class we
 309     // expect.  Interface types are not checked by the verifier so
 310     // they are roughly equivalent to Object.
 311     // The number of implementors for declared_interface is less or
 312     // equal to the number of implementors for target->holder() so
 313     // if number of implementors of target->holder() == 1 then
 314     // number of implementors for decl_interface is 0 or 1. If
 315     // it's 0 then no class implements decl_interface and there's
 316     // no point in inlining.
 317     if (call_does_dispatch && bytecode == Bytecodes::_invokeinterface) {
 318       ciInstanceKlass* declared_interface =
 319           caller->get_declared_method_holder_at_bci(bci)->as_instance_klass();
 320       ciInstanceKlass* singleton = declared_interface->unique_implementor();
 321 
 322       if (singleton != NULL) {
 323         assert(singleton != declared_interface, "not a unique implementor");
 324 
 325         ciMethod* cha_monomorphic_target =
 326             callee->find_monomorphic_target(caller->holder(), declared_interface, singleton);
 327 
 328         if (cha_monomorphic_target != NULL &&
 329             cha_monomorphic_target->holder() != env()->Object_klass()) { // subtype check against Object is useless
 330           ciKlass* holder = cha_monomorphic_target->holder();
 331 
 332           // Try to inline the method found by CHA. Inlined method is guarded by the type check.
 333           CallGenerator* hit_cg = call_generator(cha_monomorphic_target,
 334               vtable_index, !call_does_dispatch, jvms, allow_inline, prof_factor);
 335 
 336           // Deoptimize on type check fail. The interpreter will throw ICCE for us.
 337           CallGenerator* miss_cg = CallGenerator::for_uncommon_trap(callee,
 338               Deoptimization::Reason_class_check, Deoptimization::Action_none);
 339 
 340           ciKlass* constraint = (holder->is_subclass_of(singleton) ? holder : singleton); // avoid upcasts
 341           CallGenerator* cg = CallGenerator::for_guarded_call(constraint, miss_cg, hit_cg);
 342           if (hit_cg != NULL && cg != NULL) {
 343             dependencies()->assert_unique_implementor(declared_interface, singleton);
 344             dependencies()->assert_unique_concrete_method(declared_interface, cha_monomorphic_target, declared_interface, callee);
 345             return cg;
 346           }
 347         }
 348       }
 349     } // call_does_dispatch && bytecode == Bytecodes::_invokeinterface
 350 
 351     // Nothing claimed the intrinsic, we go with straight-forward inlining
 352     // for already discovered intrinsic.
 353     if (allow_intrinsics && cg_intrinsic != NULL) {
 354       assert(cg_intrinsic->does_virtual_dispatch(), "sanity");
 355       return cg_intrinsic;
 356     }
 357   } // allow_inline
 358 
 359   // There was no special inlining tactic, or it bailed out.
 360   // Use a more generic tactic, like a simple call.
 361   if (call_does_dispatch) {
 362     const char* msg = "virtual call";
 363     if (C->print_inlining()) {
 364       print_inlining(callee, jvms->depth() - 1, jvms->bci(), msg);
 365     }
 366     C->log_inline_failure(msg);
 367     if (IncrementalInlineVirtual && allow_inline) {
 368       return CallGenerator::for_late_inline_virtual(callee, vtable_index, prof_factor); // attempt to inline through virtual call later
 369     } else {
 370       return CallGenerator::for_virtual_call(callee, vtable_index);
 371     }
 372   } else {
 373     // Class Hierarchy Analysis or Type Profile reveals a unique target, or it is a static or special call.
 374     CallGenerator* cg = CallGenerator::for_direct_call(callee, should_delay_inlining(callee, jvms));
 375     // For optimized virtual calls assert at runtime that receiver object
 376     // is a subtype of the method holder.
 377     if (cg != NULL && is_virtual_or_interface && !callee->is_static()) {
 378       CallGenerator* trap_cg = CallGenerator::for_uncommon_trap(callee,
 379           Deoptimization::Reason_receiver_constraint, Deoptimization::Action_none);
 380       cg = CallGenerator::for_guarded_call(callee->holder(), trap_cg, cg);
 381     }
 382     return cg;
 383   }
 384 }
 385 
 386 // Return true for methods that shouldn't be inlined early so that
 387 // they are easier to analyze and optimize as intrinsics.
 388 bool Compile::should_delay_string_inlining(ciMethod* call_method, JVMState* jvms) {
 389   if (has_stringbuilder()) {
 390 
 391     if ((call_method->holder() == C->env()->StringBuilder_klass() ||
 392          call_method->holder() == C->env()->StringBuffer_klass()) &&
 393         (jvms->method()->holder() == C->env()->StringBuilder_klass() ||
 394          jvms->method()->holder() == C->env()->StringBuffer_klass())) {
 395       // Delay SB calls only when called from non-SB code
 396       return false;
 397     }
 398 
 399     switch (call_method->intrinsic_id()) {
 400       case vmIntrinsics::_StringBuilder_void:
 401       case vmIntrinsics::_StringBuilder_int:
 402       case vmIntrinsics::_StringBuilder_String:
 403       case vmIntrinsics::_StringBuilder_append_char:
 404       case vmIntrinsics::_StringBuilder_append_int:
 405       case vmIntrinsics::_StringBuilder_append_String:
 406       case vmIntrinsics::_StringBuilder_toString:
 407       case vmIntrinsics::_StringBuffer_void:
 408       case vmIntrinsics::_StringBuffer_int:
 409       case vmIntrinsics::_StringBuffer_String:
 410       case vmIntrinsics::_StringBuffer_append_char:
 411       case vmIntrinsics::_StringBuffer_append_int:
 412       case vmIntrinsics::_StringBuffer_append_String:
 413       case vmIntrinsics::_StringBuffer_toString:
 414       case vmIntrinsics::_Integer_toString:
 415         return true;
 416 
 417       case vmIntrinsics::_String_String:
 418         {
 419           Node* receiver = jvms->map()->in(jvms->argoff() + 1);
 420           if (receiver->is_Proj() && receiver->in(0)->is_CallStaticJava()) {
 421             CallStaticJavaNode* csj = receiver->in(0)->as_CallStaticJava();
 422             ciMethod* m = csj->method();
 423             if (m != NULL &&
 424                 (m->intrinsic_id() == vmIntrinsics::_StringBuffer_toString ||
 425                  m->intrinsic_id() == vmIntrinsics::_StringBuilder_toString))
 426               // Delay String.<init>(new SB())
 427               return true;
 428           }
 429           return false;
 430         }
 431 
 432       default:
 433         return false;
 434     }
 435   }
 436   return false;
 437 }
 438 
 439 bool Compile::should_delay_boxing_inlining(ciMethod* call_method, JVMState* jvms) {
 440   if (eliminate_boxing() && call_method->is_boxing_method()) {
 441     set_has_boxed_value(true);
 442     return aggressive_unboxing();
 443   }
 444   return false;
 445 }
 446 
 447 bool Compile::should_delay_vector_inlining(ciMethod* call_method, JVMState* jvms) {
 448   return EnableVectorSupport && call_method->is_vector_method();
 449 }
 450 
 451 bool Compile::should_delay_vector_reboxing_inlining(ciMethod* call_method, JVMState* jvms) {
 452   return EnableVectorSupport && (call_method->intrinsic_id() == vmIntrinsics::_VectorRebox);
 453 }
 454 
 455 // uncommon-trap call-sites where callee is unloaded, uninitialized or will not link
 456 bool Parse::can_not_compile_call_site(ciMethod *dest_method, ciInstanceKlass* klass) {
 457   // Additional inputs to consider...
 458   // bc      = bc()
 459   // caller  = method()
 460   // iter().get_method_holder_index()
 461   assert( dest_method->is_loaded(), "ciTypeFlow should not let us get here" );
 462   // Interface classes can be loaded & linked and never get around to
 463   // being initialized.  Uncommon-trap for not-initialized static or
 464   // v-calls.  Let interface calls happen.
 465   ciInstanceKlass* holder_klass = dest_method->holder();
 466   if (!holder_klass->is_being_initialized() &&
 467       !holder_klass->is_initialized() &&
 468       !holder_klass->is_interface()) {
 469     uncommon_trap(Deoptimization::Reason_uninitialized,
 470                   Deoptimization::Action_reinterpret,
 471                   holder_klass);
 472     return true;
 473   }
 474 
 475   assert(dest_method->is_loaded(), "dest_method: typeflow responsibility");
 476   return false;
 477 }
 478 
 479 #ifdef ASSERT
 480 static bool check_call_consistency(JVMState* jvms, CallGenerator* cg) {
 481   ciMethod* symbolic_info = jvms->method()->get_method_at_bci(jvms->bci());
 482   ciMethod* resolved_method = cg->method();
 483   if (!ciMethod::is_consistent_info(symbolic_info, resolved_method)) {
 484     tty->print_cr("JVMS:");
 485     jvms->dump();
 486     tty->print_cr("Bytecode info:");
 487     jvms->method()->get_method_at_bci(jvms->bci())->print(); tty->cr();
 488     tty->print_cr("Resolved method:");
 489     cg->method()->print(); tty->cr();
 490     return false;
 491   }
 492   return true;
 493 }
 494 #endif // ASSERT
 495 
 496 //------------------------------do_call----------------------------------------
 497 // Handle your basic call.  Inline if we can & want to, else just setup call.
 498 void Parse::do_call() {
 499   // It's likely we are going to add debug info soon.
 500   // Also, if we inline a guy who eventually needs debug info for this JVMS,
 501   // our contribution to it is cleaned up right here.
 502   kill_dead_locals();
 503 
 504   C->print_inlining_assert_ready();
 505 
 506   // Set frequently used booleans
 507   const bool is_virtual = bc() == Bytecodes::_invokevirtual;
 508   const bool is_virtual_or_interface = is_virtual || bc() == Bytecodes::_invokeinterface;
 509   const bool has_receiver = Bytecodes::has_receiver(bc());
 510 
 511   // Find target being called
 512   bool             will_link;
 513   ciSignature*     declared_signature = NULL;
 514   ciMethod*        orig_callee  = iter().get_method(will_link, &declared_signature);  // callee in the bytecode
 515   ciInstanceKlass* holder_klass = orig_callee->holder();
 516   ciKlass*         holder       = iter().get_declared_method_holder();
 517   ciInstanceKlass* klass = ciEnv::get_instance_klass_for_declared_method_holder(holder);
 518   assert(declared_signature != NULL, "cannot be null");
 519   JFR_ONLY(Jfr::on_resolution(this, holder, orig_callee);)
 520 
 521   // Bump max node limit for JSR292 users
 522   if (bc() == Bytecodes::_invokedynamic || orig_callee->is_method_handle_intrinsic()) {
 523     C->set_max_node_limit(3*MaxNodeLimit);
 524   }
 525 
 526   // uncommon-trap when callee is unloaded, uninitialized or will not link
 527   // bailout when too many arguments for register representation
 528   if (!will_link || can_not_compile_call_site(orig_callee, klass)) {
 529     if (PrintOpto && (Verbose || WizardMode)) {
 530       method()->print_name(); tty->print_cr(" can not compile call at bci %d to:", bci());
 531       orig_callee->print_name(); tty->cr();
 532     }
 533     return;
 534   }
 535   assert(holder_klass->is_loaded(), "");
 536   //assert((bc_callee->is_static() || is_invokedynamic) == !has_receiver , "must match bc");  // XXX invokehandle (cur_bc_raw)
 537   // Note: this takes into account invokeinterface of methods declared in java/lang/Object,
 538   // which should be invokevirtuals but according to the VM spec may be invokeinterfaces
 539   assert(holder_klass->is_interface() || holder_klass->super() == NULL || (bc() != Bytecodes::_invokeinterface), "must match bc");
 540   // Note:  In the absence of miranda methods, an abstract class K can perform
 541   // an invokevirtual directly on an interface method I.m if K implements I.
 542 
 543   // orig_callee is the resolved callee which's signature includes the
 544   // appendix argument.
 545   const int nargs = orig_callee->arg_size();
 546   const bool is_signature_polymorphic = MethodHandles::is_signature_polymorphic(orig_callee->intrinsic_id());
 547 
 548   // Push appendix argument (MethodType, CallSite, etc.), if one.
 549   if (iter().has_appendix()) {
 550     ciObject* appendix_arg = iter().get_appendix();
 551     const TypeOopPtr* appendix_arg_type = TypeOopPtr::make_from_constant(appendix_arg, /* require_const= */ true);
 552     Node* appendix_arg_node = _gvn.makecon(appendix_arg_type);
 553     push(appendix_arg_node);
 554   }
 555 
 556   // ---------------------
 557   // Does Class Hierarchy Analysis reveal only a single target of a v-call?
 558   // Then we may inline or make a static call, but become dependent on there being only 1 target.
 559   // Does the call-site type profile reveal only one receiver?
 560   // Then we may introduce a run-time check and inline on the path where it succeeds.
 561   // The other path may uncommon_trap, check for another receiver, or do a v-call.
 562 
 563   // Try to get the most accurate receiver type
 564   ciMethod* callee             = orig_callee;
 565   int       vtable_index       = Method::invalid_vtable_index;
 566   bool      call_does_dispatch = false;
 567 
 568   // Speculative type of the receiver if any
 569   ciKlass* speculative_receiver_type = NULL;
 570   if (is_virtual_or_interface) {
 571     Node* receiver_node             = stack(sp() - nargs);
 572     const TypeOopPtr* receiver_type = NULL;
 573     if (receiver_node->is_InlineType()) {
 574       receiver_type = TypeInstPtr::make(TypePtr::NotNull, _gvn.type(receiver_node)->inline_klass());
 575     } else {
 576       receiver_type = _gvn.type(receiver_node)->isa_oopptr();
 577     }
 578     // call_does_dispatch and vtable_index are out-parameters.  They might be changed.
 579     // For arrays, klass below is Object. When vtable calls are used,
 580     // resolving the call with Object would allow an illegal call to
 581     // finalize() on an array. We use holder instead: illegal calls to
 582     // finalize() won't be compiled as vtable calls (IC call
 583     // resolution will catch the illegal call) and the few legal calls
 584     // on array types won't be either.
 585     callee = C->optimize_virtual_call(method(), klass, holder, orig_callee,
 586                                       receiver_type, is_virtual,
 587                                       call_does_dispatch, vtable_index);  // out-parameters
 588     speculative_receiver_type = receiver_type != NULL ? receiver_type->speculative_type() : NULL;
 589   }
 590 
 591   // Additional receiver subtype checks for interface calls via invokespecial or invokeinterface.
 592   ciKlass* receiver_constraint = NULL;
 593   if (iter().cur_bc_raw() == Bytecodes::_invokespecial && !orig_callee->is_object_constructor()) {
 594     ciInstanceKlass* calling_klass = method()->holder();
 595     ciInstanceKlass* sender_klass = calling_klass;
 596     if (sender_klass->is_interface()) {
 597       receiver_constraint = sender_klass;
 598     }
 599   } else if (iter().cur_bc_raw() == Bytecodes::_invokeinterface && orig_callee->is_private()) {
 600     assert(holder->is_interface(), "How did we get a non-interface method here!");
 601     receiver_constraint = holder;
 602   }
 603 
 604   if (receiver_constraint != NULL) {
 605     Node* receiver_node = stack(sp() - nargs);
 606     Node* cls_node = makecon(TypeKlassPtr::make(receiver_constraint));
 607     Node* bad_type_ctrl = NULL;
 608     Node* casted_receiver = gen_checkcast(receiver_node, cls_node, &bad_type_ctrl);
 609     if (bad_type_ctrl != NULL) {
 610       PreserveJVMState pjvms(this);
 611       set_control(bad_type_ctrl);
 612       uncommon_trap(Deoptimization::Reason_class_check,
 613                     Deoptimization::Action_none);
 614     }
 615     if (stopped()) {
 616       return; // MUST uncommon-trap?
 617     }
 618     set_stack(sp() - nargs, casted_receiver);
 619   }
 620 
 621   // Note:  It's OK to try to inline a virtual call.
 622   // The call generator will not attempt to inline a polymorphic call
 623   // unless it knows how to optimize the receiver dispatch.
 624   bool try_inline = (C->do_inlining() || InlineAccessors);
 625 
 626   // ---------------------
 627   dec_sp(nargs);              // Temporarily pop args for JVM state of call
 628   JVMState* jvms = sync_jvms();
 629 
 630   // ---------------------
 631   // Decide call tactic.
 632   // This call checks with CHA, the interpreter profile, intrinsics table, etc.
 633   // It decides whether inlining is desirable or not.
 634   CallGenerator* cg = C->call_generator(callee, vtable_index, call_does_dispatch, jvms, try_inline, prof_factor(), speculative_receiver_type);
 635 
 636   // NOTE:  Don't use orig_callee and callee after this point!  Use cg->method() instead.
 637   orig_callee = callee = NULL;
 638 
 639   // ---------------------
 640   // Round double arguments before call
 641   round_double_arguments(cg->method());
 642 
 643   // Feed profiling data for arguments to the type system so it can
 644   // propagate it as speculative types
 645   record_profiled_arguments_for_speculation(cg->method(), bc());
 646 
 647 #ifndef PRODUCT
 648   // bump global counters for calls
 649   count_compiled_calls(/*at_method_entry*/ false, cg->is_inline());
 650 
 651   // Record first part of parsing work for this call
 652   parse_histogram()->record_change();
 653 #endif // not PRODUCT
 654 
 655   assert(jvms == this->jvms(), "still operating on the right JVMS");
 656   assert(jvms_in_sync(),       "jvms must carry full info into CG");
 657 
 658   // save across call, for a subsequent cast_not_null.
 659   Node* receiver = has_receiver ? argument(0) : NULL;
 660 
 661   // The extra CheckCastPPs for speculative types mess with PhaseStringOpts
 662   if (receiver != NULL && !receiver->is_InlineType() && !call_does_dispatch && !cg->is_string_late_inline()) {
 663     // Feed profiling data for a single receiver to the type system so
 664     // it can propagate it as a speculative type
 665     receiver = record_profiled_receiver_for_speculation(receiver);
 666   }
 667 
 668   JVMState* new_jvms = cg->generate(jvms);
 669   if (new_jvms == NULL) {
 670     // When inlining attempt fails (e.g., too many arguments),
 671     // it may contaminate the current compile state, making it
 672     // impossible to pull back and try again.  Once we call
 673     // cg->generate(), we are committed.  If it fails, the whole
 674     // compilation task is compromised.
 675     if (failing())  return;
 676 
 677     // This can happen if a library intrinsic is available, but refuses
 678     // the call site, perhaps because it did not match a pattern the
 679     // intrinsic was expecting to optimize. Should always be possible to
 680     // get a normal java call that may inline in that case
 681     cg = C->call_generator(cg->method(), vtable_index, call_does_dispatch, jvms, try_inline, prof_factor(), speculative_receiver_type, /* allow_intrinsics= */ false);
 682     new_jvms = cg->generate(jvms);
 683     if (new_jvms == NULL) {
 684       guarantee(failing(), "call failed to generate:  calls should work");
 685       return;
 686     }
 687   }
 688 
 689   if (cg->is_inline()) {
 690     // Accumulate has_loops estimate
 691     C->env()->notice_inlined_method(cg->method());
 692   }
 693 
 694   // Reset parser state from [new_]jvms, which now carries results of the call.
 695   // Return value (if any) is already pushed on the stack by the cg.
 696   add_exception_states_from(new_jvms);
 697   if (new_jvms->map()->control() == top()) {
 698     stop_and_kill_map();
 699   } else {
 700     assert(new_jvms->same_calls_as(jvms), "method/bci left unchanged");
 701     set_jvms(new_jvms);
 702   }
 703 
 704   assert(check_call_consistency(jvms, cg), "inconsistent info");
 705 
 706   if (!stopped()) {
 707     // This was some sort of virtual call, which did a null check for us.
 708     // Now we can assert receiver-not-null, on the normal return path.
 709     if (receiver != NULL && cg->is_virtual()) {
 710       Node* cast = cast_not_null(receiver);
 711       // %%% assert(receiver == cast, "should already have cast the receiver");
 712     }
 713 
 714     ciType* rtype = cg->method()->return_type();
 715     ciType* ctype = declared_signature->return_type();
 716 
 717     if (Bytecodes::has_optional_appendix(iter().cur_bc_raw()) || is_signature_polymorphic) {
 718       // Be careful here with return types.
 719       if (ctype != rtype) {
 720         BasicType rt = rtype->basic_type();
 721         BasicType ct = ctype->basic_type();
 722         if (ct == T_VOID) {
 723           // It's OK for a method to return a value that is discarded.
 724           // The discarding does not require any special action from the caller.
 725           // The Java code knows this, at VerifyType.isNullConversion.
 726           pop_node(rt);  // whatever it was, pop it
 727         } else if (rt == T_INT || is_subword_type(rt)) {
 728           // Nothing.  These cases are handled in lambda form bytecode.
 729           assert(ct == T_INT || is_subword_type(ct), "must match: rt=%s, ct=%s", type2name(rt), type2name(ct));
 730         } else if (is_reference_type(rt)) {
 731           assert(is_reference_type(ct), "rt=%s, ct=%s", type2name(rt), type2name(ct));
 732           if (ctype->is_loaded()) {
 733             const TypeOopPtr* arg_type = TypeOopPtr::make_from_klass(rtype->as_klass());
 734             const Type*       sig_type = TypeOopPtr::make_from_klass(ctype->as_klass());
 735             if (declared_signature->returns_null_free_inline_type()) {
 736               sig_type = sig_type->join_speculative(TypePtr::NOTNULL);
 737             }
 738             if (arg_type != NULL && !arg_type->higher_equal(sig_type) && !peek()->is_InlineType()) {
 739               Node* retnode = pop();
 740               Node* cast_obj = _gvn.transform(new CheckCastPPNode(control(), retnode, sig_type));
 741               push(cast_obj);
 742             }
 743           }
 744         } else {
 745           assert(rt == ct, "unexpected mismatch: rt=%s, ct=%s", type2name(rt), type2name(ct));
 746           // push a zero; it's better than getting an oop/int mismatch
 747           pop_node(rt);
 748           Node* retnode = zerocon(ct);
 749           push_node(ct, retnode);
 750         }
 751         // Now that the value is well-behaved, continue with the call-site type.
 752         rtype = ctype;
 753       }
 754     } else {
 755       // Symbolic resolution enforces the types to be the same.
 756       // NOTE: We must relax the assert for unloaded types because two
 757       // different ciType instances of the same unloaded class type
 758       // can appear to be "loaded" by different loaders (depending on
 759       // the accessing class).
 760       assert(!rtype->is_loaded() || !ctype->is_loaded() || rtype == ctype,
 761              "mismatched return types: rtype=%s, ctype=%s", rtype->name(), ctype->name());
 762     }
 763 
 764     // If the return type of the method is not loaded, assert that the
 765     // value we got is a null.  Otherwise, we need to recompile.
 766     if (!rtype->is_loaded()) {
 767       if (PrintOpto && (Verbose || WizardMode)) {
 768         method()->print_name(); tty->print_cr(" asserting nullness of result at bci: %d", bci());
 769         cg->method()->print_name(); tty->cr();
 770       }
 771       if (C->log() != NULL) {
 772         C->log()->elem("assert_null reason='return' klass='%d'",
 773                        C->log()->identify(rtype));
 774       }
 775       // If there is going to be a trap, put it at the next bytecode:
 776       set_bci(iter().next_bci());
 777       null_assert(peek());
 778       set_bci(iter().cur_bci()); // put it back
 779     }
 780     BasicType ct = ctype->basic_type();
 781     if (is_reference_type(ct)) {
 782       record_profiled_return_for_speculation();
 783     }
 784     if (rtype->basic_type() == T_PRIMITIVE_OBJECT && !peek()->is_InlineTypeBase()) {
 785       Node* retnode = pop();
 786       retnode = InlineTypeNode::make_from_oop(this, retnode, rtype->as_inline_klass(), !gvn().type(retnode)->maybe_null());
 787       push_node(T_PRIMITIVE_OBJECT, retnode);
 788     }
 789   }
 790 
 791   // Restart record of parsing work after possible inlining of call
 792 #ifndef PRODUCT
 793   parse_histogram()->set_initial_state(bc());
 794 #endif
 795 }
 796 
 797 //---------------------------catch_call_exceptions-----------------------------
 798 // Put a Catch and CatchProj nodes behind a just-created call.
 799 // Send their caught exceptions to the proper handler.
 800 // This may be used after a call to the rethrow VM stub,
 801 // when it is needed to process unloaded exception classes.
 802 void Parse::catch_call_exceptions(ciExceptionHandlerStream& handlers) {
 803   // Exceptions are delivered through this channel:
 804   Node* i_o = this->i_o();
 805 
 806   // Add a CatchNode.
 807   GrowableArray<int>* bcis = new (C->node_arena()) GrowableArray<int>(C->node_arena(), 8, 0, -1);
 808   GrowableArray<const Type*>* extypes = new (C->node_arena()) GrowableArray<const Type*>(C->node_arena(), 8, 0, NULL);
 809   GrowableArray<int>* saw_unloaded = new (C->node_arena()) GrowableArray<int>(C->node_arena(), 8, 0, 0);
 810 
 811   bool default_handler = false;
 812   for (; !handlers.is_done(); handlers.next()) {
 813     ciExceptionHandler* h        = handlers.handler();
 814     int                 h_bci    = h->handler_bci();
 815     ciInstanceKlass*    h_klass  = h->is_catch_all() ? env()->Throwable_klass() : h->catch_klass();
 816     // Do not introduce unloaded exception types into the graph:
 817     if (!h_klass->is_loaded()) {
 818       if (saw_unloaded->contains(h_bci)) {
 819         /* We've already seen an unloaded exception with h_bci,
 820            so don't duplicate. Duplication will cause the CatchNode to be
 821            unnecessarily large. See 4713716. */
 822         continue;
 823       } else {
 824         saw_unloaded->append(h_bci);
 825       }
 826     }
 827     const Type*         h_extype = TypeOopPtr::make_from_klass(h_klass);
 828     // (We use make_from_klass because it respects UseUniqueSubclasses.)
 829     h_extype = h_extype->join(TypeInstPtr::NOTNULL);
 830     assert(!h_extype->empty(), "sanity");
 831     // Note:  It's OK if the BCIs repeat themselves.
 832     bcis->append(h_bci);
 833     extypes->append(h_extype);
 834     if (h_bci == -1) {
 835       default_handler = true;
 836     }
 837   }
 838 
 839   if (!default_handler) {
 840     bcis->append(-1);
 841     extypes->append(TypeOopPtr::make_from_klass(env()->Throwable_klass())->is_instptr());
 842   }
 843 
 844   int len = bcis->length();
 845   CatchNode *cn = new CatchNode(control(), i_o, len+1);
 846   Node *catch_ = _gvn.transform(cn);
 847 
 848   // now branch with the exception state to each of the (potential)
 849   // handlers
 850   for(int i=0; i < len; i++) {
 851     // Setup JVM state to enter the handler.
 852     PreserveJVMState pjvms(this);
 853     // Locals are just copied from before the call.
 854     // Get control from the CatchNode.
 855     int handler_bci = bcis->at(i);
 856     Node* ctrl = _gvn.transform( new CatchProjNode(catch_, i+1,handler_bci));
 857     // This handler cannot happen?
 858     if (ctrl == top())  continue;
 859     set_control(ctrl);
 860 
 861     // Create exception oop
 862     const TypeInstPtr* extype = extypes->at(i)->is_instptr();
 863     Node *ex_oop = _gvn.transform(new CreateExNode(extypes->at(i), ctrl, i_o));
 864 
 865     // Handle unloaded exception classes.
 866     if (saw_unloaded->contains(handler_bci)) {
 867       // An unloaded exception type is coming here.  Do an uncommon trap.
 868 #ifndef PRODUCT
 869       // We do not expect the same handler bci to take both cold unloaded
 870       // and hot loaded exceptions.  But, watch for it.
 871       if ((Verbose || WizardMode) && extype->is_loaded()) {
 872         tty->print("Warning: Handler @%d takes mixed loaded/unloaded exceptions in ", bci());
 873         method()->print_name(); tty->cr();
 874       } else if (PrintOpto && (Verbose || WizardMode)) {
 875         tty->print("Bailing out on unloaded exception type ");
 876         extype->instance_klass()->print_name();
 877         tty->print(" at bci:%d in ", bci());
 878         method()->print_name(); tty->cr();
 879       }
 880 #endif
 881       // Emit an uncommon trap instead of processing the block.
 882       set_bci(handler_bci);
 883       push_ex_oop(ex_oop);
 884       uncommon_trap(Deoptimization::Reason_unloaded,
 885                     Deoptimization::Action_reinterpret,
 886                     extype->instance_klass(), "!loaded exception");
 887       set_bci(iter().cur_bci()); // put it back
 888       continue;
 889     }
 890 
 891     // go to the exception handler
 892     if (handler_bci < 0) {     // merge with corresponding rethrow node
 893       throw_to_exit(make_exception_state(ex_oop));
 894     } else {                      // Else jump to corresponding handle
 895       push_ex_oop(ex_oop);        // Clear stack and push just the oop.
 896       merge_exception(handler_bci);
 897     }
 898   }
 899 
 900   // The first CatchProj is for the normal return.
 901   // (Note:  If this is a call to rethrow_Java, this node goes dead.)
 902   set_control(_gvn.transform( new CatchProjNode(catch_, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci)));
 903 }
 904 
 905 
 906 //----------------------------catch_inline_exceptions--------------------------
 907 // Handle all exceptions thrown by an inlined method or individual bytecode.
 908 // Common case 1: we have no handler, so all exceptions merge right into
 909 // the rethrow case.
 910 // Case 2: we have some handlers, with loaded exception klasses that have
 911 // no subklasses.  We do a Deutsch-Shiffman style type-check on the incoming
 912 // exception oop and branch to the handler directly.
 913 // Case 3: We have some handlers with subklasses or are not loaded at
 914 // compile-time.  We have to call the runtime to resolve the exception.
 915 // So we insert a RethrowCall and all the logic that goes with it.
 916 void Parse::catch_inline_exceptions(SafePointNode* ex_map) {
 917   // Caller is responsible for saving away the map for normal control flow!
 918   assert(stopped(), "call set_map(NULL) first");
 919   assert(method()->has_exception_handlers(), "don't come here w/o work to do");
 920 
 921   Node* ex_node = saved_ex_oop(ex_map);
 922   if (ex_node == top()) {
 923     // No action needed.
 924     return;
 925   }
 926   const TypeInstPtr* ex_type = _gvn.type(ex_node)->isa_instptr();
 927   NOT_PRODUCT(if (ex_type==NULL) tty->print_cr("*** Exception not InstPtr"));
 928   if (ex_type == NULL)
 929     ex_type = TypeOopPtr::make_from_klass(env()->Throwable_klass())->is_instptr();
 930 
 931   // determine potential exception handlers
 932   ciExceptionHandlerStream handlers(method(), bci(),
 933                                     ex_type->instance_klass(),
 934                                     ex_type->klass_is_exact());
 935 
 936   // Start executing from the given throw state.  (Keep its stack, for now.)
 937   // Get the exception oop as known at compile time.
 938   ex_node = use_exception_state(ex_map);
 939 
 940   // Get the exception oop klass from its header
 941   Node* ex_klass_node = NULL;
 942   if (has_ex_handler() && !ex_type->klass_is_exact()) {
 943     Node* p = basic_plus_adr( ex_node, ex_node, oopDesc::klass_offset_in_bytes());
 944     ex_klass_node = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
 945 
 946     // Compute the exception klass a little more cleverly.
 947     // Obvious solution is to simple do a LoadKlass from the 'ex_node'.
 948     // However, if the ex_node is a PhiNode, I'm going to do a LoadKlass for
 949     // each arm of the Phi.  If I know something clever about the exceptions
 950     // I'm loading the class from, I can replace the LoadKlass with the
 951     // klass constant for the exception oop.
 952     if (ex_node->is_Phi()) {
 953       ex_klass_node = new PhiNode(ex_node->in(0), TypeInstKlassPtr::OBJECT);
 954       for (uint i = 1; i < ex_node->req(); i++) {
 955         Node* ex_in = ex_node->in(i);
 956         if (ex_in == top() || ex_in == NULL) {
 957           // This path was not taken.
 958           ex_klass_node->init_req(i, top());
 959           continue;
 960         }
 961         Node* p = basic_plus_adr(ex_in, ex_in, oopDesc::klass_offset_in_bytes());
 962         Node* k = _gvn.transform( LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
 963         ex_klass_node->init_req( i, k );
 964       }
 965       _gvn.set_type(ex_klass_node, TypeInstKlassPtr::OBJECT);
 966 
 967     }
 968   }
 969 
 970   // Scan the exception table for applicable handlers.
 971   // If none, we can call rethrow() and be done!
 972   // If precise (loaded with no subklasses), insert a D.S. style
 973   // pointer compare to the correct handler and loop back.
 974   // If imprecise, switch to the Rethrow VM-call style handling.
 975 
 976   int remaining = handlers.count_remaining();
 977 
 978   // iterate through all entries sequentially
 979   for (;!handlers.is_done(); handlers.next()) {
 980     ciExceptionHandler* handler = handlers.handler();
 981 
 982     if (handler->is_rethrow()) {
 983       // If we fell off the end of the table without finding an imprecise
 984       // exception klass (and without finding a generic handler) then we
 985       // know this exception is not handled in this method.  We just rethrow
 986       // the exception into the caller.
 987       throw_to_exit(make_exception_state(ex_node));
 988       return;
 989     }
 990 
 991     // exception handler bci range covers throw_bci => investigate further
 992     int handler_bci = handler->handler_bci();
 993 
 994     if (remaining == 1) {
 995       push_ex_oop(ex_node);        // Push exception oop for handler
 996       if (PrintOpto && WizardMode) {
 997         tty->print_cr("  Catching every inline exception bci:%d -> handler_bci:%d", bci(), handler_bci);
 998       }
 999       merge_exception(handler_bci); // jump to handler
1000       return;                   // No more handling to be done here!
1001     }
1002 
1003     // Get the handler's klass
1004     ciInstanceKlass* klass = handler->catch_klass();
1005 
1006     if (!klass->is_loaded()) {  // klass is not loaded?
1007       // fall through into catch_call_exceptions which will emit a
1008       // handler with an uncommon trap.
1009       break;
1010     }
1011 
1012     if (klass->is_interface())  // should not happen, but...
1013       break;                    // bail out
1014 
1015     // Check the type of the exception against the catch type
1016     const TypeKlassPtr *tk = TypeKlassPtr::make(klass);
1017     Node* con = _gvn.makecon(tk);
1018     Node* not_subtype_ctrl = gen_subtype_check(ex_klass_node, con);
1019     if (!stopped()) {
1020       PreserveJVMState pjvms(this);
1021       const TypeInstPtr* tinst = TypeOopPtr::make_from_klass_unique(klass)->cast_to_ptr_type(TypePtr::NotNull)->is_instptr();
1022       assert(klass->has_subklass() || tinst->klass_is_exact(), "lost exactness");
1023       Node* ex_oop = _gvn.transform(new CheckCastPPNode(control(), ex_node, tinst));
1024       push_ex_oop(ex_oop);      // Push exception oop for handler
1025       if (PrintOpto && WizardMode) {
1026         tty->print("  Catching inline exception bci:%d -> handler_bci:%d -- ", bci(), handler_bci);
1027         klass->print_name();
1028         tty->cr();
1029       }
1030       merge_exception(handler_bci);
1031     }
1032     set_control(not_subtype_ctrl);
1033 
1034     // Come here if exception does not match handler.
1035     // Carry on with more handler checks.
1036     --remaining;
1037   }
1038 
1039   assert(!stopped(), "you should return if you finish the chain");
1040 
1041   // Oops, need to call into the VM to resolve the klasses at runtime.
1042   // Note:  This call must not deoptimize, since it is not a real at this bci!
1043   kill_dead_locals();
1044 
1045   make_runtime_call(RC_NO_LEAF | RC_MUST_THROW,
1046                     OptoRuntime::rethrow_Type(),
1047                     OptoRuntime::rethrow_stub(),
1048                     NULL, NULL,
1049                     ex_node);
1050 
1051   // Rethrow is a pure call, no side effects, only a result.
1052   // The result cannot be allocated, so we use I_O
1053 
1054   // Catch exceptions from the rethrow
1055   catch_call_exceptions(handlers);
1056 }
1057 
1058 
1059 // (Note:  Moved add_debug_info into GraphKit::add_safepoint_edges.)
1060 
1061 
1062 #ifndef PRODUCT
1063 void Parse::count_compiled_calls(bool at_method_entry, bool is_inline) {
1064   if( CountCompiledCalls ) {
1065     if( at_method_entry ) {
1066       // bump invocation counter if top method (for statistics)
1067       if (CountCompiledCalls && depth() == 1) {
1068         const TypePtr* addr_type = TypeMetadataPtr::make(method());
1069         Node* adr1 = makecon(addr_type);
1070         Node* adr2 = basic_plus_adr(adr1, adr1, in_bytes(Method::compiled_invocation_counter_offset()));
1071         increment_counter(adr2);
1072       }
1073     } else if (is_inline) {
1074       switch (bc()) {
1075       case Bytecodes::_invokevirtual:   increment_counter(SharedRuntime::nof_inlined_calls_addr()); break;
1076       case Bytecodes::_invokeinterface: increment_counter(SharedRuntime::nof_inlined_interface_calls_addr()); break;
1077       case Bytecodes::_invokestatic:
1078       case Bytecodes::_invokedynamic:
1079       case Bytecodes::_invokespecial:   increment_counter(SharedRuntime::nof_inlined_static_calls_addr()); break;
1080       default: fatal("unexpected call bytecode");
1081       }
1082     } else {
1083       switch (bc()) {
1084       case Bytecodes::_invokevirtual:   increment_counter(SharedRuntime::nof_normal_calls_addr()); break;
1085       case Bytecodes::_invokeinterface: increment_counter(SharedRuntime::nof_interface_calls_addr()); break;
1086       case Bytecodes::_invokestatic:
1087       case Bytecodes::_invokedynamic:
1088       case Bytecodes::_invokespecial:   increment_counter(SharedRuntime::nof_static_calls_addr()); break;
1089       default: fatal("unexpected call bytecode");
1090       }
1091     }
1092   }
1093 }
1094 #endif //PRODUCT
1095 
1096 
1097 ciMethod* Compile::optimize_virtual_call(ciMethod* caller, ciInstanceKlass* klass,
1098                                          ciKlass* holder, ciMethod* callee,
1099                                          const TypeOopPtr* receiver_type, bool is_virtual,
1100                                          bool& call_does_dispatch, int& vtable_index,
1101                                          bool check_access) {
1102   // Set default values for out-parameters.
1103   call_does_dispatch = true;
1104   vtable_index       = Method::invalid_vtable_index;
1105 
1106   // Choose call strategy.
1107   ciMethod* optimized_virtual_method = optimize_inlining(caller, klass, holder, callee,
1108                                                          receiver_type, check_access);
1109 
1110   // Have the call been sufficiently improved such that it is no longer a virtual?
1111   if (optimized_virtual_method != NULL) {
1112     callee             = optimized_virtual_method;
1113     call_does_dispatch = false;
1114   } else if (!UseInlineCaches && is_virtual && callee->is_loaded()) {
1115     // We can make a vtable call at this site
1116     vtable_index = callee->resolve_vtable_index(caller->holder(), holder);
1117   }
1118   return callee;
1119 }
1120 
1121 // Identify possible target method and inlining style
1122 ciMethod* Compile::optimize_inlining(ciMethod* caller, ciInstanceKlass* klass, ciKlass* holder,
1123                                      ciMethod* callee, const TypeOopPtr* receiver_type,
1124                                      bool check_access) {
1125   // only use for virtual or interface calls
1126 
1127   // If it is obviously final, do not bother to call find_monomorphic_target,
1128   // because the class hierarchy checks are not needed, and may fail due to
1129   // incompletely loaded classes.  Since we do our own class loading checks
1130   // in this module, we may confidently bind to any method.
1131   if (callee->can_be_statically_bound()) {
1132     return callee;
1133   }
1134 
1135   if (receiver_type == NULL) {
1136     return NULL; // no receiver type info
1137   }
1138 
1139   // Attempt to improve the receiver
1140   bool actual_receiver_is_exact = false;
1141   ciInstanceKlass* actual_receiver = klass;
1142   // Array methods are all inherited from Object, and are monomorphic.
1143   // finalize() call on array is not allowed.
1144   if (receiver_type->isa_aryptr() &&
1145       callee->holder() == env()->Object_klass() &&
1146       callee->name() != ciSymbols::finalize_method_name()) {
1147     return callee;
1148   }
1149 
1150   // All other interesting cases are instance klasses.
1151   if (!receiver_type->isa_instptr()) {
1152     return NULL;
1153   }
1154 
1155   ciInstanceKlass* receiver_klass = receiver_type->is_instptr()->instance_klass();
1156   if (receiver_klass->is_loaded() && receiver_klass->is_initialized() && !receiver_klass->is_interface() &&
1157       (receiver_klass == actual_receiver || receiver_klass->is_subtype_of(actual_receiver))) {
1158     // ikl is a same or better type than the original actual_receiver,
1159     // e.g. static receiver from bytecodes.
1160     actual_receiver = receiver_klass;
1161     // Is the actual_receiver exact?
1162     actual_receiver_is_exact = receiver_type->klass_is_exact();
1163   }
1164 
1165   ciInstanceKlass*   calling_klass = caller->holder();
1166   ciMethod* cha_monomorphic_target = callee->find_monomorphic_target(calling_klass, klass, actual_receiver, check_access);
1167 
1168   if (cha_monomorphic_target != NULL) {
1169     // Hardwiring a virtual.
1170     assert(!callee->can_be_statically_bound(), "should have been handled earlier");
1171     assert(!cha_monomorphic_target->is_abstract(), "");
1172     if (!cha_monomorphic_target->can_be_statically_bound(actual_receiver)) {
1173       // If we inlined because CHA revealed only a single target method,
1174       // then we are dependent on that target method not getting overridden
1175       // by dynamic class loading.  Be sure to test the "static" receiver
1176       // dest_method here, as opposed to the actual receiver, which may
1177       // falsely lead us to believe that the receiver is final or private.
1178       dependencies()->assert_unique_concrete_method(actual_receiver, cha_monomorphic_target, holder, callee);
1179     }
1180     return cha_monomorphic_target;
1181   }
1182 
1183   // If the type is exact, we can still bind the method w/o a vcall.
1184   // (This case comes after CHA so we can see how much extra work it does.)
1185   if (actual_receiver_is_exact) {
1186     // In case of evolution, there is a dependence on every inlined method, since each
1187     // such method can be changed when its class is redefined.
1188     ciMethod* exact_method = callee->resolve_invoke(calling_klass, actual_receiver);
1189     if (exact_method != NULL) {
1190       return exact_method;
1191     }
1192   }
1193 
1194   return NULL;
1195 }