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