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