1 /*
   2  * Copyright (c) 2000, 2012, 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/cfgnode.hpp"
  37 #include "opto/connode.hpp"
  38 #include "opto/parse.hpp"
  39 #include "opto/rootnode.hpp"
  40 #include "opto/runtime.hpp"
  41 #include "opto/subnode.hpp"
  42 
  43 
  44 // Utility function.
  45 const TypeFunc* CallGenerator::tf() const {
  46   return TypeFunc::make(method());
  47 }
  48 
  49 //-----------------------------ParseGenerator---------------------------------
  50 // Internal class which handles all direct bytecode traversal.
  51 class ParseGenerator : public InlineCallGenerator {
  52 private:
  53   bool  _is_osr;
  54   float _expected_uses;
  55 
  56 public:
  57   ParseGenerator(ciMethod* method, float expected_uses, bool is_osr = false)
  58     : InlineCallGenerator(method)
  59   {
  60     _is_osr        = is_osr;
  61     _expected_uses = expected_uses;
  62     assert(InlineTree::check_can_parse(method) == NULL, "parse must be possible");
  63   }
  64 
  65   virtual bool      is_parse() const           { return true; }
  66   virtual JVMState* generate(JVMState* jvms);
  67   int is_osr() { return _is_osr; }
  68 
  69 };
  70 
  71 JVMState* ParseGenerator::generate(JVMState* jvms) {
  72   Compile* C = Compile::current();
  73 
  74   if (is_osr()) {
  75     // The JVMS for a OSR has a single argument (see its TypeFunc).
  76     assert(jvms->depth() == 1, "no inline OSR");
  77   }
  78 
  79   if (C->failing()) {
  80     return NULL;  // bailing out of the compile; do not try to parse
  81   }
  82 
  83   Parse parser(jvms, method(), _expected_uses);
  84   // Grab signature for matching/allocation
  85 #ifdef ASSERT
  86   if (parser.tf() != (parser.depth() == 1 ? C->tf() : tf())) {
  87     MutexLockerEx ml(Compile_lock, Mutex::_no_safepoint_check_flag);
  88     assert(C->env()->system_dictionary_modification_counter_changed(),
  89            "Must invalidate if TypeFuncs differ");
  90   }
  91 #endif
  92 
  93   GraphKit& exits = parser.exits();
  94 
  95   if (C->failing()) {
  96     while (exits.pop_exception_state() != NULL) ;
  97     return NULL;
  98   }
  99 
 100   assert(exits.jvms()->same_calls_as(jvms), "sanity");
 101 
 102   // Simply return the exit state of the parser,
 103   // augmented by any exceptional states.
 104   return exits.transfer_exceptions_into_jvms();
 105 }
 106 
 107 //---------------------------DirectCallGenerator------------------------------
 108 // Internal class which handles all out-of-line calls w/o receiver type checks.
 109 class DirectCallGenerator : public CallGenerator {
 110  private:
 111   CallStaticJavaNode* _call_node;
 112   // Force separate memory and I/O projections for the exceptional
 113   // paths to facilitate late inlinig.
 114   bool                _separate_io_proj;
 115 
 116  public:
 117   DirectCallGenerator(ciMethod* method, bool separate_io_proj)
 118     : CallGenerator(method),
 119       _separate_io_proj(separate_io_proj)
 120   {
 121   }
 122   virtual JVMState* generate(JVMState* jvms);
 123 
 124   CallStaticJavaNode* call_node() const { return _call_node; }
 125 };
 126 
 127 JVMState* DirectCallGenerator::generate(JVMState* jvms) {
 128   GraphKit kit(jvms);
 129   bool is_static = method()->is_static();
 130   address target = is_static ? SharedRuntime::get_resolve_static_call_stub()
 131                              : SharedRuntime::get_resolve_opt_virtual_call_stub();
 132 
 133   if (kit.C->log() != NULL) {
 134     kit.C->log()->elem("direct_call bci='%d'", jvms->bci());
 135   }
 136 
 137   CallStaticJavaNode *call = new (kit.C) CallStaticJavaNode(tf(), target, method(), kit.bci());
 138   _call_node = call;  // Save the call node in case we need it later
 139   if (!is_static) {
 140     // Make an explicit receiver null_check as part of this call.
 141     // Since we share a map with the caller, his JVMS gets adjusted.
 142     kit.null_check_receiver_before_call(method());
 143     if (kit.stopped()) {
 144       // And dump it back to the caller, decorated with any exceptions:
 145       return kit.transfer_exceptions_into_jvms();
 146     }
 147     // Mark the call node as virtual, sort of:
 148     call->set_optimized_virtual(true);
 149     if (method()->is_method_handle_intrinsic() ||
 150         method()->is_compiled_lambda_form()) {
 151       call->set_method_handle_invoke(true);
 152     }
 153   }
 154   kit.set_arguments_for_java_call(call);
 155   kit.set_edges_for_java_call(call, false, _separate_io_proj);
 156   Node* ret = kit.set_results_for_java_call(call, _separate_io_proj);
 157   kit.push_node(method()->return_type()->basic_type(), ret);
 158   return kit.transfer_exceptions_into_jvms();
 159 }
 160 
 161 //--------------------------VirtualCallGenerator------------------------------
 162 // Internal class which handles all out-of-line calls checking receiver type.
 163 class VirtualCallGenerator : public CallGenerator {
 164 private:
 165   int _vtable_index;
 166 public:
 167   VirtualCallGenerator(ciMethod* method, int vtable_index)
 168     : CallGenerator(method), _vtable_index(vtable_index)
 169   {
 170     assert(vtable_index == Method::invalid_vtable_index ||
 171            vtable_index >= 0, "either invalid or usable");
 172   }
 173   virtual bool      is_virtual() const          { return true; }
 174   virtual JVMState* generate(JVMState* jvms);
 175 };
 176 
 177 JVMState* VirtualCallGenerator::generate(JVMState* jvms) {
 178   GraphKit kit(jvms);
 179   Node* receiver = kit.argument(0);
 180 
 181   if (kit.C->log() != NULL) {
 182     kit.C->log()->elem("virtual_call bci='%d'", jvms->bci());
 183   }
 184 
 185   // If the receiver is a constant null, do not torture the system
 186   // by attempting to call through it.  The compile will proceed
 187   // correctly, but may bail out in final_graph_reshaping, because
 188   // the call instruction will have a seemingly deficient out-count.
 189   // (The bailout says something misleading about an "infinite loop".)
 190   if (kit.gvn().type(receiver)->higher_equal(TypePtr::NULL_PTR)) {
 191     kit.inc_sp(method()->arg_size());  // restore arguments
 192     kit.uncommon_trap(Deoptimization::Reason_null_check,
 193                       Deoptimization::Action_none,
 194                       NULL, "null receiver");
 195     return kit.transfer_exceptions_into_jvms();
 196   }
 197 
 198   // Ideally we would unconditionally do a null check here and let it
 199   // be converted to an implicit check based on profile information.
 200   // However currently the conversion to implicit null checks in
 201   // Block::implicit_null_check() only looks for loads and stores, not calls.
 202   ciMethod *caller = kit.method();
 203   ciMethodData *caller_md = (caller == NULL) ? NULL : caller->method_data();
 204   if (!UseInlineCaches || !ImplicitNullChecks ||
 205        ((ImplicitNullCheckThreshold > 0) && caller_md &&
 206        (caller_md->trap_count(Deoptimization::Reason_null_check)
 207        >= (uint)ImplicitNullCheckThreshold))) {
 208     // Make an explicit receiver null_check as part of this call.
 209     // Since we share a map with the caller, his JVMS gets adjusted.
 210     receiver = kit.null_check_receiver_before_call(method());
 211     if (kit.stopped()) {
 212       // And dump it back to the caller, decorated with any exceptions:
 213       return kit.transfer_exceptions_into_jvms();
 214     }
 215   }
 216 
 217   assert(!method()->is_static(), "virtual call must not be to static");
 218   assert(!method()->is_final(), "virtual call should not be to final");
 219   assert(!method()->is_private(), "virtual call should not be to private");
 220   assert(_vtable_index == Method::invalid_vtable_index || !UseInlineCaches,
 221          "no vtable calls if +UseInlineCaches ");
 222   address target = SharedRuntime::get_resolve_virtual_call_stub();
 223   // Normal inline cache used for call
 224   CallDynamicJavaNode *call = new (kit.C) CallDynamicJavaNode(tf(), target, method(), _vtable_index, kit.bci());
 225   kit.set_arguments_for_java_call(call);
 226   kit.set_edges_for_java_call(call);
 227   Node* ret = kit.set_results_for_java_call(call);
 228   kit.push_node(method()->return_type()->basic_type(), ret);
 229 
 230   // Represent the effect of an implicit receiver null_check
 231   // as part of this call.  Since we share a map with the caller,
 232   // his JVMS gets adjusted.
 233   kit.cast_not_null(receiver);
 234   return kit.transfer_exceptions_into_jvms();
 235 }
 236 
 237 CallGenerator* CallGenerator::for_inline(ciMethod* m, float expected_uses) {
 238   if (InlineTree::check_can_parse(m) != NULL)  return NULL;
 239   return new ParseGenerator(m, expected_uses);
 240 }
 241 
 242 // As a special case, the JVMS passed to this CallGenerator is
 243 // for the method execution already in progress, not just the JVMS
 244 // of the caller.  Thus, this CallGenerator cannot be mixed with others!
 245 CallGenerator* CallGenerator::for_osr(ciMethod* m, int osr_bci) {
 246   if (InlineTree::check_can_parse(m) != NULL)  return NULL;
 247   float past_uses = m->interpreter_invocation_count();
 248   float expected_uses = past_uses;
 249   return new ParseGenerator(m, expected_uses, true);
 250 }
 251 
 252 CallGenerator* CallGenerator::for_direct_call(ciMethod* m, bool separate_io_proj) {
 253   assert(!m->is_abstract(), "for_direct_call mismatch");
 254   return new DirectCallGenerator(m, separate_io_proj);
 255 }
 256 
 257 CallGenerator* CallGenerator::for_virtual_call(ciMethod* m, int vtable_index) {
 258   assert(!m->is_static(), "for_virtual_call mismatch");
 259   assert(!m->is_method_handle_intrinsic(), "should be a direct call");
 260   return new VirtualCallGenerator(m, vtable_index);
 261 }
 262 
 263 // Allow inlining decisions to be delayed
 264 class LateInlineCallGenerator : public DirectCallGenerator {
 265   CallGenerator* _inline_cg;
 266 
 267  public:
 268   LateInlineCallGenerator(ciMethod* method, CallGenerator* inline_cg) :
 269     DirectCallGenerator(method, true), _inline_cg(inline_cg) {}
 270 
 271   virtual bool      is_late_inline() const { return true; }
 272 
 273   // Convert the CallStaticJava into an inline
 274   virtual void do_late_inline();
 275 
 276   virtual JVMState* generate(JVMState* jvms) {
 277     // Record that this call site should be revisited once the main
 278     // parse is finished.
 279     Compile::current()->add_late_inline(this);
 280 
 281     // Emit the CallStaticJava and request separate projections so
 282     // that the late inlining logic can distinguish between fall
 283     // through and exceptional uses of the memory and io projections
 284     // as is done for allocations and macro expansion.
 285     return DirectCallGenerator::generate(jvms);
 286   }
 287 
 288 };
 289 
 290 
 291 void LateInlineCallGenerator::do_late_inline() {
 292   // Can't inline it
 293   if (call_node() == NULL || call_node()->outcnt() == 0 ||
 294       call_node()->in(0) == NULL || call_node()->in(0)->is_top())
 295     return;
 296 
 297   CallStaticJavaNode* call = call_node();
 298 
 299   // Make a clone of the JVMState that appropriate to use for driving a parse
 300   Compile* C = Compile::current();
 301   JVMState* jvms     = call->jvms()->clone_shallow(C);
 302   uint size = call->req();
 303   SafePointNode* map = new (C) SafePointNode(size, jvms);
 304   for (uint i1 = 0; i1 < size; i1++) {
 305     map->init_req(i1, call->in(i1));
 306   }
 307 
 308   // Make sure the state is a MergeMem for parsing.
 309   if (!map->in(TypeFunc::Memory)->is_MergeMem()) {
 310     map->set_req(TypeFunc::Memory, MergeMemNode::make(C, map->in(TypeFunc::Memory)));
 311   }
 312 
 313   // Make enough space for the expression stack and transfer the incoming arguments
 314   int nargs    = method()->arg_size();
 315   jvms->set_map(map);
 316   map->ensure_stack(jvms, jvms->method()->max_stack());
 317   if (nargs > 0) {
 318     for (int i1 = 0; i1 < nargs; i1++) {
 319       map->set_req(i1 + jvms->argoff(), call->in(TypeFunc::Parms + i1));
 320     }
 321   }
 322 
 323   CompileLog* log = C->log();
 324   if (log != NULL) {
 325     log->head("late_inline method='%d'", log->identify(method()));
 326     JVMState* p = jvms;
 327     while (p != NULL) {
 328       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
 329       p = p->caller();
 330     }
 331     log->tail("late_inline");
 332   }
 333 
 334   // Setup default node notes to be picked up by the inlining
 335   Node_Notes* old_nn = C->default_node_notes();
 336   if (old_nn != NULL) {
 337     Node_Notes* entry_nn = old_nn->clone(C);
 338     entry_nn->set_jvms(jvms);
 339     C->set_default_node_notes(entry_nn);
 340   }
 341 
 342   // Now perform the inling using the synthesized JVMState
 343   JVMState* new_jvms = _inline_cg->generate(jvms);
 344   if (new_jvms == NULL)  return;  // no change
 345   if (C->failing())      return;
 346 
 347   // Capture any exceptional control flow
 348   GraphKit kit(new_jvms);
 349 
 350   // Find the result object
 351   Node* result = C->top();
 352   int   result_size = method()->return_type()->size();
 353   if (result_size != 0 && !kit.stopped()) {
 354     result = (result_size == 1) ? kit.pop() : kit.pop_pair();
 355   }
 356 
 357   kit.replace_call(call, result);
 358 }
 359 
 360 
 361 CallGenerator* CallGenerator::for_late_inline(ciMethod* method, CallGenerator* inline_cg) {
 362   return new LateInlineCallGenerator(method, inline_cg);
 363 }
 364 
 365 
 366 //---------------------------WarmCallGenerator--------------------------------
 367 // Internal class which handles initial deferral of inlining decisions.
 368 class WarmCallGenerator : public CallGenerator {
 369   WarmCallInfo*   _call_info;
 370   CallGenerator*  _if_cold;
 371   CallGenerator*  _if_hot;
 372   bool            _is_virtual;   // caches virtuality of if_cold
 373   bool            _is_inline;    // caches inline-ness of if_hot
 374 
 375 public:
 376   WarmCallGenerator(WarmCallInfo* ci,
 377                     CallGenerator* if_cold,
 378                     CallGenerator* if_hot)
 379     : CallGenerator(if_cold->method())
 380   {
 381     assert(method() == if_hot->method(), "consistent choices");
 382     _call_info  = ci;
 383     _if_cold    = if_cold;
 384     _if_hot     = if_hot;
 385     _is_virtual = if_cold->is_virtual();
 386     _is_inline  = if_hot->is_inline();
 387   }
 388 
 389   virtual bool      is_inline() const           { return _is_inline; }
 390   virtual bool      is_virtual() const          { return _is_virtual; }
 391   virtual bool      is_deferred() const         { return true; }
 392 
 393   virtual JVMState* generate(JVMState* jvms);
 394 };
 395 
 396 
 397 CallGenerator* CallGenerator::for_warm_call(WarmCallInfo* ci,
 398                                             CallGenerator* if_cold,
 399                                             CallGenerator* if_hot) {
 400   return new WarmCallGenerator(ci, if_cold, if_hot);
 401 }
 402 
 403 JVMState* WarmCallGenerator::generate(JVMState* jvms) {
 404   Compile* C = Compile::current();
 405   if (C->log() != NULL) {
 406     C->log()->elem("warm_call bci='%d'", jvms->bci());
 407   }
 408   jvms = _if_cold->generate(jvms);
 409   if (jvms != NULL) {
 410     Node* m = jvms->map()->control();
 411     if (m->is_CatchProj()) m = m->in(0);  else m = C->top();
 412     if (m->is_Catch())     m = m->in(0);  else m = C->top();
 413     if (m->is_Proj())      m = m->in(0);  else m = C->top();
 414     if (m->is_CallJava()) {
 415       _call_info->set_call(m->as_Call());
 416       _call_info->set_hot_cg(_if_hot);
 417 #ifndef PRODUCT
 418       if (PrintOpto || PrintOptoInlining) {
 419         tty->print_cr("Queueing for warm inlining at bci %d:", jvms->bci());
 420         tty->print("WCI: ");
 421         _call_info->print();
 422       }
 423 #endif
 424       _call_info->set_heat(_call_info->compute_heat());
 425       C->set_warm_calls(_call_info->insert_into(C->warm_calls()));
 426     }
 427   }
 428   return jvms;
 429 }
 430 
 431 void WarmCallInfo::make_hot() {
 432   Unimplemented();
 433 }
 434 
 435 void WarmCallInfo::make_cold() {
 436   // No action:  Just dequeue.
 437 }
 438 
 439 
 440 //------------------------PredictedCallGenerator------------------------------
 441 // Internal class which handles all out-of-line calls checking receiver type.
 442 class PredictedCallGenerator : public CallGenerator {
 443   ciKlass*       _predicted_receiver;
 444   CallGenerator* _if_missed;
 445   CallGenerator* _if_hit;
 446   float          _hit_prob;
 447 
 448 public:
 449   PredictedCallGenerator(ciKlass* predicted_receiver,
 450                          CallGenerator* if_missed,
 451                          CallGenerator* if_hit, float hit_prob)
 452     : CallGenerator(if_missed->method())
 453   {
 454     // The call profile data may predict the hit_prob as extreme as 0 or 1.
 455     // Remove the extremes values from the range.
 456     if (hit_prob > PROB_MAX)   hit_prob = PROB_MAX;
 457     if (hit_prob < PROB_MIN)   hit_prob = PROB_MIN;
 458 
 459     _predicted_receiver = predicted_receiver;
 460     _if_missed          = if_missed;
 461     _if_hit             = if_hit;
 462     _hit_prob           = hit_prob;
 463   }
 464 
 465   virtual bool      is_virtual()   const    { return true; }
 466   virtual bool      is_inline()    const    { return _if_hit->is_inline(); }
 467   virtual bool      is_deferred()  const    { return _if_hit->is_deferred(); }
 468 
 469   virtual JVMState* generate(JVMState* jvms);
 470 };
 471 
 472 
 473 CallGenerator* CallGenerator::for_predicted_call(ciKlass* predicted_receiver,
 474                                                  CallGenerator* if_missed,
 475                                                  CallGenerator* if_hit,
 476                                                  float hit_prob) {
 477   return new PredictedCallGenerator(predicted_receiver, if_missed, if_hit, hit_prob);
 478 }
 479 
 480 
 481 JVMState* PredictedCallGenerator::generate(JVMState* jvms) {
 482   GraphKit kit(jvms);
 483   PhaseGVN& gvn = kit.gvn();
 484   // We need an explicit receiver null_check before checking its type.
 485   // We share a map with the caller, so his JVMS gets adjusted.
 486   Node* receiver = kit.argument(0);
 487 
 488   CompileLog* log = kit.C->log();
 489   if (log != NULL) {
 490     log->elem("predicted_call bci='%d' klass='%d'",
 491               jvms->bci(), log->identify(_predicted_receiver));
 492   }
 493 
 494   receiver = kit.null_check_receiver_before_call(method());
 495   if (kit.stopped()) {
 496     return kit.transfer_exceptions_into_jvms();
 497   }
 498 
 499   Node* exact_receiver = receiver;  // will get updated in place...
 500   Node* slow_ctl = kit.type_check_receiver(receiver,
 501                                            _predicted_receiver, _hit_prob,
 502                                            &exact_receiver);
 503 
 504   SafePointNode* slow_map = NULL;
 505   JVMState* slow_jvms;
 506   { PreserveJVMState pjvms(&kit);
 507     kit.set_control(slow_ctl);
 508     if (!kit.stopped()) {
 509       slow_jvms = _if_missed->generate(kit.sync_jvms());
 510       if (kit.failing())
 511         return NULL;  // might happen because of NodeCountInliningCutoff
 512       assert(slow_jvms != NULL, "must be");
 513       kit.add_exception_states_from(slow_jvms);
 514       kit.set_map(slow_jvms->map());
 515       if (!kit.stopped())
 516         slow_map = kit.stop();
 517     }
 518   }
 519 
 520   if (kit.stopped()) {
 521     // Instance exactly does not matches the desired type.
 522     kit.set_jvms(slow_jvms);
 523     return kit.transfer_exceptions_into_jvms();
 524   }
 525 
 526   // fall through if the instance exactly matches the desired type
 527   kit.replace_in_map(receiver, exact_receiver);
 528 
 529   // Make the hot call:
 530   JVMState* new_jvms = _if_hit->generate(kit.sync_jvms());
 531   if (new_jvms == NULL) {
 532     // Inline failed, so make a direct call.
 533     assert(_if_hit->is_inline(), "must have been a failed inline");
 534     CallGenerator* cg = CallGenerator::for_direct_call(_if_hit->method());
 535     new_jvms = cg->generate(kit.sync_jvms());
 536   }
 537   kit.add_exception_states_from(new_jvms);
 538   kit.set_jvms(new_jvms);
 539 
 540   // Need to merge slow and fast?
 541   if (slow_map == NULL) {
 542     // The fast path is the only path remaining.
 543     return kit.transfer_exceptions_into_jvms();
 544   }
 545 
 546   if (kit.stopped()) {
 547     // Inlined method threw an exception, so it's just the slow path after all.
 548     kit.set_jvms(slow_jvms);
 549     return kit.transfer_exceptions_into_jvms();
 550   }
 551 
 552   // Finish the diamond.
 553   kit.C->set_has_split_ifs(true); // Has chance for split-if optimization
 554   RegionNode* region = new (kit.C) RegionNode(3);
 555   region->init_req(1, kit.control());
 556   region->init_req(2, slow_map->control());
 557   kit.set_control(gvn.transform(region));
 558   Node* iophi = PhiNode::make(region, kit.i_o(), Type::ABIO);
 559   iophi->set_req(2, slow_map->i_o());
 560   kit.set_i_o(gvn.transform(iophi));
 561   kit.merge_memory(slow_map->merged_memory(), region, 2);
 562   uint tos = kit.jvms()->stkoff() + kit.sp();
 563   uint limit = slow_map->req();
 564   for (uint i = TypeFunc::Parms; i < limit; i++) {
 565     // Skip unused stack slots; fast forward to monoff();
 566     if (i == tos) {
 567       i = kit.jvms()->monoff();
 568       if( i >= limit ) break;
 569     }
 570     Node* m = kit.map()->in(i);
 571     Node* n = slow_map->in(i);
 572     if (m != n) {
 573       const Type* t = gvn.type(m)->meet(gvn.type(n));
 574       Node* phi = PhiNode::make(region, m, t);
 575       phi->set_req(2, n);
 576       kit.map()->set_req(i, gvn.transform(phi));
 577     }
 578   }
 579   return kit.transfer_exceptions_into_jvms();
 580 }
 581 
 582 
 583 CallGenerator* CallGenerator::for_method_handle_call(JVMState* jvms, ciMethod* caller, ciMethod* callee) {
 584   assert(callee->is_method_handle_intrinsic() ||
 585          callee->is_compiled_lambda_form(), "for_method_handle_call mismatch");
 586   CallGenerator* cg = CallGenerator::for_method_handle_inline(jvms, caller, callee);
 587   if (cg != NULL)
 588     return cg;
 589   return CallGenerator::for_direct_call(callee);
 590 }
 591 
 592 CallGenerator* CallGenerator::for_method_handle_inline(JVMState* jvms, ciMethod* caller, ciMethod* callee) {
 593   GraphKit kit(jvms);
 594   PhaseGVN& gvn = kit.gvn();
 595   Compile* C = kit.C;
 596   vmIntrinsics::ID iid = callee->intrinsic_id();
 597   switch (iid) {
 598   case vmIntrinsics::_invokeBasic:
 599     {
 600       // Get MethodHandle receiver:
 601       Node* receiver = kit.argument(0);
 602       if (receiver->Opcode() == Op_ConP) {
 603         const TypeOopPtr* oop_ptr = receiver->bottom_type()->is_oopptr();
 604         ciMethod* target = oop_ptr->const_oop()->as_method_handle()->get_vmtarget();
 605         guarantee(!target->is_method_handle_intrinsic(), "should not happen");  // XXX remove
 606         const int vtable_index = Method::invalid_vtable_index;
 607         CallGenerator* cg = C->call_generator(target, vtable_index, false, jvms, true, PROB_ALWAYS);
 608         if (cg != NULL && cg->is_inline())
 609           return cg;
 610       } else {
 611         if (PrintInlining)  CompileTask::print_inlining(callee, jvms->depth() - 1, jvms->bci(), "receiver not constant");
 612       }
 613     }
 614     break;
 615 
 616   case vmIntrinsics::_linkToVirtual:
 617   case vmIntrinsics::_linkToStatic:
 618   case vmIntrinsics::_linkToSpecial:
 619   case vmIntrinsics::_linkToInterface:
 620     {
 621       // Get MemberName argument:
 622       Node* member_name = kit.argument(callee->arg_size() - 1);
 623       if (member_name->Opcode() == Op_ConP) {
 624         const TypeOopPtr* oop_ptr = member_name->bottom_type()->is_oopptr();
 625         ciMethod* target = oop_ptr->const_oop()->as_member_name()->get_vmtarget();
 626 
 627         // In lamda forms we erase signature types to avoid resolving issues
 628         // involving class loaders.  When we optimize a method handle invoke
 629         // to a direct call we must cast the receiver and arguments to its
 630         // actual types.
 631         ciSignature* signature = target->signature();
 632         const int receiver_skip = target->is_static() ? 0 : 1;
 633         // Cast receiver to its type.
 634         if (!target->is_static()) {
 635           Node* arg = kit.argument(0);
 636           const TypeOopPtr* arg_type = arg->bottom_type()->isa_oopptr();
 637           const Type*       sig_type = TypeOopPtr::make_from_klass(signature->accessing_klass());
 638           if (arg_type != NULL && !arg_type->higher_equal(sig_type)) {
 639             Node* cast_obj = gvn.transform(new (C) CheckCastPPNode(kit.control(), arg, sig_type));
 640             kit.set_argument(0, cast_obj);
 641           }
 642         }
 643         // Cast reference arguments to its type.
 644         for (int i = 0; i < signature->count(); i++) {
 645           ciType* t = signature->type_at(i);
 646           if (t->is_klass()) {
 647             Node* arg = kit.argument(receiver_skip + i);
 648             const TypeOopPtr* arg_type = arg->bottom_type()->isa_oopptr();
 649             const Type*       sig_type = TypeOopPtr::make_from_klass(t->as_klass());
 650             if (arg_type != NULL && !arg_type->higher_equal(sig_type)) {
 651               Node* cast_obj = gvn.transform(new (C) CheckCastPPNode(kit.control(), arg, sig_type));
 652               kit.set_argument(receiver_skip + i, cast_obj);
 653             }
 654           }
 655         }
 656         const int vtable_index = Method::invalid_vtable_index;
 657         const bool call_is_virtual = target->is_abstract();  // FIXME workaround
 658         CallGenerator* cg = C->call_generator(target, vtable_index, call_is_virtual, jvms, true, PROB_ALWAYS);
 659         if (cg != NULL && cg->is_inline())
 660           return cg;
 661       }
 662     }
 663     break;
 664 
 665   default:
 666     fatal(err_msg_res("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid)));
 667     break;
 668   }
 669   return NULL;
 670 }
 671 
 672 
 673 //------------------------PredictedIntrinsicGenerator------------------------------
 674 // Internal class which handles all predicted Intrinsic calls.
 675 class PredictedIntrinsicGenerator : public CallGenerator {
 676   CallGenerator* _intrinsic;
 677   CallGenerator* _cg;
 678 
 679 public:
 680   PredictedIntrinsicGenerator(CallGenerator* intrinsic,
 681                               CallGenerator* cg)
 682     : CallGenerator(cg->method())
 683   {
 684     _intrinsic = intrinsic;
 685     _cg        = cg;
 686   }
 687 
 688   virtual bool      is_virtual()   const    { return true; }
 689   virtual bool      is_inlined()   const    { return true; }
 690   virtual bool      is_intrinsic() const    { return true; }
 691 
 692   virtual JVMState* generate(JVMState* jvms);
 693 };
 694 
 695 
 696 CallGenerator* CallGenerator::for_predicted_intrinsic(CallGenerator* intrinsic,
 697                                                       CallGenerator* cg) {
 698   return new PredictedIntrinsicGenerator(intrinsic, cg);
 699 }
 700 
 701 
 702 JVMState* PredictedIntrinsicGenerator::generate(JVMState* jvms) {
 703   GraphKit kit(jvms);
 704   PhaseGVN& gvn = kit.gvn();
 705 
 706   CompileLog* log = kit.C->log();
 707   if (log != NULL) {
 708     log->elem("predicted_intrinsic bci='%d' method='%d'",
 709               jvms->bci(), log->identify(method()));
 710   }
 711 
 712   Node* slow_ctl = _intrinsic->generate_predicate(kit.sync_jvms());
 713   if (kit.failing())
 714     return NULL;  // might happen because of NodeCountInliningCutoff
 715 
 716   SafePointNode* slow_map = NULL;
 717   JVMState* slow_jvms;
 718   if (slow_ctl != NULL) {
 719     PreserveJVMState pjvms(&kit);
 720     kit.set_control(slow_ctl);
 721     if (!kit.stopped()) {
 722       slow_jvms = _cg->generate(kit.sync_jvms());
 723       if (kit.failing())
 724         return NULL;  // might happen because of NodeCountInliningCutoff
 725       assert(slow_jvms != NULL, "must be");
 726       kit.add_exception_states_from(slow_jvms);
 727       kit.set_map(slow_jvms->map());
 728       if (!kit.stopped())
 729         slow_map = kit.stop();
 730     }
 731   }
 732 
 733   if (kit.stopped()) {
 734     // Predicate is always false.
 735     kit.set_jvms(slow_jvms);
 736     return kit.transfer_exceptions_into_jvms();
 737   }
 738 
 739   // Generate intrinsic code:
 740   JVMState* new_jvms = _intrinsic->generate(kit.sync_jvms());
 741   if (new_jvms == NULL) {
 742     // Intrinsic failed, so use slow code or make a direct call.
 743     if (slow_map == NULL) {
 744       CallGenerator* cg = CallGenerator::for_direct_call(method());
 745       new_jvms = cg->generate(kit.sync_jvms());
 746     } else {
 747       kit.set_jvms(slow_jvms);
 748       return kit.transfer_exceptions_into_jvms();
 749     }
 750   }
 751   kit.add_exception_states_from(new_jvms);
 752   kit.set_jvms(new_jvms);
 753 
 754   // Need to merge slow and fast?
 755   if (slow_map == NULL) {
 756     // The fast path is the only path remaining.
 757     return kit.transfer_exceptions_into_jvms();
 758   }
 759 
 760   if (kit.stopped()) {
 761     // Intrinsic method threw an exception, so it's just the slow path after all.
 762     kit.set_jvms(slow_jvms);
 763     return kit.transfer_exceptions_into_jvms();
 764   }
 765 
 766   // Finish the diamond.
 767   kit.C->set_has_split_ifs(true); // Has chance for split-if optimization
 768   RegionNode* region = new (kit.C) RegionNode(3);
 769   region->init_req(1, kit.control());
 770   region->init_req(2, slow_map->control());
 771   kit.set_control(gvn.transform(region));
 772   Node* iophi = PhiNode::make(region, kit.i_o(), Type::ABIO);
 773   iophi->set_req(2, slow_map->i_o());
 774   kit.set_i_o(gvn.transform(iophi));
 775   kit.merge_memory(slow_map->merged_memory(), region, 2);
 776   uint tos = kit.jvms()->stkoff() + kit.sp();
 777   uint limit = slow_map->req();
 778   for (uint i = TypeFunc::Parms; i < limit; i++) {
 779     // Skip unused stack slots; fast forward to monoff();
 780     if (i == tos) {
 781       i = kit.jvms()->monoff();
 782       if( i >= limit ) break;
 783     }
 784     Node* m = kit.map()->in(i);
 785     Node* n = slow_map->in(i);
 786     if (m != n) {
 787       const Type* t = gvn.type(m)->meet(gvn.type(n));
 788       Node* phi = PhiNode::make(region, m, t);
 789       phi->set_req(2, n);
 790       kit.map()->set_req(i, gvn.transform(phi));
 791     }
 792   }
 793   return kit.transfer_exceptions_into_jvms();
 794 }
 795 
 796 //-------------------------UncommonTrapCallGenerator-----------------------------
 797 // Internal class which handles all out-of-line calls checking receiver type.
 798 class UncommonTrapCallGenerator : public CallGenerator {
 799   Deoptimization::DeoptReason _reason;
 800   Deoptimization::DeoptAction _action;
 801 
 802 public:
 803   UncommonTrapCallGenerator(ciMethod* m,
 804                             Deoptimization::DeoptReason reason,
 805                             Deoptimization::DeoptAction action)
 806     : CallGenerator(m)
 807   {
 808     _reason = reason;
 809     _action = action;
 810   }
 811 
 812   virtual bool      is_virtual() const          { ShouldNotReachHere(); return false; }
 813   virtual bool      is_trap() const             { return true; }
 814 
 815   virtual JVMState* generate(JVMState* jvms);
 816 };
 817 
 818 
 819 CallGenerator*
 820 CallGenerator::for_uncommon_trap(ciMethod* m,
 821                                  Deoptimization::DeoptReason reason,
 822                                  Deoptimization::DeoptAction action) {
 823   return new UncommonTrapCallGenerator(m, reason, action);
 824 }
 825 
 826 
 827 JVMState* UncommonTrapCallGenerator::generate(JVMState* jvms) {
 828   GraphKit kit(jvms);
 829   // Take the trap with arguments pushed on the stack.  (Cf. null_check_receiver).
 830   int nargs = method()->arg_size();
 831   kit.inc_sp(nargs);
 832   assert(nargs <= kit.sp() && kit.sp() <= jvms->stk_size(), "sane sp w/ args pushed");
 833   if (_reason == Deoptimization::Reason_class_check &&
 834       _action == Deoptimization::Action_maybe_recompile) {
 835     // Temp fix for 6529811
 836     // Don't allow uncommon_trap to override our decision to recompile in the event
 837     // of a class cast failure for a monomorphic call as it will never let us convert
 838     // the call to either bi-morphic or megamorphic and can lead to unc-trap loops
 839     bool keep_exact_action = true;
 840     kit.uncommon_trap(_reason, _action, NULL, "monomorphic vcall checkcast", false, keep_exact_action);
 841   } else {
 842     kit.uncommon_trap(_reason, _action);
 843   }
 844   return kit.transfer_exceptions_into_jvms();
 845 }
 846 
 847 // (Note:  Moved hook_up_call to GraphKit::set_edges_for_java_call.)
 848 
 849 // (Node:  Merged hook_up_exits into ParseGenerator::generate.)
 850 
 851 #define NODES_OVERHEAD_PER_METHOD (30.0)
 852 #define NODES_PER_BYTECODE (9.5)
 853 
 854 void WarmCallInfo::init(JVMState* call_site, ciMethod* call_method, ciCallProfile& profile, float prof_factor) {
 855   int call_count = profile.count();
 856   int code_size = call_method->code_size();
 857 
 858   // Expected execution count is based on the historical count:
 859   _count = call_count < 0 ? 1 : call_site->method()->scale_count(call_count, prof_factor);
 860 
 861   // Expected profit from inlining, in units of simple call-overheads.
 862   _profit = 1.0;
 863 
 864   // Expected work performed by the call in units of call-overheads.
 865   // %%% need an empirical curve fit for "work" (time in call)
 866   float bytecodes_per_call = 3;
 867   _work = 1.0 + code_size / bytecodes_per_call;
 868 
 869   // Expected size of compilation graph:
 870   // -XX:+PrintParseStatistics once reported:
 871   //  Methods seen: 9184  Methods parsed: 9184  Nodes created: 1582391
 872   //  Histogram of 144298 parsed bytecodes:
 873   // %%% Need an better predictor for graph size.
 874   _size = NODES_OVERHEAD_PER_METHOD + (NODES_PER_BYTECODE * code_size);
 875 }
 876 
 877 // is_cold:  Return true if the node should never be inlined.
 878 // This is true if any of the key metrics are extreme.
 879 bool WarmCallInfo::is_cold() const {
 880   if (count()  <  WarmCallMinCount)        return true;
 881   if (profit() <  WarmCallMinProfit)       return true;
 882   if (work()   >  WarmCallMaxWork)         return true;
 883   if (size()   >  WarmCallMaxSize)         return true;
 884   return false;
 885 }
 886 
 887 // is_hot:  Return true if the node should be inlined immediately.
 888 // This is true if any of the key metrics are extreme.
 889 bool WarmCallInfo::is_hot() const {
 890   assert(!is_cold(), "eliminate is_cold cases before testing is_hot");
 891   if (count()  >= HotCallCountThreshold)   return true;
 892   if (profit() >= HotCallProfitThreshold)  return true;
 893   if (work()   <= HotCallTrivialWork)      return true;
 894   if (size()   <= HotCallTrivialSize)      return true;
 895   return false;
 896 }
 897 
 898 // compute_heat:
 899 float WarmCallInfo::compute_heat() const {
 900   assert(!is_cold(), "compute heat only on warm nodes");
 901   assert(!is_hot(),  "compute heat only on warm nodes");
 902   int min_size = MAX2(0,   (int)HotCallTrivialSize);
 903   int max_size = MIN2(500, (int)WarmCallMaxSize);
 904   float method_size = (size() - min_size) / MAX2(1, max_size - min_size);
 905   float size_factor;
 906   if      (method_size < 0.05)  size_factor = 4;   // 2 sigmas better than avg.
 907   else if (method_size < 0.15)  size_factor = 2;   // 1 sigma better than avg.
 908   else if (method_size < 0.5)   size_factor = 1;   // better than avg.
 909   else                          size_factor = 0.5; // worse than avg.
 910   return (count() * profit() * size_factor);
 911 }
 912 
 913 bool WarmCallInfo::warmer_than(WarmCallInfo* that) {
 914   assert(this != that, "compare only different WCIs");
 915   assert(this->heat() != 0 && that->heat() != 0, "call compute_heat 1st");
 916   if (this->heat() > that->heat())   return true;
 917   if (this->heat() < that->heat())   return false;
 918   assert(this->heat() == that->heat(), "no NaN heat allowed");
 919   // Equal heat.  Break the tie some other way.
 920   if (!this->call() || !that->call())  return (address)this > (address)that;
 921   return this->call()->_idx > that->call()->_idx;
 922 }
 923 
 924 //#define UNINIT_NEXT ((WarmCallInfo*)badAddress)
 925 #define UNINIT_NEXT ((WarmCallInfo*)NULL)
 926 
 927 WarmCallInfo* WarmCallInfo::insert_into(WarmCallInfo* head) {
 928   assert(next() == UNINIT_NEXT, "not yet on any list");
 929   WarmCallInfo* prev_p = NULL;
 930   WarmCallInfo* next_p = head;
 931   while (next_p != NULL && next_p->warmer_than(this)) {
 932     prev_p = next_p;
 933     next_p = prev_p->next();
 934   }
 935   // Install this between prev_p and next_p.
 936   this->set_next(next_p);
 937   if (prev_p == NULL)
 938     head = this;
 939   else
 940     prev_p->set_next(this);
 941   return head;
 942 }
 943 
 944 WarmCallInfo* WarmCallInfo::remove_from(WarmCallInfo* head) {
 945   WarmCallInfo* prev_p = NULL;
 946   WarmCallInfo* next_p = head;
 947   while (next_p != this) {
 948     assert(next_p != NULL, "this must be in the list somewhere");
 949     prev_p = next_p;
 950     next_p = prev_p->next();
 951   }
 952   next_p = this->next();
 953   debug_only(this->set_next(UNINIT_NEXT));
 954   // Remove this from between prev_p and next_p.
 955   if (prev_p == NULL)
 956     head = next_p;
 957   else
 958     prev_p->set_next(next_p);
 959   return head;
 960 }
 961 
 962 WarmCallInfo WarmCallInfo::_always_hot(WarmCallInfo::MAX_VALUE(), WarmCallInfo::MAX_VALUE(),
 963                                        WarmCallInfo::MIN_VALUE(), WarmCallInfo::MIN_VALUE());
 964 WarmCallInfo WarmCallInfo::_always_cold(WarmCallInfo::MIN_VALUE(), WarmCallInfo::MIN_VALUE(),
 965                                         WarmCallInfo::MAX_VALUE(), WarmCallInfo::MAX_VALUE());
 966 
 967 WarmCallInfo* WarmCallInfo::always_hot() {
 968   assert(_always_hot.is_hot(), "must always be hot");
 969   return &_always_hot;
 970 }
 971 
 972 WarmCallInfo* WarmCallInfo::always_cold() {
 973   assert(_always_cold.is_cold(), "must always be cold");
 974   return &_always_cold;
 975 }
 976 
 977 
 978 #ifndef PRODUCT
 979 
 980 void WarmCallInfo::print() const {
 981   tty->print("%s : C=%6.1f P=%6.1f W=%6.1f S=%6.1f H=%6.1f -> %p",
 982              is_cold() ? "cold" : is_hot() ? "hot " : "warm",
 983              count(), profit(), work(), size(), compute_heat(), next());
 984   tty->cr();
 985   if (call() != NULL)  call()->dump();
 986 }
 987 
 988 void print_wci(WarmCallInfo* ci) {
 989   ci->print();
 990 }
 991 
 992 void WarmCallInfo::print_all() const {
 993   for (const WarmCallInfo* p = this; p != NULL; p = p->next())
 994     p->print();
 995 }
 996 
 997 int WarmCallInfo::count_all() const {
 998   int cnt = 0;
 999   for (const WarmCallInfo* p = this; p != NULL; p = p->next())
1000     cnt++;
1001   return cnt;
1002 }
1003 
1004 #endif //PRODUCT