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