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