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