1 /*
   2  * Copyright (c) 2000, 2015, 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/bcEscapeAnalyzer.hpp"
  27 #include "ci/ciCallSite.hpp"
  28 #include "ci/ciObjArray.hpp"
  29 #include "ci/ciMemberName.hpp"
  30 #include "ci/ciMethodHandle.hpp"
  31 #include "classfile/javaClasses.hpp"
  32 #include "compiler/compileLog.hpp"
  33 #include "opto/addnode.hpp"
  34 #include "opto/callGenerator.hpp"
  35 #include "opto/callnode.hpp"
  36 #include "opto/castnode.hpp"
  37 #include "opto/cfgnode.hpp"
  38 #include "opto/parse.hpp"
  39 #include "opto/rootnode.hpp"
  40 #include "opto/runtime.hpp"
  41 #include "opto/subnode.hpp"
  42 #include "opto/valuetypenode.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 
  45 // Utility function.
  46 const TypeFunc* CallGenerator::tf() const {
  47   return TypeFunc::make(method());
  48 }
  49 
  50 bool CallGenerator::is_inlined_mh_linker(JVMState* jvms, ciMethod* callee) {
  51   ciMethod* symbolic_info = jvms->method()->get_method_at_bci(jvms->bci());
  52   return symbolic_info->is_method_handle_intrinsic() && !callee->is_method_handle_intrinsic();
  53 }
  54 
  55 //-----------------------------ParseGenerator---------------------------------
  56 // Internal class which handles all direct bytecode traversal.
  57 class ParseGenerator : public InlineCallGenerator {
  58 private:
  59   bool  _is_osr;
  60   float _expected_uses;
  61 
  62 public:
  63   ParseGenerator(ciMethod* method, float expected_uses, bool is_osr = false)
  64     : InlineCallGenerator(method)
  65   {
  66     _is_osr        = is_osr;
  67     _expected_uses = expected_uses;
  68     assert(InlineTree::check_can_parse(method) == NULL, "parse must be possible");
  69   }
  70 
  71   virtual bool      is_parse() const           { return true; }
  72   virtual JVMState* generate(JVMState* jvms);
  73   int is_osr() { return _is_osr; }
  74 
  75 };
  76 
  77 JVMState* ParseGenerator::generate(JVMState* jvms) {
  78   Compile* C = Compile::current();
  79   C->print_inlining_update(this);
  80 
  81   if (is_osr()) {
  82     // The JVMS for a OSR has a single argument (see its TypeFunc).
  83     assert(jvms->depth() == 1, "no inline OSR");
  84   }
  85 
  86   if (C->failing()) {
  87     return NULL;  // bailing out of the compile; do not try to parse
  88   }
  89 
  90   Parse parser(jvms, method(), _expected_uses);
  91   // Grab signature for matching/allocation
  92 #ifdef ASSERT
  93   if (parser.tf() != (parser.depth() == 1 ? C->tf() : tf())) {
  94     MutexLockerEx ml(Compile_lock, Mutex::_no_safepoint_check_flag);
  95     assert(C->env()->system_dictionary_modification_counter_changed(),
  96            "Must invalidate if TypeFuncs differ");
  97   }
  98 #endif
  99 
 100   GraphKit& exits = parser.exits();
 101 
 102   if (C->failing()) {
 103     while (exits.pop_exception_state() != NULL) ;
 104     return NULL;
 105   }
 106 
 107   assert(exits.jvms()->same_calls_as(jvms), "sanity");
 108 
 109   // Simply return the exit state of the parser,
 110   // augmented by any exceptional states.
 111   return exits.transfer_exceptions_into_jvms();
 112 }
 113 
 114 //---------------------------DirectCallGenerator------------------------------
 115 // Internal class which handles all out-of-line calls w/o receiver type checks.
 116 class DirectCallGenerator : public CallGenerator {
 117  private:
 118   CallStaticJavaNode* _call_node;
 119   // Force separate memory and I/O projections for the exceptional
 120   // paths to facilitate late inlinig.
 121   bool                _separate_io_proj;
 122 
 123  public:
 124   DirectCallGenerator(ciMethod* method, bool separate_io_proj)
 125     : CallGenerator(method),
 126       _separate_io_proj(separate_io_proj)
 127   {
 128   }
 129   virtual JVMState* generate(JVMState* jvms);
 130 
 131   CallStaticJavaNode* call_node() const { return _call_node; }
 132 };
 133 
 134 JVMState* DirectCallGenerator::generate(JVMState* jvms) {
 135   GraphKit kit(jvms);
 136   kit.C->print_inlining_update(this);
 137   PhaseGVN& gvn = kit.gvn();
 138   bool is_static = method()->is_static();
 139   address target = is_static ? SharedRuntime::get_resolve_static_call_stub()
 140                              : SharedRuntime::get_resolve_opt_virtual_call_stub();
 141 
 142   if (kit.C->log() != NULL) {
 143     kit.C->log()->elem("direct_call bci='%d'", jvms->bci());
 144   }
 145 
 146   CallStaticJavaNode *call = new CallStaticJavaNode(kit.C, tf(), target, method(), kit.bci());
 147   if (is_inlined_mh_linker(jvms, method())) {
 148     // To be able to issue a direct call and skip a call to MH.linkTo*/invokeBasic adapter,
 149     // additional information about the method being invoked should be attached
 150     // to the call site to make resolution logic work
 151     // (see SharedRuntime::resolve_static_call_C).
 152     call->set_override_symbolic_info(true);
 153   }
 154   _call_node = call;  // Save the call node in case we need it later
 155   if (!is_static) {
 156     if (kit.argument(0)->is_ValueType()) {
 157       if (!ValueTypePassFieldsAsArgs) {
 158         ValueTypeNode* vt = kit.argument(0)->as_ValueType();
 159         vt->store_to_memory(&kit);
 160       }
 161     } else {
 162       // Make an explicit receiver null_check as part of this call.
 163       // Since we share a map with the caller, his JVMS gets adjusted.
 164       kit.null_check_receiver_before_call(method());
 165     }
 166     if (kit.stopped()) {
 167       // And dump it back to the caller, decorated with any exceptions:
 168       return kit.transfer_exceptions_into_jvms();
 169     }
 170     // Mark the call node as virtual, sort of:
 171     call->set_optimized_virtual(true);
 172     if (method()->is_method_handle_intrinsic() ||
 173         method()->is_compiled_lambda_form()) {
 174       call->set_method_handle_invoke(true);
 175     }
 176   }
 177   kit.set_arguments_for_java_call(call);
 178   kit.set_edges_for_java_call(call, false, _separate_io_proj);
 179   Node* ret = kit.set_results_for_java_call(call, _separate_io_proj);
 180   // Check if return value is a value type pointer
 181   if (gvn.type(ret)->isa_valuetypeptr()) {
 182     // Create ValueTypeNode from the oop and replace the return value
 183     Node* vt = ValueTypeNode::make(gvn, kit.merged_memory(), ret);
 184     kit.push_node(T_VALUETYPE, vt);
 185   } else {
 186     kit.push_node(method()->return_type()->basic_type(), ret);
 187   }
 188   return kit.transfer_exceptions_into_jvms();
 189 }
 190 
 191 //--------------------------VirtualCallGenerator------------------------------
 192 // Internal class which handles all out-of-line calls checking receiver type.
 193 class VirtualCallGenerator : public CallGenerator {
 194 private:
 195   int _vtable_index;
 196 public:
 197   VirtualCallGenerator(ciMethod* method, int vtable_index)
 198     : CallGenerator(method), _vtable_index(vtable_index)
 199   {
 200     assert(vtable_index == Method::invalid_vtable_index ||
 201            vtable_index >= 0, "either invalid or usable");
 202   }
 203   virtual bool      is_virtual() const          { return true; }
 204   virtual JVMState* generate(JVMState* jvms);
 205 };
 206 
 207 JVMState* VirtualCallGenerator::generate(JVMState* jvms) {
 208   GraphKit kit(jvms);
 209   Node* receiver = kit.argument(0);
 210   PhaseGVN& gvn = kit.gvn();
 211   kit.C->print_inlining_update(this);
 212 
 213   if (kit.C->log() != NULL) {
 214     kit.C->log()->elem("virtual_call bci='%d'", jvms->bci());
 215   }
 216 
 217   // If the receiver is a constant null, do not torture the system
 218   // by attempting to call through it.  The compile will proceed
 219   // correctly, but may bail out in final_graph_reshaping, because
 220   // the call instruction will have a seemingly deficient out-count.
 221   // (The bailout says something misleading about an "infinite loop".)
 222   if (kit.gvn().type(receiver)->higher_equal(TypePtr::NULL_PTR)) {
 223     assert(Bytecodes::is_invoke(kit.java_bc()), "%d: %s", kit.java_bc(), Bytecodes::name(kit.java_bc()));
 224     ciMethod* declared_method = kit.method()->get_method_at_bci(kit.bci());
 225     int arg_size = declared_method->signature()->arg_size_for_bc(kit.java_bc());
 226     kit.inc_sp(arg_size);  // restore arguments
 227     kit.uncommon_trap(Deoptimization::Reason_null_check,
 228                       Deoptimization::Action_none,
 229                       NULL, "null receiver");
 230     return kit.transfer_exceptions_into_jvms();
 231   }
 232 
 233   // Ideally we would unconditionally do a null check here and let it
 234   // be converted to an implicit check based on profile information.
 235   // However currently the conversion to implicit null checks in
 236   // Block::implicit_null_check() only looks for loads and stores, not calls.
 237   ciMethod *caller = kit.method();
 238   ciMethodData *caller_md = (caller == NULL) ? NULL : caller->method_data();
 239   if (!UseInlineCaches || !ImplicitNullChecks || !os::zero_page_read_protected() ||
 240        ((ImplicitNullCheckThreshold > 0) && caller_md &&
 241        (caller_md->trap_count(Deoptimization::Reason_null_check)
 242        >= (uint)ImplicitNullCheckThreshold))) {
 243     // Make an explicit receiver null_check as part of this call.
 244     // Since we share a map with the caller, his JVMS gets adjusted.
 245     receiver = kit.null_check_receiver_before_call(method());
 246     if (kit.stopped()) {
 247       // And dump it back to the caller, decorated with any exceptions:
 248       return kit.transfer_exceptions_into_jvms();
 249     }
 250   }
 251 
 252   assert(!method()->is_static(), "virtual call must not be to static");
 253   assert(!method()->is_final(), "virtual call should not be to final");
 254   assert(!method()->is_private(), "virtual call should not be to private");
 255   assert(_vtable_index == Method::invalid_vtable_index || !UseInlineCaches,
 256          "no vtable calls if +UseInlineCaches ");
 257   address target = SharedRuntime::get_resolve_virtual_call_stub();
 258   // Normal inline cache used for call
 259   CallDynamicJavaNode *call = new CallDynamicJavaNode(tf(), target, method(), _vtable_index, kit.bci());
 260   if (is_inlined_mh_linker(jvms, method())) {
 261     // To be able to issue a direct call (optimized virtual or virtual)
 262     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
 263     // about the method being invoked should be attached to the call site to
 264     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
 265     call->set_override_symbolic_info(true);
 266   }
 267   kit.set_arguments_for_java_call(call);
 268   kit.set_edges_for_java_call(call);
 269   Node* ret = kit.set_results_for_java_call(call);
 270   // Check if return value is a value type pointer
 271   if (gvn.type(ret)->isa_valuetypeptr()) {
 272     // Create ValueTypeNode from the oop and replace the return value
 273     Node* vt = ValueTypeNode::make(gvn, kit.merged_memory(), ret);
 274     kit.push_node(T_VALUETYPE, vt);
 275   } else {
 276     kit.push_node(method()->return_type()->basic_type(), ret);
 277   }
 278 
 279   // Represent the effect of an implicit receiver null_check
 280   // as part of this call.  Since we share a map with the caller,
 281   // his JVMS gets adjusted.
 282   kit.cast_not_null(receiver);
 283   return kit.transfer_exceptions_into_jvms();
 284 }
 285 
 286 CallGenerator* CallGenerator::for_inline(ciMethod* m, float expected_uses) {
 287   if (InlineTree::check_can_parse(m) != NULL)  return NULL;
 288   return new ParseGenerator(m, expected_uses);
 289 }
 290 
 291 // As a special case, the JVMS passed to this CallGenerator is
 292 // for the method execution already in progress, not just the JVMS
 293 // of the caller.  Thus, this CallGenerator cannot be mixed with others!
 294 CallGenerator* CallGenerator::for_osr(ciMethod* m, int osr_bci) {
 295   if (InlineTree::check_can_parse(m) != NULL)  return NULL;
 296   float past_uses = m->interpreter_invocation_count();
 297   float expected_uses = past_uses;
 298   return new ParseGenerator(m, expected_uses, true);
 299 }
 300 
 301 CallGenerator* CallGenerator::for_direct_call(ciMethod* m, bool separate_io_proj) {
 302   assert(!m->is_abstract(), "for_direct_call mismatch");
 303   return new DirectCallGenerator(m, separate_io_proj);
 304 }
 305 
 306 CallGenerator* CallGenerator::for_virtual_call(ciMethod* m, int vtable_index) {
 307   assert(!m->is_static(), "for_virtual_call mismatch");
 308   assert(!m->is_method_handle_intrinsic(), "should be a direct call");
 309   return new VirtualCallGenerator(m, vtable_index);
 310 }
 311 
 312 // Allow inlining decisions to be delayed
 313 class LateInlineCallGenerator : public DirectCallGenerator {
 314  private:
 315   // unique id for log compilation
 316   jlong _unique_id;
 317 
 318  protected:
 319   CallGenerator* _inline_cg;
 320   virtual bool do_late_inline_check(JVMState* jvms) { return true; }
 321 
 322  public:
 323   LateInlineCallGenerator(ciMethod* method, CallGenerator* inline_cg) :
 324     DirectCallGenerator(method, true), _inline_cg(inline_cg), _unique_id(0) {}
 325 
 326   virtual bool is_late_inline() const { return true; }
 327 
 328   // Convert the CallStaticJava into an inline
 329   virtual void do_late_inline();
 330 
 331   virtual JVMState* generate(JVMState* jvms) {
 332     Compile *C = Compile::current();
 333 
 334     C->log_inline_id(this);
 335 
 336     // Record that this call site should be revisited once the main
 337     // parse is finished.
 338     if (!is_mh_late_inline()) {
 339       C->add_late_inline(this);
 340     }
 341 
 342     // Emit the CallStaticJava and request separate projections so
 343     // that the late inlining logic can distinguish between fall
 344     // through and exceptional uses of the memory and io projections
 345     // as is done for allocations and macro expansion.
 346     return DirectCallGenerator::generate(jvms);
 347   }
 348 
 349   virtual void print_inlining_late(const char* msg) {
 350     CallNode* call = call_node();
 351     Compile* C = Compile::current();
 352     C->print_inlining_assert_ready();
 353     C->print_inlining(method(), call->jvms()->depth()-1, call->jvms()->bci(), msg);
 354     C->print_inlining_move_to(this);
 355     C->print_inlining_update_delayed(this);
 356   }
 357 
 358   virtual void set_unique_id(jlong id) {
 359     _unique_id = id;
 360   }
 361 
 362   virtual jlong unique_id() const {
 363     return _unique_id;
 364   }
 365 };
 366 
 367 void LateInlineCallGenerator::do_late_inline() {
 368   // Can't inline it
 369   CallStaticJavaNode* call = call_node();
 370   if (call == NULL || call->outcnt() == 0 ||
 371       call->in(0) == NULL || call->in(0)->is_top()) {
 372     return;
 373   }
 374   
 375   const TypeTuple *r = call->tf()->domain_cc();
 376   for (int i1 = 0; i1 < method()->arg_size(); i1++) {
 377     if (call->in(TypeFunc::Parms + i1)->is_top() && r->field_at(TypeFunc::Parms + i1) != Type::HALF) {
 378       assert(Compile::current()->inlining_incrementally(), "shouldn't happen during parsing");
 379       return;
 380     }
 381   }
 382 
 383   if (call->in(TypeFunc::Memory)->is_top()) {
 384     assert(Compile::current()->inlining_incrementally(), "shouldn't happen during parsing");
 385     return;
 386   }
 387 
 388   Compile* C = Compile::current();
 389   // Remove inlined methods from Compiler's lists.
 390   if (call->is_macro()) {
 391     C->remove_macro_node(call);
 392   }
 393 
 394   // Make a clone of the JVMState that appropriate to use for driving a parse
 395   JVMState* old_jvms = call->jvms();
 396   JVMState* jvms = old_jvms->clone_shallow(C);
 397   uint size = call->req();
 398   SafePointNode* map = new SafePointNode(size, jvms);
 399   for (uint i1 = 0; i1 < size; i1++) {
 400     map->init_req(i1, call->in(i1));
 401   }
 402 
 403   PhaseGVN& gvn = *C->initial_gvn();
 404   // Make sure the state is a MergeMem for parsing.
 405   if (!map->in(TypeFunc::Memory)->is_MergeMem()) {
 406     Node* mem = MergeMemNode::make(map->in(TypeFunc::Memory));
 407     gvn.set_type_bottom(mem);
 408     map->set_req(TypeFunc::Memory, mem);
 409   }
 410 
 411   // blow away old call arguments
 412   Node* top = C->top();
 413   for (uint i1 = TypeFunc::Parms; i1 < call->_tf->domain_cc()->cnt(); i1++) {
 414     map->set_req(i1, top);
 415   }
 416   jvms->set_map(map);
 417 
 418   // Make enough space in the expression stack to transfer
 419   // the incoming arguments and return value.
 420   map->ensure_stack(jvms, jvms->method()->max_stack());
 421   const TypeTuple *domain_sig = call->_tf->domain_sig();
 422   uint nargs = method()->arg_size();
 423   assert(domain_sig->cnt() - TypeFunc::Parms == nargs, "inconsistent signature");
 424 
 425   uint j = TypeFunc::Parms;
 426   for (uint i1 = 0; i1 < nargs; i1++) {
 427     const Type* t = domain_sig->field_at(TypeFunc::Parms + i1);
 428     if (!ValueTypePassFieldsAsArgs) {
 429       Node* arg = call->in(TypeFunc::Parms + i1);
 430       if (t->isa_valuetypeptr()) {
 431         arg = ValueTypeNode::make(gvn, map->memory(), arg);
 432       }
 433       map->set_argument(jvms, i1, arg);
 434     } else {
 435       if (t->isa_valuetypeptr()) {
 436         ciValueKlass* vk = t->is_valuetypeptr()->value_type()->value_klass();
 437         Node* vt = C->create_vt_node(call, vk, vk, 0, j);
 438         map->set_argument(jvms, i1, gvn.transform(vt));
 439         j += vk->value_arg_slots();
 440       } else {
 441         map->set_argument(jvms, i1, call->in(j));
 442         j++;
 443       }
 444     }
 445   }
 446 
 447   C->print_inlining_assert_ready();
 448 
 449   C->print_inlining_move_to(this);
 450 
 451   C->log_late_inline(this);
 452 
 453   // This check is done here because for_method_handle_inline() method
 454   // needs jvms for inlined state.
 455   if (!do_late_inline_check(jvms)) {
 456     map->disconnect_inputs(NULL, C);
 457     return;
 458   }
 459 
 460   // Setup default node notes to be picked up by the inlining
 461   Node_Notes* old_nn = C->node_notes_at(call->_idx);
 462   if (old_nn != NULL) {
 463     Node_Notes* entry_nn = old_nn->clone(C);
 464     entry_nn->set_jvms(jvms);
 465     C->set_default_node_notes(entry_nn);
 466   }
 467 
 468   // Now perform the inlining using the synthesized JVMState
 469   JVMState* new_jvms = _inline_cg->generate(jvms);
 470   if (new_jvms == NULL)  return;  // no change
 471   if (C->failing())      return;
 472 
 473   // Capture any exceptional control flow
 474   GraphKit kit(new_jvms);
 475 
 476   // Find the result object
 477   Node* result = C->top();
 478   int   result_size = method()->return_type()->size();
 479   if (result_size != 0 && !kit.stopped()) {
 480     result = (result_size == 1) ? kit.pop() : kit.pop_pair();
 481   }
 482 
 483   C->set_has_loops(C->has_loops() || _inline_cg->method()->has_loops());
 484   C->env()->notice_inlined_method(_inline_cg->method());
 485   C->set_inlining_progress(true);
 486 
 487   if (result->is_ValueType()) {
 488     result = result->as_ValueType()->store_to_memory(&kit);
 489   }
 490 
 491   kit.replace_call(call, result, true);
 492 }
 493 
 494 
 495 CallGenerator* CallGenerator::for_late_inline(ciMethod* method, CallGenerator* inline_cg) {
 496   return new LateInlineCallGenerator(method, inline_cg);
 497 }
 498 
 499 class LateInlineMHCallGenerator : public LateInlineCallGenerator {
 500   ciMethod* _caller;
 501   int _attempt;
 502   bool _input_not_const;
 503 
 504   virtual bool do_late_inline_check(JVMState* jvms);
 505   virtual bool already_attempted() const { return _attempt > 0; }
 506 
 507  public:
 508   LateInlineMHCallGenerator(ciMethod* caller, ciMethod* callee, bool input_not_const) :
 509     LateInlineCallGenerator(callee, NULL), _caller(caller), _attempt(0), _input_not_const(input_not_const) {}
 510 
 511   virtual bool is_mh_late_inline() const { return true; }
 512 
 513   virtual JVMState* generate(JVMState* jvms) {
 514     JVMState* new_jvms = LateInlineCallGenerator::generate(jvms);
 515 
 516     Compile* C = Compile::current();
 517     if (_input_not_const) {
 518       // inlining won't be possible so no need to enqueue right now.
 519       call_node()->set_generator(this);
 520     } else {
 521       C->add_late_inline(this);
 522     }
 523     return new_jvms;
 524   }
 525 };
 526 
 527 bool LateInlineMHCallGenerator::do_late_inline_check(JVMState* jvms) {
 528 
 529   CallGenerator* cg = for_method_handle_inline(jvms, _caller, method(), _input_not_const);
 530 
 531   Compile::current()->print_inlining_update_delayed(this);
 532 
 533   if (!_input_not_const) {
 534     _attempt++;
 535   }
 536 
 537   if (cg != NULL && cg->is_inline()) {
 538     assert(!cg->is_late_inline(), "we're doing late inlining");
 539     _inline_cg = cg;
 540     Compile::current()->dec_number_of_mh_late_inlines();
 541     return true;
 542   }
 543 
 544   call_node()->set_generator(this);
 545   return false;
 546 }
 547 
 548 CallGenerator* CallGenerator::for_mh_late_inline(ciMethod* caller, ciMethod* callee, bool input_not_const) {
 549   Compile::current()->inc_number_of_mh_late_inlines();
 550   CallGenerator* cg = new LateInlineMHCallGenerator(caller, callee, input_not_const);
 551   return cg;
 552 }
 553 
 554 class LateInlineStringCallGenerator : public LateInlineCallGenerator {
 555 
 556  public:
 557   LateInlineStringCallGenerator(ciMethod* method, CallGenerator* inline_cg) :
 558     LateInlineCallGenerator(method, inline_cg) {}
 559 
 560   virtual JVMState* generate(JVMState* jvms) {
 561     Compile *C = Compile::current();
 562 
 563     C->log_inline_id(this);
 564 
 565     C->add_string_late_inline(this);
 566 
 567     JVMState* new_jvms =  DirectCallGenerator::generate(jvms);
 568     return new_jvms;
 569   }
 570 
 571   virtual bool is_string_late_inline() const { return true; }
 572 };
 573 
 574 CallGenerator* CallGenerator::for_string_late_inline(ciMethod* method, CallGenerator* inline_cg) {
 575   return new LateInlineStringCallGenerator(method, inline_cg);
 576 }
 577 
 578 class LateInlineBoxingCallGenerator : public LateInlineCallGenerator {
 579 
 580  public:
 581   LateInlineBoxingCallGenerator(ciMethod* method, CallGenerator* inline_cg) :
 582     LateInlineCallGenerator(method, inline_cg) {}
 583 
 584   virtual JVMState* generate(JVMState* jvms) {
 585     Compile *C = Compile::current();
 586 
 587     C->log_inline_id(this);
 588 
 589     C->add_boxing_late_inline(this);
 590 
 591     JVMState* new_jvms =  DirectCallGenerator::generate(jvms);
 592     return new_jvms;
 593   }
 594 };
 595 
 596 CallGenerator* CallGenerator::for_boxing_late_inline(ciMethod* method, CallGenerator* inline_cg) {
 597   return new LateInlineBoxingCallGenerator(method, inline_cg);
 598 }
 599 
 600 //---------------------------WarmCallGenerator--------------------------------
 601 // Internal class which handles initial deferral of inlining decisions.
 602 class WarmCallGenerator : public CallGenerator {
 603   WarmCallInfo*   _call_info;
 604   CallGenerator*  _if_cold;
 605   CallGenerator*  _if_hot;
 606   bool            _is_virtual;   // caches virtuality of if_cold
 607   bool            _is_inline;    // caches inline-ness of if_hot
 608 
 609 public:
 610   WarmCallGenerator(WarmCallInfo* ci,
 611                     CallGenerator* if_cold,
 612                     CallGenerator* if_hot)
 613     : CallGenerator(if_cold->method())
 614   {
 615     assert(method() == if_hot->method(), "consistent choices");
 616     _call_info  = ci;
 617     _if_cold    = if_cold;
 618     _if_hot     = if_hot;
 619     _is_virtual = if_cold->is_virtual();
 620     _is_inline  = if_hot->is_inline();
 621   }
 622 
 623   virtual bool      is_inline() const           { return _is_inline; }
 624   virtual bool      is_virtual() const          { return _is_virtual; }
 625   virtual bool      is_deferred() const         { return true; }
 626 
 627   virtual JVMState* generate(JVMState* jvms);
 628 };
 629 
 630 
 631 CallGenerator* CallGenerator::for_warm_call(WarmCallInfo* ci,
 632                                             CallGenerator* if_cold,
 633                                             CallGenerator* if_hot) {
 634   return new WarmCallGenerator(ci, if_cold, if_hot);
 635 }
 636 
 637 JVMState* WarmCallGenerator::generate(JVMState* jvms) {
 638   Compile* C = Compile::current();
 639   C->print_inlining_update(this);
 640 
 641   if (C->log() != NULL) {
 642     C->log()->elem("warm_call bci='%d'", jvms->bci());
 643   }
 644   jvms = _if_cold->generate(jvms);
 645   if (jvms != NULL) {
 646     Node* m = jvms->map()->control();
 647     if (m->is_CatchProj()) m = m->in(0);  else m = C->top();
 648     if (m->is_Catch())     m = m->in(0);  else m = C->top();
 649     if (m->is_Proj())      m = m->in(0);  else m = C->top();
 650     if (m->is_CallJava()) {
 651       _call_info->set_call(m->as_Call());
 652       _call_info->set_hot_cg(_if_hot);
 653 #ifndef PRODUCT
 654       if (PrintOpto || PrintOptoInlining) {
 655         tty->print_cr("Queueing for warm inlining at bci %d:", jvms->bci());
 656         tty->print("WCI: ");
 657         _call_info->print();
 658       }
 659 #endif
 660       _call_info->set_heat(_call_info->compute_heat());
 661       C->set_warm_calls(_call_info->insert_into(C->warm_calls()));
 662     }
 663   }
 664   return jvms;
 665 }
 666 
 667 void WarmCallInfo::make_hot() {
 668   Unimplemented();
 669 }
 670 
 671 void WarmCallInfo::make_cold() {
 672   // No action:  Just dequeue.
 673 }
 674 
 675 
 676 //------------------------PredictedCallGenerator------------------------------
 677 // Internal class which handles all out-of-line calls checking receiver type.
 678 class PredictedCallGenerator : public CallGenerator {
 679   ciKlass*       _predicted_receiver;
 680   CallGenerator* _if_missed;
 681   CallGenerator* _if_hit;
 682   float          _hit_prob;
 683 
 684 public:
 685   PredictedCallGenerator(ciKlass* predicted_receiver,
 686                          CallGenerator* if_missed,
 687                          CallGenerator* if_hit, float hit_prob)
 688     : CallGenerator(if_missed->method())
 689   {
 690     // The call profile data may predict the hit_prob as extreme as 0 or 1.
 691     // Remove the extremes values from the range.
 692     if (hit_prob > PROB_MAX)   hit_prob = PROB_MAX;
 693     if (hit_prob < PROB_MIN)   hit_prob = PROB_MIN;
 694 
 695     _predicted_receiver = predicted_receiver;
 696     _if_missed          = if_missed;
 697     _if_hit             = if_hit;
 698     _hit_prob           = hit_prob;
 699   }
 700 
 701   virtual bool      is_virtual()   const    { return true; }
 702   virtual bool      is_inline()    const    { return _if_hit->is_inline(); }
 703   virtual bool      is_deferred()  const    { return _if_hit->is_deferred(); }
 704 
 705   virtual JVMState* generate(JVMState* jvms);
 706 };
 707 
 708 
 709 CallGenerator* CallGenerator::for_predicted_call(ciKlass* predicted_receiver,
 710                                                  CallGenerator* if_missed,
 711                                                  CallGenerator* if_hit,
 712                                                  float hit_prob) {
 713   return new PredictedCallGenerator(predicted_receiver, if_missed, if_hit, hit_prob);
 714 }
 715 
 716 
 717 JVMState* PredictedCallGenerator::generate(JVMState* jvms) {
 718   GraphKit kit(jvms);
 719   kit.C->print_inlining_update(this);
 720   PhaseGVN& gvn = kit.gvn();
 721   // We need an explicit receiver null_check before checking its type.
 722   // We share a map with the caller, so his JVMS gets adjusted.
 723   Node* receiver = kit.argument(0);
 724   CompileLog* log = kit.C->log();
 725   if (log != NULL) {
 726     log->elem("predicted_call bci='%d' klass='%d'",
 727               jvms->bci(), log->identify(_predicted_receiver));
 728   }
 729 
 730   receiver = kit.null_check_receiver_before_call(method());
 731   if (kit.stopped()) {
 732     return kit.transfer_exceptions_into_jvms();
 733   }
 734 
 735   // Make a copy of the replaced nodes in case we need to restore them
 736   ReplacedNodes replaced_nodes = kit.map()->replaced_nodes();
 737   replaced_nodes.clone();
 738 
 739   Node* exact_receiver = receiver;  // will get updated in place...
 740   Node* slow_ctl = kit.type_check_receiver(receiver,
 741                                            _predicted_receiver, _hit_prob,
 742                                            &exact_receiver);
 743 
 744   SafePointNode* slow_map = NULL;
 745   JVMState* slow_jvms = NULL;
 746   { PreserveJVMState pjvms(&kit);
 747     kit.set_control(slow_ctl);
 748     if (!kit.stopped()) {
 749       slow_jvms = _if_missed->generate(kit.sync_jvms());
 750       if (kit.failing())
 751         return NULL;  // might happen because of NodeCountInliningCutoff
 752       assert(slow_jvms != NULL, "must be");
 753       kit.add_exception_states_from(slow_jvms);
 754       kit.set_map(slow_jvms->map());
 755       if (!kit.stopped())
 756         slow_map = kit.stop();
 757     }
 758   }
 759 
 760   if (kit.stopped()) {
 761     // Instance exactly does not matches the desired type.
 762     kit.set_jvms(slow_jvms);
 763     return kit.transfer_exceptions_into_jvms();
 764   }
 765 
 766   // fall through if the instance exactly matches the desired type
 767   kit.replace_in_map(receiver, exact_receiver);
 768 
 769   // Make the hot call:
 770   JVMState* new_jvms = _if_hit->generate(kit.sync_jvms());
 771   if (new_jvms == NULL) {
 772     // Inline failed, so make a direct call.
 773     assert(_if_hit->is_inline(), "must have been a failed inline");
 774     CallGenerator* cg = CallGenerator::for_direct_call(_if_hit->method());
 775     new_jvms = cg->generate(kit.sync_jvms());
 776   }
 777   kit.add_exception_states_from(new_jvms);
 778   kit.set_jvms(new_jvms);
 779 
 780   // Need to merge slow and fast?
 781   if (slow_map == NULL) {
 782     // The fast path is the only path remaining.
 783     return kit.transfer_exceptions_into_jvms();
 784   }
 785 
 786   if (kit.stopped()) {
 787     // Inlined method threw an exception, so it's just the slow path after all.
 788     kit.set_jvms(slow_jvms);
 789     return kit.transfer_exceptions_into_jvms();
 790   }
 791 
 792   // There are 2 branches and the replaced nodes are only valid on
 793   // one: restore the replaced nodes to what they were before the
 794   // branch.
 795   kit.map()->set_replaced_nodes(replaced_nodes);
 796 
 797   // Finish the diamond.
 798   kit.C->set_has_split_ifs(true); // Has chance for split-if optimization
 799   RegionNode* region = new RegionNode(3);
 800   region->init_req(1, kit.control());
 801   region->init_req(2, slow_map->control());
 802   kit.set_control(gvn.transform(region));
 803   Node* iophi = PhiNode::make(region, kit.i_o(), Type::ABIO);
 804   iophi->set_req(2, slow_map->i_o());
 805   kit.set_i_o(gvn.transform(iophi));
 806   // Merge memory
 807   kit.merge_memory(slow_map->merged_memory(), region, 2);
 808   // Transform new memory Phis.
 809   for (MergeMemStream mms(kit.merged_memory()); mms.next_non_empty();) {
 810     Node* phi = mms.memory();
 811     if (phi->is_Phi() && phi->in(0) == region) {
 812       mms.set_memory(gvn.transform(phi));
 813     }
 814   }
 815   uint tos = kit.jvms()->stkoff() + kit.sp();
 816   uint limit = slow_map->req();
 817   for (uint i = TypeFunc::Parms; i < limit; i++) {
 818     // Skip unused stack slots; fast forward to monoff();
 819     if (i == tos) {
 820       i = kit.jvms()->monoff();
 821       if( i >= limit ) break;
 822     }
 823     Node* m = kit.map()->in(i);
 824     Node* n = slow_map->in(i);
 825     if (m != n) {
 826       const Type* t = gvn.type(m)->meet_speculative(gvn.type(n));
 827       Node* phi = PhiNode::make(region, m, t);
 828       phi->set_req(2, n);
 829       kit.map()->set_req(i, gvn.transform(phi));
 830     }
 831   }
 832   return kit.transfer_exceptions_into_jvms();
 833 }
 834 
 835 
 836 CallGenerator* CallGenerator::for_method_handle_call(JVMState* jvms, ciMethod* caller, ciMethod* callee, bool delayed_forbidden) {
 837   assert(callee->is_method_handle_intrinsic() ||
 838          callee->is_compiled_lambda_form(), "for_method_handle_call mismatch");
 839   bool input_not_const;
 840   CallGenerator* cg = CallGenerator::for_method_handle_inline(jvms, caller, callee, input_not_const);
 841   Compile* C = Compile::current();
 842   if (cg != NULL) {
 843     if (!delayed_forbidden && AlwaysIncrementalInline) {
 844       return CallGenerator::for_late_inline(callee, cg);
 845     } else {
 846       return cg;
 847     }
 848   }
 849   int bci = jvms->bci();
 850   ciCallProfile profile = caller->call_profile_at_bci(bci);
 851   int call_site_count = caller->scale_count(profile.count());
 852 
 853   if (IncrementalInline && call_site_count > 0 &&
 854       (input_not_const || !C->inlining_incrementally() || C->over_inlining_cutoff())) {
 855     return CallGenerator::for_mh_late_inline(caller, callee, input_not_const);
 856   } else {
 857     // Out-of-line call.
 858     return CallGenerator::for_direct_call(callee);
 859   }
 860 }
 861 
 862 CallGenerator* CallGenerator::for_method_handle_inline(JVMState* jvms, ciMethod* caller, ciMethod* callee, bool& input_not_const) {
 863   GraphKit kit(jvms);
 864   PhaseGVN& gvn = kit.gvn();
 865   Compile* C = kit.C;
 866   vmIntrinsics::ID iid = callee->intrinsic_id();
 867   input_not_const = true;
 868   switch (iid) {
 869   case vmIntrinsics::_invokeBasic:
 870     {
 871       // Get MethodHandle receiver:
 872       Node* receiver = kit.argument(0);
 873       if (receiver->Opcode() == Op_ConP) {
 874         input_not_const = false;
 875         const TypeOopPtr* oop_ptr = receiver->bottom_type()->is_oopptr();
 876         ciMethod* target = oop_ptr->const_oop()->as_method_handle()->get_vmtarget();
 877         const int vtable_index = Method::invalid_vtable_index;
 878         CallGenerator* cg = C->call_generator(target, vtable_index,
 879                                               false /* call_does_dispatch */,
 880                                               jvms,
 881                                               true /* allow_inline */,
 882                                               PROB_ALWAYS);
 883         return cg;
 884       } else {
 885         const char* msg = "receiver not constant";
 886         if (PrintInlining)  C->print_inlining(callee, jvms->depth() - 1, jvms->bci(), msg);
 887         C->log_inline_failure(msg);
 888       }
 889     }
 890     break;
 891 
 892   case vmIntrinsics::_linkToVirtual:
 893   case vmIntrinsics::_linkToStatic:
 894   case vmIntrinsics::_linkToSpecial:
 895   case vmIntrinsics::_linkToInterface:
 896     {
 897       // Get MemberName argument:
 898       Node* member_name = kit.argument(callee->arg_size() - 1);
 899       if (member_name->Opcode() == Op_ConP) {
 900         input_not_const = false;
 901         const TypeOopPtr* oop_ptr = member_name->bottom_type()->is_oopptr();
 902         ciMethod* target = oop_ptr->const_oop()->as_member_name()->get_vmtarget();
 903 
 904         // In lambda forms we erase signature types to avoid resolving issues
 905         // involving class loaders.  When we optimize a method handle invoke
 906         // to a direct call we must cast the receiver and arguments to its
 907         // actual types.
 908         ciSignature* signature = target->signature();
 909         const int receiver_skip = target->is_static() ? 0 : 1;
 910         // Cast receiver to its type.
 911         if (!target->is_static()) {
 912           Node* arg = kit.argument(0);
 913           const TypeOopPtr* arg_type = arg->bottom_type()->isa_oopptr();
 914           const Type*       sig_type = TypeOopPtr::make_from_klass(signature->accessing_klass());
 915           if (arg_type != NULL && !arg_type->higher_equal(sig_type)) {
 916             Node* cast_obj = gvn.transform(new CheckCastPPNode(kit.control(), arg, sig_type));
 917             kit.set_argument(0, cast_obj);
 918           }
 919         }
 920         // Cast reference arguments to its type.
 921         for (int i = 0, j = 0; i < signature->count(); i++) {
 922           ciType* t = signature->type_at(i);
 923           if (t->is_klass()) {
 924             Node* arg = kit.argument(receiver_skip + j);
 925             const TypeOopPtr* arg_type = arg->bottom_type()->isa_oopptr();
 926             const Type*       sig_type = TypeOopPtr::make_from_klass(t->as_klass());
 927             if (arg_type != NULL && !arg_type->higher_equal(sig_type)) {
 928               Node* cast_obj = gvn.transform(new CheckCastPPNode(kit.control(), arg, sig_type));
 929               kit.set_argument(receiver_skip + j, cast_obj);
 930             }
 931           }
 932           j += t->size();  // long and double take two slots
 933         }
 934 
 935         // Try to get the most accurate receiver type
 936         const bool is_virtual              = (iid == vmIntrinsics::_linkToVirtual);
 937         const bool is_virtual_or_interface = (is_virtual || iid == vmIntrinsics::_linkToInterface);
 938         int  vtable_index       = Method::invalid_vtable_index;
 939         bool call_does_dispatch = false;
 940 
 941         ciKlass* speculative_receiver_type = NULL;
 942         if (is_virtual_or_interface) {
 943           ciInstanceKlass* klass = target->holder();
 944           Node*             receiver_node = kit.argument(0);
 945           const TypeOopPtr* receiver_type = gvn.type(receiver_node)->isa_oopptr();
 946           // call_does_dispatch and vtable_index are out-parameters.  They might be changed.
 947           // optimize_virtual_call() takes 2 different holder
 948           // arguments for a corner case that doesn't apply here (see
 949           // Parse::do_call())
 950           target = C->optimize_virtual_call(caller, jvms->bci(), klass, klass,
 951                                             target, receiver_type, is_virtual,
 952                                             call_does_dispatch, vtable_index, // out-parameters
 953                                             false /* check_access */);
 954           // We lack profiling at this call but type speculation may
 955           // provide us with a type
 956           speculative_receiver_type = (receiver_type != NULL) ? receiver_type->speculative_type() : NULL;
 957         }
 958         CallGenerator* cg = C->call_generator(target, vtable_index, call_does_dispatch, jvms,
 959                                               true /* allow_inline */,
 960                                               PROB_ALWAYS,
 961                                               speculative_receiver_type);
 962         return cg;
 963       } else {
 964         const char* msg = "member_name not constant";
 965         if (PrintInlining)  C->print_inlining(callee, jvms->depth() - 1, jvms->bci(), msg);
 966         C->log_inline_failure(msg);
 967       }
 968     }
 969     break;
 970 
 971   default:
 972     fatal("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid));
 973     break;
 974   }
 975   return NULL;
 976 }
 977 
 978 
 979 //------------------------PredicatedIntrinsicGenerator------------------------------
 980 // Internal class which handles all predicated Intrinsic calls.
 981 class PredicatedIntrinsicGenerator : public CallGenerator {
 982   CallGenerator* _intrinsic;
 983   CallGenerator* _cg;
 984 
 985 public:
 986   PredicatedIntrinsicGenerator(CallGenerator* intrinsic,
 987                                CallGenerator* cg)
 988     : CallGenerator(cg->method())
 989   {
 990     _intrinsic = intrinsic;
 991     _cg        = cg;
 992   }
 993 
 994   virtual bool      is_virtual()   const    { return true; }
 995   virtual bool      is_inlined()   const    { return true; }
 996   virtual bool      is_intrinsic() const    { return true; }
 997 
 998   virtual JVMState* generate(JVMState* jvms);
 999 };
1000 
1001 
1002 CallGenerator* CallGenerator::for_predicated_intrinsic(CallGenerator* intrinsic,
1003                                                        CallGenerator* cg) {
1004   return new PredicatedIntrinsicGenerator(intrinsic, cg);
1005 }
1006 
1007 
1008 JVMState* PredicatedIntrinsicGenerator::generate(JVMState* jvms) {
1009   // The code we want to generate here is:
1010   //    if (receiver == NULL)
1011   //        uncommon_Trap
1012   //    if (predicate(0))
1013   //        do_intrinsic(0)
1014   //    else
1015   //    if (predicate(1))
1016   //        do_intrinsic(1)
1017   //    ...
1018   //    else
1019   //        do_java_comp
1020 
1021   GraphKit kit(jvms);
1022   PhaseGVN& gvn = kit.gvn();
1023 
1024   CompileLog* log = kit.C->log();
1025   if (log != NULL) {
1026     log->elem("predicated_intrinsic bci='%d' method='%d'",
1027               jvms->bci(), log->identify(method()));
1028   }
1029 
1030   if (!method()->is_static()) {
1031     // We need an explicit receiver null_check before checking its type in predicate.
1032     // We share a map with the caller, so his JVMS gets adjusted.
1033     Node* receiver = kit.null_check_receiver_before_call(method());
1034     if (kit.stopped()) {
1035       return kit.transfer_exceptions_into_jvms();
1036     }
1037   }
1038 
1039   int n_predicates = _intrinsic->predicates_count();
1040   assert(n_predicates > 0, "sanity");
1041 
1042   JVMState** result_jvms = NEW_RESOURCE_ARRAY(JVMState*, (n_predicates+1));
1043 
1044   // Region for normal compilation code if intrinsic failed.
1045   Node* slow_region = new RegionNode(1);
1046 
1047   int results = 0;
1048   for (int predicate = 0; (predicate < n_predicates) && !kit.stopped(); predicate++) {
1049 #ifdef ASSERT
1050     JVMState* old_jvms = kit.jvms();
1051     SafePointNode* old_map = kit.map();
1052     Node* old_io  = old_map->i_o();
1053     Node* old_mem = old_map->memory();
1054     Node* old_exc = old_map->next_exception();
1055 #endif
1056     Node* else_ctrl = _intrinsic->generate_predicate(kit.sync_jvms(), predicate);
1057 #ifdef ASSERT
1058     // Assert(no_new_memory && no_new_io && no_new_exceptions) after generate_predicate.
1059     assert(old_jvms == kit.jvms(), "generate_predicate should not change jvm state");
1060     SafePointNode* new_map = kit.map();
1061     assert(old_io  == new_map->i_o(), "generate_predicate should not change i_o");
1062     assert(old_mem == new_map->memory(), "generate_predicate should not change memory");
1063     assert(old_exc == new_map->next_exception(), "generate_predicate should not add exceptions");
1064 #endif
1065     if (!kit.stopped()) {
1066       PreserveJVMState pjvms(&kit);
1067       // Generate intrinsic code:
1068       JVMState* new_jvms = _intrinsic->generate(kit.sync_jvms());
1069       if (new_jvms == NULL) {
1070         // Intrinsic failed, use normal compilation path for this predicate.
1071         slow_region->add_req(kit.control());
1072       } else {
1073         kit.add_exception_states_from(new_jvms);
1074         kit.set_jvms(new_jvms);
1075         if (!kit.stopped()) {
1076           result_jvms[results++] = kit.jvms();
1077         }
1078       }
1079     }
1080     if (else_ctrl == NULL) {
1081       else_ctrl = kit.C->top();
1082     }
1083     kit.set_control(else_ctrl);
1084   }
1085   if (!kit.stopped()) {
1086     // Final 'else' after predicates.
1087     slow_region->add_req(kit.control());
1088   }
1089   if (slow_region->req() > 1) {
1090     PreserveJVMState pjvms(&kit);
1091     // Generate normal compilation code:
1092     kit.set_control(gvn.transform(slow_region));
1093     JVMState* new_jvms = _cg->generate(kit.sync_jvms());
1094     if (kit.failing())
1095       return NULL;  // might happen because of NodeCountInliningCutoff
1096     assert(new_jvms != NULL, "must be");
1097     kit.add_exception_states_from(new_jvms);
1098     kit.set_jvms(new_jvms);
1099     if (!kit.stopped()) {
1100       result_jvms[results++] = kit.jvms();
1101     }
1102   }
1103 
1104   if (results == 0) {
1105     // All paths ended in uncommon traps.
1106     (void) kit.stop();
1107     return kit.transfer_exceptions_into_jvms();
1108   }
1109 
1110   if (results == 1) { // Only one path
1111     kit.set_jvms(result_jvms[0]);
1112     return kit.transfer_exceptions_into_jvms();
1113   }
1114 
1115   // Merge all paths.
1116   kit.C->set_has_split_ifs(true); // Has chance for split-if optimization
1117   RegionNode* region = new RegionNode(results + 1);
1118   Node* iophi = PhiNode::make(region, kit.i_o(), Type::ABIO);
1119   for (int i = 0; i < results; i++) {
1120     JVMState* jvms = result_jvms[i];
1121     int path = i + 1;
1122     SafePointNode* map = jvms->map();
1123     region->init_req(path, map->control());
1124     iophi->set_req(path, map->i_o());
1125     if (i == 0) {
1126       kit.set_jvms(jvms);
1127     } else {
1128       kit.merge_memory(map->merged_memory(), region, path);
1129     }
1130   }
1131   kit.set_control(gvn.transform(region));
1132   kit.set_i_o(gvn.transform(iophi));
1133   // Transform new memory Phis.
1134   for (MergeMemStream mms(kit.merged_memory()); mms.next_non_empty();) {
1135     Node* phi = mms.memory();
1136     if (phi->is_Phi() && phi->in(0) == region) {
1137       mms.set_memory(gvn.transform(phi));
1138     }
1139   }
1140 
1141   // Merge debug info.
1142   Node** ins = NEW_RESOURCE_ARRAY(Node*, results);
1143   uint tos = kit.jvms()->stkoff() + kit.sp();
1144   Node* map = kit.map();
1145   uint limit = map->req();
1146   for (uint i = TypeFunc::Parms; i < limit; i++) {
1147     // Skip unused stack slots; fast forward to monoff();
1148     if (i == tos) {
1149       i = kit.jvms()->monoff();
1150       if( i >= limit ) break;
1151     }
1152     Node* n = map->in(i);
1153     ins[0] = n;
1154     const Type* t = gvn.type(n);
1155     bool needs_phi = false;
1156     for (int j = 1; j < results; j++) {
1157       JVMState* jvms = result_jvms[j];
1158       Node* jmap = jvms->map();
1159       Node* m = NULL;
1160       if (jmap->req() > i) {
1161         m = jmap->in(i);
1162         if (m != n) {
1163           needs_phi = true;
1164           t = t->meet_speculative(gvn.type(m));
1165         }
1166       }
1167       ins[j] = m;
1168     }
1169     if (needs_phi) {
1170       Node* phi = PhiNode::make(region, n, t);
1171       for (int j = 1; j < results; j++) {
1172         phi->set_req(j + 1, ins[j]);
1173       }
1174       map->set_req(i, gvn.transform(phi));
1175     }
1176   }
1177 
1178   return kit.transfer_exceptions_into_jvms();
1179 }
1180 
1181 //-------------------------UncommonTrapCallGenerator-----------------------------
1182 // Internal class which handles all out-of-line calls checking receiver type.
1183 class UncommonTrapCallGenerator : public CallGenerator {
1184   Deoptimization::DeoptReason _reason;
1185   Deoptimization::DeoptAction _action;
1186 
1187 public:
1188   UncommonTrapCallGenerator(ciMethod* m,
1189                             Deoptimization::DeoptReason reason,
1190                             Deoptimization::DeoptAction action)
1191     : CallGenerator(m)
1192   {
1193     _reason = reason;
1194     _action = action;
1195   }
1196 
1197   virtual bool      is_virtual() const          { ShouldNotReachHere(); return false; }
1198   virtual bool      is_trap() const             { return true; }
1199 
1200   virtual JVMState* generate(JVMState* jvms);
1201 };
1202 
1203 
1204 CallGenerator*
1205 CallGenerator::for_uncommon_trap(ciMethod* m,
1206                                  Deoptimization::DeoptReason reason,
1207                                  Deoptimization::DeoptAction action) {
1208   return new UncommonTrapCallGenerator(m, reason, action);
1209 }
1210 
1211 
1212 JVMState* UncommonTrapCallGenerator::generate(JVMState* jvms) {
1213   GraphKit kit(jvms);
1214   kit.C->print_inlining_update(this);
1215   // Take the trap with arguments pushed on the stack.  (Cf. null_check_receiver).
1216   int nargs = method()->arg_size();
1217   kit.inc_sp(nargs);
1218   assert(nargs <= kit.sp() && kit.sp() <= jvms->stk_size(), "sane sp w/ args pushed");
1219   if (_reason == Deoptimization::Reason_class_check &&
1220       _action == Deoptimization::Action_maybe_recompile) {
1221     // Temp fix for 6529811
1222     // Don't allow uncommon_trap to override our decision to recompile in the event
1223     // of a class cast failure for a monomorphic call as it will never let us convert
1224     // the call to either bi-morphic or megamorphic and can lead to unc-trap loops
1225     bool keep_exact_action = true;
1226     kit.uncommon_trap(_reason, _action, NULL, "monomorphic vcall checkcast", false, keep_exact_action);
1227   } else {
1228     kit.uncommon_trap(_reason, _action);
1229   }
1230   return kit.transfer_exceptions_into_jvms();
1231 }
1232 
1233 // (Note:  Moved hook_up_call to GraphKit::set_edges_for_java_call.)
1234 
1235 // (Node:  Merged hook_up_exits into ParseGenerator::generate.)
1236 
1237 #define NODES_OVERHEAD_PER_METHOD (30.0)
1238 #define NODES_PER_BYTECODE (9.5)
1239 
1240 void WarmCallInfo::init(JVMState* call_site, ciMethod* call_method, ciCallProfile& profile, float prof_factor) {
1241   int call_count = profile.count();
1242   int code_size = call_method->code_size();
1243 
1244   // Expected execution count is based on the historical count:
1245   _count = call_count < 0 ? 1 : call_site->method()->scale_count(call_count, prof_factor);
1246 
1247   // Expected profit from inlining, in units of simple call-overheads.
1248   _profit = 1.0;
1249 
1250   // Expected work performed by the call in units of call-overheads.
1251   // %%% need an empirical curve fit for "work" (time in call)
1252   float bytecodes_per_call = 3;
1253   _work = 1.0 + code_size / bytecodes_per_call;
1254 
1255   // Expected size of compilation graph:
1256   // -XX:+PrintParseStatistics once reported:
1257   //  Methods seen: 9184  Methods parsed: 9184  Nodes created: 1582391
1258   //  Histogram of 144298 parsed bytecodes:
1259   // %%% Need an better predictor for graph size.
1260   _size = NODES_OVERHEAD_PER_METHOD + (NODES_PER_BYTECODE * code_size);
1261 }
1262 
1263 // is_cold:  Return true if the node should never be inlined.
1264 // This is true if any of the key metrics are extreme.
1265 bool WarmCallInfo::is_cold() const {
1266   if (count()  <  WarmCallMinCount)        return true;
1267   if (profit() <  WarmCallMinProfit)       return true;
1268   if (work()   >  WarmCallMaxWork)         return true;
1269   if (size()   >  WarmCallMaxSize)         return true;
1270   return false;
1271 }
1272 
1273 // is_hot:  Return true if the node should be inlined immediately.
1274 // This is true if any of the key metrics are extreme.
1275 bool WarmCallInfo::is_hot() const {
1276   assert(!is_cold(), "eliminate is_cold cases before testing is_hot");
1277   if (count()  >= HotCallCountThreshold)   return true;
1278   if (profit() >= HotCallProfitThreshold)  return true;
1279   if (work()   <= HotCallTrivialWork)      return true;
1280   if (size()   <= HotCallTrivialSize)      return true;
1281   return false;
1282 }
1283 
1284 // compute_heat:
1285 float WarmCallInfo::compute_heat() const {
1286   assert(!is_cold(), "compute heat only on warm nodes");
1287   assert(!is_hot(),  "compute heat only on warm nodes");
1288   int min_size = MAX2(0,   (int)HotCallTrivialSize);
1289   int max_size = MIN2(500, (int)WarmCallMaxSize);
1290   float method_size = (size() - min_size) / MAX2(1, max_size - min_size);
1291   float size_factor;
1292   if      (method_size < 0.05)  size_factor = 4;   // 2 sigmas better than avg.
1293   else if (method_size < 0.15)  size_factor = 2;   // 1 sigma better than avg.
1294   else if (method_size < 0.5)   size_factor = 1;   // better than avg.
1295   else                          size_factor = 0.5; // worse than avg.
1296   return (count() * profit() * size_factor);
1297 }
1298 
1299 bool WarmCallInfo::warmer_than(WarmCallInfo* that) {
1300   assert(this != that, "compare only different WCIs");
1301   assert(this->heat() != 0 && that->heat() != 0, "call compute_heat 1st");
1302   if (this->heat() > that->heat())   return true;
1303   if (this->heat() < that->heat())   return false;
1304   assert(this->heat() == that->heat(), "no NaN heat allowed");
1305   // Equal heat.  Break the tie some other way.
1306   if (!this->call() || !that->call())  return (address)this > (address)that;
1307   return this->call()->_idx > that->call()->_idx;
1308 }
1309 
1310 //#define UNINIT_NEXT ((WarmCallInfo*)badAddress)
1311 #define UNINIT_NEXT ((WarmCallInfo*)NULL)
1312 
1313 WarmCallInfo* WarmCallInfo::insert_into(WarmCallInfo* head) {
1314   assert(next() == UNINIT_NEXT, "not yet on any list");
1315   WarmCallInfo* prev_p = NULL;
1316   WarmCallInfo* next_p = head;
1317   while (next_p != NULL && next_p->warmer_than(this)) {
1318     prev_p = next_p;
1319     next_p = prev_p->next();
1320   }
1321   // Install this between prev_p and next_p.
1322   this->set_next(next_p);
1323   if (prev_p == NULL)
1324     head = this;
1325   else
1326     prev_p->set_next(this);
1327   return head;
1328 }
1329 
1330 WarmCallInfo* WarmCallInfo::remove_from(WarmCallInfo* head) {
1331   WarmCallInfo* prev_p = NULL;
1332   WarmCallInfo* next_p = head;
1333   while (next_p != this) {
1334     assert(next_p != NULL, "this must be in the list somewhere");
1335     prev_p = next_p;
1336     next_p = prev_p->next();
1337   }
1338   next_p = this->next();
1339   debug_only(this->set_next(UNINIT_NEXT));
1340   // Remove this from between prev_p and next_p.
1341   if (prev_p == NULL)
1342     head = next_p;
1343   else
1344     prev_p->set_next(next_p);
1345   return head;
1346 }
1347 
1348 WarmCallInfo WarmCallInfo::_always_hot(WarmCallInfo::MAX_VALUE(), WarmCallInfo::MAX_VALUE(),
1349                                        WarmCallInfo::MIN_VALUE(), WarmCallInfo::MIN_VALUE());
1350 WarmCallInfo WarmCallInfo::_always_cold(WarmCallInfo::MIN_VALUE(), WarmCallInfo::MIN_VALUE(),
1351                                         WarmCallInfo::MAX_VALUE(), WarmCallInfo::MAX_VALUE());
1352 
1353 WarmCallInfo* WarmCallInfo::always_hot() {
1354   assert(_always_hot.is_hot(), "must always be hot");
1355   return &_always_hot;
1356 }
1357 
1358 WarmCallInfo* WarmCallInfo::always_cold() {
1359   assert(_always_cold.is_cold(), "must always be cold");
1360   return &_always_cold;
1361 }
1362 
1363 
1364 #ifndef PRODUCT
1365 
1366 void WarmCallInfo::print() const {
1367   tty->print("%s : C=%6.1f P=%6.1f W=%6.1f S=%6.1f H=%6.1f -> %p",
1368              is_cold() ? "cold" : is_hot() ? "hot " : "warm",
1369              count(), profit(), work(), size(), compute_heat(), next());
1370   tty->cr();
1371   if (call() != NULL)  call()->dump();
1372 }
1373 
1374 void print_wci(WarmCallInfo* ci) {
1375   ci->print();
1376 }
1377 
1378 void WarmCallInfo::print_all() const {
1379   for (const WarmCallInfo* p = this; p != NULL; p = p->next())
1380     p->print();
1381 }
1382 
1383 int WarmCallInfo::count_all() const {
1384   int cnt = 0;
1385   for (const WarmCallInfo* p = this; p != NULL; p = p->next())
1386     cnt++;
1387   return cnt;
1388 }
1389 
1390 #endif //PRODUCT