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