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