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