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