1 /*
   2  * Copyright (c) 1997, 2021, 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 "compiler/compileLog.hpp"
  27 #include "interpreter/linkResolver.hpp"
  28 #include "memory/resourceArea.hpp"
  29 #include "oops/method.hpp"
  30 #include "opto/addnode.hpp"
  31 #include "opto/c2compiler.hpp"
  32 #include "opto/castnode.hpp"
  33 #include "opto/idealGraphPrinter.hpp"
  34 #include "opto/locknode.hpp"
  35 #include "opto/memnode.hpp"
  36 #include "opto/opaquenode.hpp"
  37 #include "opto/parse.hpp"
  38 #include "opto/rootnode.hpp"
  39 #include "opto/runtime.hpp"
  40 #include "opto/type.hpp"
  41 #include "runtime/handles.inline.hpp"
  42 #include "runtime/safepointMechanism.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 #include "utilities/bitMap.inline.hpp"
  45 #include "utilities/copy.hpp"
  46 
  47 // Static array so we can figure out which bytecodes stop us from compiling
  48 // the most. Some of the non-static variables are needed in bytecodeInfo.cpp
  49 // and eventually should be encapsulated in a proper class (gri 8/18/98).
  50 
  51 #ifndef PRODUCT
  52 int nodes_created              = 0;
  53 int methods_parsed             = 0;
  54 int methods_seen               = 0;
  55 int blocks_parsed              = 0;
  56 int blocks_seen                = 0;
  57 
  58 int explicit_null_checks_inserted = 0;
  59 int explicit_null_checks_elided   = 0;
  60 int all_null_checks_found         = 0;
  61 int implicit_null_checks          = 0;
  62 
  63 bool Parse::BytecodeParseHistogram::_initialized = false;
  64 uint Parse::BytecodeParseHistogram::_bytecodes_parsed [Bytecodes::number_of_codes];
  65 uint Parse::BytecodeParseHistogram::_nodes_constructed[Bytecodes::number_of_codes];
  66 uint Parse::BytecodeParseHistogram::_nodes_transformed[Bytecodes::number_of_codes];
  67 uint Parse::BytecodeParseHistogram::_new_values       [Bytecodes::number_of_codes];
  68 
  69 //------------------------------print_statistics-------------------------------
  70 void Parse::print_statistics() {
  71   tty->print_cr("--- Compiler Statistics ---");
  72   tty->print("Methods seen: %d  Methods parsed: %d", methods_seen, methods_parsed);
  73   tty->print("  Nodes created: %d", nodes_created);
  74   tty->cr();
  75   if (methods_seen != methods_parsed) {
  76     tty->print_cr("Reasons for parse failures (NOT cumulative):");
  77   }
  78   tty->print_cr("Blocks parsed: %d  Blocks seen: %d", blocks_parsed, blocks_seen);
  79 
  80   if (explicit_null_checks_inserted) {
  81     tty->print_cr("%d original NULL checks - %d elided (%2d%%); optimizer leaves %d,",
  82                   explicit_null_checks_inserted, explicit_null_checks_elided,
  83                   (100*explicit_null_checks_elided)/explicit_null_checks_inserted,
  84                   all_null_checks_found);
  85   }
  86   if (all_null_checks_found) {
  87     tty->print_cr("%d made implicit (%2d%%)", implicit_null_checks,
  88                   (100*implicit_null_checks)/all_null_checks_found);
  89   }
  90   if (SharedRuntime::_implicit_null_throws) {
  91     tty->print_cr("%d implicit null exceptions at runtime",
  92                   SharedRuntime::_implicit_null_throws);
  93   }
  94 
  95   if (PrintParseStatistics && BytecodeParseHistogram::initialized()) {
  96     BytecodeParseHistogram::print();
  97   }
  98 }
  99 #endif
 100 
 101 //------------------------------ON STACK REPLACEMENT---------------------------
 102 
 103 // Construct a node which can be used to get incoming state for
 104 // on stack replacement.
 105 Node *Parse::fetch_interpreter_state(int index,
 106                                      BasicType bt,
 107                                      Node *local_addrs,
 108                                      Node *local_addrs_base) {
 109   Node *mem = memory(Compile::AliasIdxRaw);
 110   Node *adr = basic_plus_adr( local_addrs_base, local_addrs, -index*wordSize );
 111   Node *ctl = control();
 112 
 113   // Very similar to LoadNode::make, except we handle un-aligned longs and
 114   // doubles on Sparc.  Intel can handle them just fine directly.
 115   Node *l = NULL;
 116   switch (bt) {                // Signature is flattened
 117   case T_INT:     l = new LoadINode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeInt::INT,        MemNode::unordered); break;
 118   case T_FLOAT:   l = new LoadFNode(ctl, mem, adr, TypeRawPtr::BOTTOM, Type::FLOAT,         MemNode::unordered); break;
 119   case T_ADDRESS: l = new LoadPNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM,  MemNode::unordered); break;
 120   case T_OBJECT:  l = new LoadPNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeInstPtr::BOTTOM, MemNode::unordered); break;
 121   case T_LONG:
 122   case T_DOUBLE: {
 123     // Since arguments are in reverse order, the argument address 'adr'
 124     // refers to the back half of the long/double.  Recompute adr.
 125     adr = basic_plus_adr(local_addrs_base, local_addrs, -(index+1)*wordSize);
 126     if (Matcher::misaligned_doubles_ok) {
 127       l = (bt == T_DOUBLE)
 128         ? (Node*)new LoadDNode(ctl, mem, adr, TypeRawPtr::BOTTOM, Type::DOUBLE, MemNode::unordered)
 129         : (Node*)new LoadLNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeLong::LONG, MemNode::unordered);
 130     } else {
 131       l = (bt == T_DOUBLE)
 132         ? (Node*)new LoadD_unalignedNode(ctl, mem, adr, TypeRawPtr::BOTTOM, MemNode::unordered)
 133         : (Node*)new LoadL_unalignedNode(ctl, mem, adr, TypeRawPtr::BOTTOM, MemNode::unordered);
 134     }
 135     break;
 136   }
 137   default: ShouldNotReachHere();
 138   }
 139   return _gvn.transform(l);
 140 }
 141 
 142 // Helper routine to prevent the interpreter from handing
 143 // unexpected typestate to an OSR method.
 144 // The Node l is a value newly dug out of the interpreter frame.
 145 // The type is the type predicted by ciTypeFlow.  Note that it is
 146 // not a general type, but can only come from Type::get_typeflow_type.
 147 // The safepoint is a map which will feed an uncommon trap.
 148 Node* Parse::check_interpreter_type(Node* l, const Type* type,
 149                                     SafePointNode* &bad_type_exit) {
 150 
 151   const TypeOopPtr* tp = type->isa_oopptr();
 152 
 153   // TypeFlow may assert null-ness if a type appears unloaded.
 154   if (type == TypePtr::NULL_PTR ||
 155       (tp != NULL && !tp->klass()->is_loaded())) {
 156     // Value must be null, not a real oop.
 157     Node* chk = _gvn.transform( new CmpPNode(l, null()) );
 158     Node* tst = _gvn.transform( new BoolNode(chk, BoolTest::eq) );
 159     IfNode* iff = create_and_map_if(control(), tst, PROB_MAX, COUNT_UNKNOWN);
 160     set_control(_gvn.transform( new IfTrueNode(iff) ));
 161     Node* bad_type = _gvn.transform( new IfFalseNode(iff) );
 162     bad_type_exit->control()->add_req(bad_type);
 163     l = null();
 164   }
 165 
 166   // Typeflow can also cut off paths from the CFG, based on
 167   // types which appear unloaded, or call sites which appear unlinked.
 168   // When paths are cut off, values at later merge points can rise
 169   // toward more specific classes.  Make sure these specific classes
 170   // are still in effect.
 171   if (tp != NULL && tp->klass() != C->env()->Object_klass()) {
 172     // TypeFlow asserted a specific object type.  Value must have that type.
 173     Node* bad_type_ctrl = NULL;
 174     l = gen_checkcast(l, makecon(TypeKlassPtr::make(tp->klass())), &bad_type_ctrl);
 175     bad_type_exit->control()->add_req(bad_type_ctrl);
 176   }
 177 
 178   BasicType bt_l = _gvn.type(l)->basic_type();
 179   BasicType bt_t = type->basic_type();
 180   assert(_gvn.type(l)->higher_equal(type), "must constrain OSR typestate");
 181   return l;
 182 }
 183 
 184 // Helper routine which sets up elements of the initial parser map when
 185 // performing a parse for on stack replacement.  Add values into map.
 186 // The only parameter contains the address of a interpreter arguments.
 187 void Parse::load_interpreter_state(Node* osr_buf) {
 188   int index;
 189   int max_locals = jvms()->loc_size();
 190   int max_stack  = jvms()->stk_size();
 191 
 192 
 193   // Mismatch between method and jvms can occur since map briefly held
 194   // an OSR entry state (which takes up one RawPtr word).
 195   assert(max_locals == method()->max_locals(), "sanity");
 196   assert(max_stack  >= method()->max_stack(),  "sanity");
 197   assert((int)jvms()->endoff() == TypeFunc::Parms + max_locals + max_stack, "sanity");
 198   assert((int)jvms()->endoff() == (int)map()->req(), "sanity");
 199 
 200   // Find the start block.
 201   Block* osr_block = start_block();
 202   assert(osr_block->start() == osr_bci(), "sanity");
 203 
 204   // Set initial BCI.
 205   set_parse_bci(osr_block->start());
 206 
 207   // Set initial stack depth.
 208   set_sp(osr_block->start_sp());
 209 
 210   // Check bailouts.  We currently do not perform on stack replacement
 211   // of loops in catch blocks or loops which branch with a non-empty stack.
 212   if (sp() != 0) {
 213     C->record_method_not_compilable("OSR starts with non-empty stack");
 214     return;
 215   }
 216   // Do not OSR inside finally clauses:
 217   if (osr_block->has_trap_at(osr_block->start())) {
 218     C->record_method_not_compilable("OSR starts with an immediate trap");
 219     return;
 220   }
 221 
 222   // Commute monitors from interpreter frame to compiler frame.
 223   assert(jvms()->monitor_depth() == 0, "should be no active locks at beginning of osr");
 224   int mcnt = osr_block->flow()->monitor_count();
 225   Node *monitors_addr = basic_plus_adr(osr_buf, osr_buf, (max_locals+mcnt*2-1)*wordSize);
 226   for (index = 0; index < mcnt; index++) {
 227     // Make a BoxLockNode for the monitor.
 228     Node *box = _gvn.transform(new BoxLockNode(next_monitor()));
 229 
 230 
 231     // Displaced headers and locked objects are interleaved in the
 232     // temp OSR buffer.  We only copy the locked objects out here.
 233     // Fetch the locked object from the OSR temp buffer and copy to our fastlock node.
 234     Node *lock_object = fetch_interpreter_state(index*2, T_OBJECT, monitors_addr, osr_buf);
 235     // Try and copy the displaced header to the BoxNode
 236     Node *displaced_hdr = fetch_interpreter_state((index*2) + 1, T_ADDRESS, monitors_addr, osr_buf);
 237 
 238 
 239     store_to_memory(control(), box, displaced_hdr, T_ADDRESS, Compile::AliasIdxRaw, MemNode::unordered);
 240 
 241     // Build a bogus FastLockNode (no code will be generated) and push the
 242     // monitor into our debug info.
 243     const FastLockNode *flock = _gvn.transform(new FastLockNode( 0, lock_object, box ))->as_FastLock();
 244     map()->push_monitor(flock);
 245 
 246     // If the lock is our method synchronization lock, tuck it away in
 247     // _sync_lock for return and rethrow exit paths.
 248     if (index == 0 && method()->is_synchronized()) {
 249       _synch_lock = flock;
 250     }
 251   }
 252 
 253   // Use the raw liveness computation to make sure that unexpected
 254   // values don't propagate into the OSR frame.
 255   MethodLivenessResult live_locals = method()->liveness_at_bci(osr_bci());
 256   if (!live_locals.is_valid()) {
 257     // Degenerate or breakpointed method.
 258     C->record_method_not_compilable("OSR in empty or breakpointed method");
 259     return;
 260   }
 261 
 262   // Extract the needed locals from the interpreter frame.
 263   Node *locals_addr = basic_plus_adr(osr_buf, osr_buf, (max_locals-1)*wordSize);
 264 
 265   // find all the locals that the interpreter thinks contain live oops
 266   const ResourceBitMap live_oops = method()->live_local_oops_at_bci(osr_bci());
 267   for (index = 0; index < max_locals; index++) {
 268 
 269     if (!live_locals.at(index)) {
 270       continue;
 271     }
 272 
 273     const Type *type = osr_block->local_type_at(index);
 274 
 275     if (type->isa_oopptr() != NULL) {
 276 
 277       // 6403625: Verify that the interpreter oopMap thinks that the oop is live
 278       // else we might load a stale oop if the MethodLiveness disagrees with the
 279       // result of the interpreter. If the interpreter says it is dead we agree
 280       // by making the value go to top.
 281       //
 282 
 283       if (!live_oops.at(index)) {
 284         if (C->log() != NULL) {
 285           C->log()->elem("OSR_mismatch local_index='%d'",index);
 286         }
 287         set_local(index, null());
 288         // and ignore it for the loads
 289         continue;
 290       }
 291     }
 292 
 293     // Filter out TOP, HALF, and BOTTOM.  (Cf. ensure_phi.)
 294     if (type == Type::TOP || type == Type::HALF) {
 295       continue;
 296     }
 297     // If the type falls to bottom, then this must be a local that
 298     // is mixing ints and oops or some such.  Forcing it to top
 299     // makes it go dead.
 300     if (type == Type::BOTTOM) {
 301       continue;
 302     }
 303     // Construct code to access the appropriate local.
 304     BasicType bt = type->basic_type();
 305     if (type == TypePtr::NULL_PTR) {
 306       // Ptr types are mixed together with T_ADDRESS but NULL is
 307       // really for T_OBJECT types so correct it.
 308       bt = T_OBJECT;
 309     }
 310     Node *value = fetch_interpreter_state(index, bt, locals_addr, osr_buf);
 311     set_local(index, value);
 312   }
 313 
 314   // Extract the needed stack entries from the interpreter frame.
 315   for (index = 0; index < sp(); index++) {
 316     const Type *type = osr_block->stack_type_at(index);
 317     if (type != Type::TOP) {
 318       // Currently the compiler bails out when attempting to on stack replace
 319       // at a bci with a non-empty stack.  We should not reach here.
 320       ShouldNotReachHere();
 321     }
 322   }
 323 
 324   // End the OSR migration
 325   make_runtime_call(RC_LEAF, OptoRuntime::osr_end_Type(),
 326                     CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_end),
 327                     "OSR_migration_end", TypeRawPtr::BOTTOM,
 328                     osr_buf);
 329 
 330   // Now that the interpreter state is loaded, make sure it will match
 331   // at execution time what the compiler is expecting now:
 332   SafePointNode* bad_type_exit = clone_map();
 333   bad_type_exit->set_control(new RegionNode(1));
 334 
 335   assert(osr_block->flow()->jsrs()->size() == 0, "should be no jsrs live at osr point");
 336   for (index = 0; index < max_locals; index++) {
 337     if (stopped())  break;
 338     Node* l = local(index);
 339     if (l->is_top())  continue;  // nothing here
 340     const Type *type = osr_block->local_type_at(index);
 341     if (type->isa_oopptr() != NULL) {
 342       if (!live_oops.at(index)) {
 343         // skip type check for dead oops
 344         continue;
 345       }
 346     }
 347     if (osr_block->flow()->local_type_at(index)->is_return_address()) {
 348       // In our current system it's illegal for jsr addresses to be
 349       // live into an OSR entry point because the compiler performs
 350       // inlining of jsrs.  ciTypeFlow has a bailout that detect this
 351       // case and aborts the compile if addresses are live into an OSR
 352       // entry point.  Because of that we can assume that any address
 353       // locals at the OSR entry point are dead.  Method liveness
 354       // isn't precise enought to figure out that they are dead in all
 355       // cases so simply skip checking address locals all
 356       // together. Any type check is guaranteed to fail since the
 357       // interpreter type is the result of a load which might have any
 358       // value and the expected type is a constant.
 359       continue;
 360     }
 361     set_local(index, check_interpreter_type(l, type, bad_type_exit));
 362   }
 363 
 364   for (index = 0; index < sp(); index++) {
 365     if (stopped())  break;
 366     Node* l = stack(index);
 367     if (l->is_top())  continue;  // nothing here
 368     const Type *type = osr_block->stack_type_at(index);
 369     set_stack(index, check_interpreter_type(l, type, bad_type_exit));
 370   }
 371 
 372   if (bad_type_exit->control()->req() > 1) {
 373     // Build an uncommon trap here, if any inputs can be unexpected.
 374     bad_type_exit->set_control(_gvn.transform( bad_type_exit->control() ));
 375     record_for_igvn(bad_type_exit->control());
 376     SafePointNode* types_are_good = map();
 377     set_map(bad_type_exit);
 378     // The unexpected type happens because a new edge is active
 379     // in the CFG, which typeflow had previously ignored.
 380     // E.g., Object x = coldAtFirst() && notReached()? "str": new Integer(123).
 381     // This x will be typed as Integer if notReached is not yet linked.
 382     // It could also happen due to a problem in ciTypeFlow analysis.
 383     uncommon_trap(Deoptimization::Reason_constraint,
 384                   Deoptimization::Action_reinterpret);
 385     set_map(types_are_good);
 386   }
 387 }
 388 
 389 //------------------------------Parse------------------------------------------
 390 // Main parser constructor.
 391 Parse::Parse(JVMState* caller, ciMethod* parse_method, float expected_uses)
 392   : _exits(caller)
 393 {
 394   // Init some variables
 395   _caller = caller;
 396   _method = parse_method;
 397   _expected_uses = expected_uses;
 398   _depth = 1 + (caller->has_method() ? caller->depth() : 0);
 399   _wrote_final = false;
 400   _wrote_volatile = false;
 401   _wrote_stable = false;
 402   _wrote_fields = false;
 403   _alloc_with_final = NULL;
 404   _entry_bci = InvocationEntryBci;
 405   _tf = NULL;
 406   _block = NULL;
 407   _first_return = true;
 408   _replaced_nodes_for_exceptions = false;
 409   _new_idx = C->unique();
 410   debug_only(_block_count = -1);
 411   debug_only(_blocks = (Block*)-1);
 412 #ifndef PRODUCT
 413   if (PrintCompilation || PrintOpto) {
 414     // Make sure I have an inline tree, so I can print messages about it.
 415     JVMState* ilt_caller = is_osr_parse() ? caller->caller() : caller;
 416     InlineTree::find_subtree_from_root(C->ilt(), ilt_caller, parse_method);
 417   }
 418   _max_switch_depth = 0;
 419   _est_switch_depth = 0;
 420 #endif
 421 
 422   if (parse_method->has_reserved_stack_access()) {
 423     C->set_has_reserved_stack_access(true);
 424   }
 425 
 426   if (parse_method->is_synchronized()) {
 427     C->push_monitor();
 428   }
 429 
 430    _tf = TypeFunc::make(method());
 431   _iter.reset_to_method(method());
 432   _flow = method()->get_flow_analysis();
 433   if (_flow->failing()) {
 434     C->record_method_not_compilable(_flow->failure_reason());
 435   }
 436 
 437 #ifndef PRODUCT
 438   if (_flow->has_irreducible_entry()) {
 439     C->set_parsed_irreducible_loop(true);
 440   }
 441 #endif
 442   C->set_has_loops(C->has_loops() || method()->has_loops());
 443 
 444   if (_expected_uses <= 0) {
 445     _prof_factor = 1;
 446   } else {
 447     float prof_total = parse_method->interpreter_invocation_count();
 448     if (prof_total <= _expected_uses) {
 449       _prof_factor = 1;
 450     } else {
 451       _prof_factor = _expected_uses / prof_total;
 452     }
 453   }
 454 
 455   CompileLog* log = C->log();
 456   if (log != NULL) {
 457     log->begin_head("parse method='%d' uses='%f'",
 458                     log->identify(parse_method), expected_uses);
 459     if (depth() == 1 && C->is_osr_compilation()) {
 460       log->print(" osr_bci='%d'", C->entry_bci());
 461     }
 462     log->stamp();
 463     log->end_head();
 464   }
 465 
 466   // Accumulate deoptimization counts.
 467   // (The range_check and store_check counts are checked elsewhere.)
 468   ciMethodData* md = method()->method_data();
 469   for (uint reason = 0; reason < md->trap_reason_limit(); reason++) {
 470     uint md_count = md->trap_count(reason);
 471     if (md_count != 0) {
 472       if (md_count == md->trap_count_limit())
 473         md_count += md->overflow_trap_count();
 474       uint total_count = C->trap_count(reason);
 475       uint old_count   = total_count;
 476       total_count += md_count;
 477       // Saturate the add if it overflows.
 478       if (total_count < old_count || total_count < md_count)
 479         total_count = (uint)-1;
 480       C->set_trap_count(reason, total_count);
 481       if (log != NULL)
 482         log->elem("observe trap='%s' count='%d' total='%d'",
 483                   Deoptimization::trap_reason_name(reason),
 484                   md_count, total_count);
 485     }
 486   }
 487   // Accumulate total sum of decompilations, also.
 488   C->set_decompile_count(C->decompile_count() + md->decompile_count());
 489 
 490   if (log != NULL && method()->has_exception_handlers()) {
 491     log->elem("observe that='has_exception_handlers'");
 492   }
 493 
 494   assert(InlineTree::check_can_parse(method()) == NULL, "Can not parse this method, cutout earlier");
 495   assert(method()->has_balanced_monitors(), "Can not parse unbalanced monitors, cutout earlier");
 496 
 497   // Always register dependence if JVMTI is enabled, because
 498   // either breakpoint setting or hotswapping of methods may
 499   // cause deoptimization.
 500   if (C->env()->jvmti_can_hotswap_or_post_breakpoint()) {
 501     C->dependencies()->assert_evol_method(method());
 502   }
 503 
 504   NOT_PRODUCT(methods_seen++);
 505 
 506   // Do some special top-level things.
 507   if (depth() == 1 && C->is_osr_compilation()) {
 508     _entry_bci = C->entry_bci();
 509     _flow = method()->get_osr_flow_analysis(osr_bci());
 510     if (_flow->failing()) {
 511       C->record_method_not_compilable(_flow->failure_reason());
 512 #ifndef PRODUCT
 513       if (PrintOpto && (Verbose || WizardMode)) {
 514         tty->print_cr("OSR @%d type flow bailout: %s", _entry_bci, _flow->failure_reason());
 515         if (Verbose) {
 516           method()->print();
 517           method()->print_codes();
 518           _flow->print();
 519         }
 520       }
 521 #endif
 522     }
 523     _tf = C->tf();     // the OSR entry type is different
 524   }
 525 
 526 #ifdef ASSERT
 527   if (depth() == 1) {
 528     assert(C->is_osr_compilation() == this->is_osr_parse(), "OSR in sync");
 529   } else {
 530     assert(!this->is_osr_parse(), "no recursive OSR");
 531   }
 532 #endif
 533 
 534 #ifndef PRODUCT
 535   methods_parsed++;
 536   // add method size here to guarantee that inlined methods are added too
 537   if (CITime)
 538     _total_bytes_compiled += method()->code_size();
 539 
 540   show_parse_info();
 541 #endif
 542 
 543   if (failing()) {
 544     if (log)  log->done("parse");
 545     return;
 546   }
 547 
 548   gvn().set_type(root(), root()->bottom_type());
 549   gvn().transform(top());
 550 
 551   // Import the results of the ciTypeFlow.
 552   init_blocks();
 553 
 554   // Merge point for all normal exits
 555   build_exits();
 556 
 557   // Setup the initial JVM state map.
 558   SafePointNode* entry_map = create_entry_map();
 559 
 560   // Check for bailouts during map initialization
 561   if (failing() || entry_map == NULL) {
 562     if (log)  log->done("parse");
 563     return;
 564   }
 565 
 566   Node_Notes* caller_nn = C->default_node_notes();
 567   // Collect debug info for inlined calls unless -XX:-DebugInlinedCalls.
 568   if (DebugInlinedCalls || depth() == 1) {
 569     C->set_default_node_notes(make_node_notes(caller_nn));
 570   }
 571 
 572   if (is_osr_parse()) {
 573     Node* osr_buf = entry_map->in(TypeFunc::Parms+0);
 574     entry_map->set_req(TypeFunc::Parms+0, top());
 575     set_map(entry_map);
 576     load_interpreter_state(osr_buf);
 577   } else {
 578     set_map(entry_map);
 579     do_method_entry();
 580     if (depth() == 1 && C->age_code()) {
 581       decrement_age();
 582     }
 583   }
 584 
 585   if (depth() == 1 && !failing()) {
 586     if (C->clinit_barrier_on_entry()) {
 587       // Add check to deoptimize the nmethod once the holder class is fully initialized
 588       clinit_deopt();
 589     }
 590 
 591     // Add check to deoptimize the nmethod if RTM state was changed
 592     rtm_deopt();
 593   }
 594 
 595   // Check for bailouts during method entry or RTM state check setup.
 596   if (failing()) {
 597     if (log)  log->done("parse");
 598     C->set_default_node_notes(caller_nn);
 599     return;
 600   }
 601 
 602   entry_map = map();  // capture any changes performed by method setup code
 603   assert(jvms()->endoff() == map()->req(), "map matches JVMS layout");
 604 
 605   // We begin parsing as if we have just encountered a jump to the
 606   // method entry.
 607   Block* entry_block = start_block();
 608   assert(entry_block->start() == (is_osr_parse() ? osr_bci() : 0), "");
 609   set_map_clone(entry_map);
 610   merge_common(entry_block, entry_block->next_path_num());
 611 
 612 #ifndef PRODUCT
 613   BytecodeParseHistogram *parse_histogram_obj = new (C->env()->arena()) BytecodeParseHistogram(this, C);
 614   set_parse_histogram( parse_histogram_obj );
 615 #endif
 616 
 617   // Parse all the basic blocks.
 618   do_all_blocks();
 619 
 620   C->set_default_node_notes(caller_nn);
 621 
 622   // Check for bailouts during conversion to graph
 623   if (failing()) {
 624     if (log)  log->done("parse");
 625     return;
 626   }
 627 
 628   // Fix up all exiting control flow.
 629   set_map(entry_map);
 630   do_exits();
 631 
 632   if (log)  log->done("parse nodes='%d' live='%d' memory='" SIZE_FORMAT "'",
 633                       C->unique(), C->live_nodes(), C->node_arena()->used());
 634 }
 635 
 636 //---------------------------do_all_blocks-------------------------------------
 637 void Parse::do_all_blocks() {
 638   bool has_irreducible = flow()->has_irreducible_entry();
 639 
 640   // Walk over all blocks in Reverse Post-Order.
 641   while (true) {
 642     bool progress = false;
 643     for (int rpo = 0; rpo < block_count(); rpo++) {
 644       Block* block = rpo_at(rpo);
 645 
 646       if (block->is_parsed()) continue;
 647 
 648       if (!block->is_merged()) {
 649         // Dead block, no state reaches this block
 650         continue;
 651       }
 652 
 653       // Prepare to parse this block.
 654       load_state_from(block);
 655 
 656       if (stopped()) {
 657         // Block is dead.
 658         continue;
 659       }
 660 
 661       NOT_PRODUCT(blocks_parsed++);
 662 
 663       progress = true;
 664       if (block->is_loop_head() || block->is_handler() || (has_irreducible && !block->is_ready())) {
 665         // Not all preds have been parsed.  We must build phis everywhere.
 666         // (Note that dead locals do not get phis built, ever.)
 667         ensure_phis_everywhere();
 668 
 669         if (block->is_SEL_head()) {
 670           // Add predicate to single entry (not irreducible) loop head.
 671           assert(!block->has_merged_backedge(), "only entry paths should be merged for now");
 672           // Predicates may have been added after a dominating if
 673           if (!block->has_predicates()) {
 674             // Need correct bci for predicate.
 675             // It is fine to set it here since do_one_block() will set it anyway.
 676             set_parse_bci(block->start());
 677             add_empty_predicates();
 678           }
 679           // Add new region for back branches.
 680           int edges = block->pred_count() - block->preds_parsed() + 1; // +1 for original region
 681           RegionNode *r = new RegionNode(edges+1);
 682           _gvn.set_type(r, Type::CONTROL);
 683           record_for_igvn(r);
 684           r->init_req(edges, control());
 685           set_control(r);
 686           // Add new phis.
 687           ensure_phis_everywhere();
 688         }
 689 
 690         // Leave behind an undisturbed copy of the map, for future merges.
 691         set_map(clone_map());
 692       }
 693 
 694       if (control()->is_Region() && !block->is_loop_head() && !has_irreducible && !block->is_handler()) {
 695         // In the absence of irreducible loops, the Region and Phis
 696         // associated with a merge that doesn't involve a backedge can
 697         // be simplified now since the RPO parsing order guarantees
 698         // that any path which was supposed to reach here has already
 699         // been parsed or must be dead.
 700         Node* c = control();
 701         Node* result = _gvn.transform_no_reclaim(control());
 702         if (c != result && TraceOptoParse) {
 703           tty->print_cr("Block #%d replace %d with %d", block->rpo(), c->_idx, result->_idx);
 704         }
 705         if (result != top()) {
 706           record_for_igvn(result);
 707         }
 708       }
 709 
 710       // Parse the block.
 711       do_one_block();
 712 
 713       // Check for bailouts.
 714       if (failing())  return;
 715     }
 716 
 717     // with irreducible loops multiple passes might be necessary to parse everything
 718     if (!has_irreducible || !progress) {
 719       break;
 720     }
 721   }
 722 
 723 #ifndef PRODUCT
 724   blocks_seen += block_count();
 725 
 726   // Make sure there are no half-processed blocks remaining.
 727   // Every remaining unprocessed block is dead and may be ignored now.
 728   for (int rpo = 0; rpo < block_count(); rpo++) {
 729     Block* block = rpo_at(rpo);
 730     if (!block->is_parsed()) {
 731       if (TraceOptoParse) {
 732         tty->print_cr("Skipped dead block %d at bci:%d", rpo, block->start());
 733       }
 734       assert(!block->is_merged(), "no half-processed blocks");
 735     }
 736   }
 737 #endif
 738 }
 739 
 740 static Node* mask_int_value(Node* v, BasicType bt, PhaseGVN* gvn) {
 741   switch (bt) {
 742   case T_BYTE:
 743     v = gvn->transform(new LShiftINode(v, gvn->intcon(24)));
 744     v = gvn->transform(new RShiftINode(v, gvn->intcon(24)));
 745     break;
 746   case T_SHORT:
 747     v = gvn->transform(new LShiftINode(v, gvn->intcon(16)));
 748     v = gvn->transform(new RShiftINode(v, gvn->intcon(16)));
 749     break;
 750   case T_CHAR:
 751     v = gvn->transform(new AndINode(v, gvn->intcon(0xFFFF)));
 752     break;
 753   case T_BOOLEAN:
 754     v = gvn->transform(new AndINode(v, gvn->intcon(0x1)));
 755     break;
 756   default:
 757     break;
 758   }
 759   return v;
 760 }
 761 
 762 //-------------------------------build_exits----------------------------------
 763 // Build normal and exceptional exit merge points.
 764 void Parse::build_exits() {
 765   // make a clone of caller to prevent sharing of side-effects
 766   _exits.set_map(_exits.clone_map());
 767   _exits.clean_stack(_exits.sp());
 768   _exits.sync_jvms();
 769 
 770   RegionNode* region = new RegionNode(1);
 771   record_for_igvn(region);
 772   gvn().set_type_bottom(region);
 773   _exits.set_control(region);
 774 
 775   // Note:  iophi and memphi are not transformed until do_exits.
 776   Node* iophi  = new PhiNode(region, Type::ABIO);
 777   Node* memphi = new PhiNode(region, Type::MEMORY, TypePtr::BOTTOM);
 778   gvn().set_type_bottom(iophi);
 779   gvn().set_type_bottom(memphi);
 780   _exits.set_i_o(iophi);
 781   _exits.set_all_memory(memphi);
 782 
 783   // Add a return value to the exit state.  (Do not push it yet.)
 784   if (tf()->range()->cnt() > TypeFunc::Parms) {
 785     const Type* ret_type = tf()->range()->field_at(TypeFunc::Parms);
 786     if (ret_type->isa_int()) {
 787       BasicType ret_bt = method()->return_type()->basic_type();
 788       if (ret_bt == T_BOOLEAN ||
 789           ret_bt == T_CHAR ||
 790           ret_bt == T_BYTE ||
 791           ret_bt == T_SHORT) {
 792         ret_type = TypeInt::INT;
 793       }
 794     }
 795 
 796     // Don't "bind" an unloaded return klass to the ret_phi. If the klass
 797     // becomes loaded during the subsequent parsing, the loaded and unloaded
 798     // types will not join when we transform and push in do_exits().
 799     const TypeOopPtr* ret_oop_type = ret_type->isa_oopptr();
 800     if (ret_oop_type && !ret_oop_type->klass()->is_loaded()) {
 801       ret_type = TypeOopPtr::BOTTOM;
 802     }
 803     int         ret_size = type2size[ret_type->basic_type()];
 804     Node*       ret_phi  = new PhiNode(region, ret_type);
 805     gvn().set_type_bottom(ret_phi);
 806     _exits.ensure_stack(ret_size);
 807     assert((int)(tf()->range()->cnt() - TypeFunc::Parms) == ret_size, "good tf range");
 808     assert(method()->return_type()->size() == ret_size, "tf agrees w/ method");
 809     _exits.set_argument(0, ret_phi);  // here is where the parser finds it
 810     // Note:  ret_phi is not yet pushed, until do_exits.
 811   }
 812 }
 813 
 814 
 815 //----------------------------build_start_state-------------------------------
 816 // Construct a state which contains only the incoming arguments from an
 817 // unknown caller.  The method & bci will be NULL & InvocationEntryBci.
 818 JVMState* Compile::build_start_state(StartNode* start, const TypeFunc* tf) {
 819   int        arg_size = tf->domain()->cnt();
 820   int        max_size = MAX2(arg_size, (int)tf->range()->cnt());
 821   JVMState*  jvms     = new (this) JVMState(max_size - TypeFunc::Parms);
 822   SafePointNode* map  = new SafePointNode(max_size, jvms);
 823   record_for_igvn(map);
 824   assert(arg_size == TypeFunc::Parms + (is_osr_compilation() ? 1 : method()->arg_size()), "correct arg_size");
 825   Node_Notes* old_nn = default_node_notes();
 826   if (old_nn != NULL && has_method()) {
 827     Node_Notes* entry_nn = old_nn->clone(this);
 828     JVMState* entry_jvms = new(this) JVMState(method(), old_nn->jvms());
 829     entry_jvms->set_offsets(0);
 830     entry_jvms->set_bci(entry_bci());
 831     entry_nn->set_jvms(entry_jvms);
 832     set_default_node_notes(entry_nn);
 833   }
 834   uint i;
 835   for (i = 0; i < (uint)arg_size; i++) {
 836     Node* parm = initial_gvn()->transform(new ParmNode(start, i));
 837     map->init_req(i, parm);
 838     // Record all these guys for later GVN.
 839     record_for_igvn(parm);
 840   }
 841   for (; i < map->req(); i++) {
 842     map->init_req(i, top());
 843   }
 844   assert(jvms->argoff() == TypeFunc::Parms, "parser gets arguments here");
 845   set_default_node_notes(old_nn);
 846   jvms->set_map(map);
 847   return jvms;
 848 }
 849 
 850 //-----------------------------make_node_notes---------------------------------
 851 Node_Notes* Parse::make_node_notes(Node_Notes* caller_nn) {
 852   if (caller_nn == NULL)  return NULL;
 853   Node_Notes* nn = caller_nn->clone(C);
 854   JVMState* caller_jvms = nn->jvms();
 855   JVMState* jvms = new (C) JVMState(method(), caller_jvms);
 856   jvms->set_offsets(0);
 857   jvms->set_bci(_entry_bci);
 858   nn->set_jvms(jvms);
 859   return nn;
 860 }
 861 
 862 
 863 //--------------------------return_values--------------------------------------
 864 void Compile::return_values(JVMState* jvms) {
 865   GraphKit kit(jvms);
 866   Node* ret = new ReturnNode(TypeFunc::Parms,
 867                              kit.control(),
 868                              kit.i_o(),
 869                              kit.reset_memory(),
 870                              kit.frameptr(),
 871                              kit.returnadr());
 872   // Add zero or 1 return values
 873   int ret_size = tf()->range()->cnt() - TypeFunc::Parms;
 874   if (ret_size > 0) {
 875     kit.inc_sp(-ret_size);  // pop the return value(s)
 876     kit.sync_jvms();
 877     ret->add_req(kit.argument(0));
 878     // Note:  The second dummy edge is not needed by a ReturnNode.
 879   }
 880   // bind it to root
 881   root()->add_req(ret);
 882   record_for_igvn(ret);
 883   initial_gvn()->transform_no_reclaim(ret);
 884 }
 885 
 886 //------------------------rethrow_exceptions-----------------------------------
 887 // Bind all exception states in the list into a single RethrowNode.
 888 void Compile::rethrow_exceptions(JVMState* jvms) {
 889   GraphKit kit(jvms);
 890   if (!kit.has_exceptions())  return;  // nothing to generate
 891   // Load my combined exception state into the kit, with all phis transformed:
 892   SafePointNode* ex_map = kit.combine_and_pop_all_exception_states();
 893   Node* ex_oop = kit.use_exception_state(ex_map);
 894   RethrowNode* exit = new RethrowNode(kit.control(),
 895                                       kit.i_o(), kit.reset_memory(),
 896                                       kit.frameptr(), kit.returnadr(),
 897                                       // like a return but with exception input
 898                                       ex_oop);
 899   // bind to root
 900   root()->add_req(exit);
 901   record_for_igvn(exit);
 902   initial_gvn()->transform_no_reclaim(exit);
 903 }
 904 
 905 //---------------------------do_exceptions-------------------------------------
 906 // Process exceptions arising from the current bytecode.
 907 // Send caught exceptions to the proper handler within this method.
 908 // Unhandled exceptions feed into _exit.
 909 void Parse::do_exceptions() {
 910   if (!has_exceptions())  return;
 911 
 912   if (failing()) {
 913     // Pop them all off and throw them away.
 914     while (pop_exception_state() != NULL) ;
 915     return;
 916   }
 917 
 918   PreserveJVMState pjvms(this, false);
 919 
 920   SafePointNode* ex_map;
 921   while ((ex_map = pop_exception_state()) != NULL) {
 922     if (!method()->has_exception_handlers()) {
 923       // Common case:  Transfer control outward.
 924       // Doing it this early allows the exceptions to common up
 925       // even between adjacent method calls.
 926       throw_to_exit(ex_map);
 927     } else {
 928       // Have to look at the exception first.
 929       assert(stopped(), "catch_inline_exceptions trashes the map");
 930       catch_inline_exceptions(ex_map);
 931       stop_and_kill_map();      // we used up this exception state; kill it
 932     }
 933   }
 934 
 935   // We now return to our regularly scheduled program:
 936 }
 937 
 938 //---------------------------throw_to_exit-------------------------------------
 939 // Merge the given map into an exception exit from this method.
 940 // The exception exit will handle any unlocking of receiver.
 941 // The ex_oop must be saved within the ex_map, unlike merge_exception.
 942 void Parse::throw_to_exit(SafePointNode* ex_map) {
 943   // Pop the JVMS to (a copy of) the caller.
 944   GraphKit caller;
 945   caller.set_map_clone(_caller->map());
 946   caller.set_bci(_caller->bci());
 947   caller.set_sp(_caller->sp());
 948   // Copy out the standard machine state:
 949   for (uint i = 0; i < TypeFunc::Parms; i++) {
 950     caller.map()->set_req(i, ex_map->in(i));
 951   }
 952   if (ex_map->has_replaced_nodes()) {
 953     _replaced_nodes_for_exceptions = true;
 954   }
 955   caller.map()->transfer_replaced_nodes_from(ex_map, _new_idx);
 956   // ...and the exception:
 957   Node*          ex_oop        = saved_ex_oop(ex_map);
 958   SafePointNode* caller_ex_map = caller.make_exception_state(ex_oop);
 959   // Finally, collect the new exception state in my exits:
 960   _exits.add_exception_state(caller_ex_map);
 961 }
 962 
 963 //------------------------------do_exits---------------------------------------
 964 void Parse::do_exits() {
 965   set_parse_bci(InvocationEntryBci);
 966 
 967   // Now peephole on the return bits
 968   Node* region = _exits.control();
 969   _exits.set_control(gvn().transform(region));
 970 
 971   Node* iophi = _exits.i_o();
 972   _exits.set_i_o(gvn().transform(iophi));
 973 
 974   // Figure out if we need to emit the trailing barrier. The barrier is only
 975   // needed in the constructors, and only in three cases:
 976   //
 977   // 1. The constructor wrote a final. The effects of all initializations
 978   //    must be committed to memory before any code after the constructor
 979   //    publishes the reference to the newly constructed object. Rather
 980   //    than wait for the publication, we simply block the writes here.
 981   //    Rather than put a barrier on only those writes which are required
 982   //    to complete, we force all writes to complete.
 983   //
 984   // 2. Experimental VM option is used to force the barrier if any field
 985   //    was written out in the constructor.
 986   //
 987   // 3. On processors which are not CPU_MULTI_COPY_ATOMIC (e.g. PPC64),
 988   //    support_IRIW_for_not_multiple_copy_atomic_cpu selects that
 989   //    MemBarVolatile is used before volatile load instead of after volatile
 990   //    store, so there's no barrier after the store.
 991   //    We want to guarantee the same behavior as on platforms with total store
 992   //    order, although this is not required by the Java memory model.
 993   //    In this case, we want to enforce visibility of volatile field
 994   //    initializations which are performed in constructors.
 995   //    So as with finals, we add a barrier here.
 996   //
 997   // "All bets are off" unless the first publication occurs after a
 998   // normal return from the constructor.  We do not attempt to detect
 999   // such unusual early publications.  But no barrier is needed on
1000   // exceptional returns, since they cannot publish normally.
1001   //
1002   if (method()->is_initializer() &&
1003        (wrote_final() ||
1004          (AlwaysSafeConstructors && wrote_fields()) ||
1005          (support_IRIW_for_not_multiple_copy_atomic_cpu && wrote_volatile()))) {
1006     _exits.insert_mem_bar(Op_MemBarRelease, alloc_with_final());
1007 
1008     // If Memory barrier is created for final fields write
1009     // and allocation node does not escape the initialize method,
1010     // then barrier introduced by allocation node can be removed.
1011     if (DoEscapeAnalysis && alloc_with_final()) {
1012       AllocateNode *alloc = AllocateNode::Ideal_allocation(alloc_with_final(), &_gvn);
1013       alloc->compute_MemBar_redundancy(method());
1014     }
1015     if (PrintOpto && (Verbose || WizardMode)) {
1016       method()->print_name();
1017       tty->print_cr(" writes finals and needs a memory barrier");
1018     }
1019   }
1020 
1021   // Any method can write a @Stable field; insert memory barriers
1022   // after those also. Can't bind predecessor allocation node (if any)
1023   // with barrier because allocation doesn't always dominate
1024   // MemBarRelease.
1025   if (wrote_stable()) {
1026     _exits.insert_mem_bar(Op_MemBarRelease);
1027     if (PrintOpto && (Verbose || WizardMode)) {
1028       method()->print_name();
1029       tty->print_cr(" writes @Stable and needs a memory barrier");
1030     }
1031   }
1032 
1033   for (MergeMemStream mms(_exits.merged_memory()); mms.next_non_empty(); ) {
1034     // transform each slice of the original memphi:
1035     mms.set_memory(_gvn.transform(mms.memory()));
1036   }
1037   // Clean up input MergeMems created by transforming the slices
1038   _gvn.transform(_exits.merged_memory());
1039 
1040   if (tf()->range()->cnt() > TypeFunc::Parms) {
1041     const Type* ret_type = tf()->range()->field_at(TypeFunc::Parms);
1042     Node*       ret_phi  = _gvn.transform( _exits.argument(0) );
1043     if (!_exits.control()->is_top() && _gvn.type(ret_phi)->empty()) {
1044       // If the type we set for the ret_phi in build_exits() is too optimistic and
1045       // the ret_phi is top now, there's an extremely small chance that it may be due to class
1046       // loading.  It could also be due to an error, so mark this method as not compilable because
1047       // otherwise this could lead to an infinite compile loop.
1048       // In any case, this code path is rarely (and never in my testing) reached.
1049       C->record_method_not_compilable("Can't determine return type.");
1050       return;
1051     }
1052     if (ret_type->isa_int()) {
1053       BasicType ret_bt = method()->return_type()->basic_type();
1054       ret_phi = mask_int_value(ret_phi, ret_bt, &_gvn);
1055     }
1056     _exits.push_node(ret_type->basic_type(), ret_phi);
1057   }
1058 
1059   // Note:  Logic for creating and optimizing the ReturnNode is in Compile.
1060 
1061   // Unlock along the exceptional paths.
1062   // This is done late so that we can common up equivalent exceptions
1063   // (e.g., null checks) arising from multiple points within this method.
1064   // See GraphKit::add_exception_state, which performs the commoning.
1065   bool do_synch = method()->is_synchronized() && GenerateSynchronizationCode;
1066 
1067   // record exit from a method if compiled while Dtrace is turned on.
1068   if (do_synch || C->env()->dtrace_method_probes() || _replaced_nodes_for_exceptions) {
1069     // First move the exception list out of _exits:
1070     GraphKit kit(_exits.transfer_exceptions_into_jvms());
1071     SafePointNode* normal_map = kit.map();  // keep this guy safe
1072     // Now re-collect the exceptions into _exits:
1073     SafePointNode* ex_map;
1074     while ((ex_map = kit.pop_exception_state()) != NULL) {
1075       Node* ex_oop = kit.use_exception_state(ex_map);
1076       // Force the exiting JVM state to have this method at InvocationEntryBci.
1077       // The exiting JVM state is otherwise a copy of the calling JVMS.
1078       JVMState* caller = kit.jvms();
1079       JVMState* ex_jvms = caller->clone_shallow(C);
1080       ex_jvms->bind_map(kit.clone_map());
1081       ex_jvms->set_bci(   InvocationEntryBci);
1082       kit.set_jvms(ex_jvms);
1083       if (do_synch) {
1084         // Add on the synchronized-method box/object combo
1085         kit.map()->push_monitor(_synch_lock);
1086         // Unlock!
1087         kit.shared_unlock(_synch_lock->box_node(), _synch_lock->obj_node());
1088       }
1089       if (C->env()->dtrace_method_probes()) {
1090         kit.make_dtrace_method_exit(method());
1091       }
1092       if (_replaced_nodes_for_exceptions) {
1093         kit.map()->apply_replaced_nodes(_new_idx);
1094       }
1095       // Done with exception-path processing.
1096       ex_map = kit.make_exception_state(ex_oop);
1097       assert(ex_jvms->same_calls_as(ex_map->jvms()), "sanity");
1098       // Pop the last vestige of this method:
1099       caller->clone_shallow(C)->bind_map(ex_map);
1100       _exits.push_exception_state(ex_map);
1101     }
1102     assert(_exits.map() == normal_map, "keep the same return state");
1103   }
1104 
1105   {
1106     // Capture very early exceptions (receiver null checks) from caller JVMS
1107     GraphKit caller(_caller);
1108     SafePointNode* ex_map;
1109     while ((ex_map = caller.pop_exception_state()) != NULL) {
1110       _exits.add_exception_state(ex_map);
1111     }
1112   }
1113   _exits.map()->apply_replaced_nodes(_new_idx);
1114 }
1115 
1116 //-----------------------------create_entry_map-------------------------------
1117 // Initialize our parser map to contain the types at method entry.
1118 // For OSR, the map contains a single RawPtr parameter.
1119 // Initial monitor locking for sync. methods is performed by do_method_entry.
1120 SafePointNode* Parse::create_entry_map() {
1121   // Check for really stupid bail-out cases.
1122   uint len = TypeFunc::Parms + method()->max_locals() + method()->max_stack();
1123   if (len >= 32760) {
1124     C->record_method_not_compilable("too many local variables");
1125     return NULL;
1126   }
1127 
1128   // clear current replaced nodes that are of no use from here on (map was cloned in build_exits).
1129   _caller->map()->delete_replaced_nodes();
1130 
1131   // If this is an inlined method, we may have to do a receiver null check.
1132   if (_caller->has_method() && is_normal_parse() && !method()->is_static()) {
1133     GraphKit kit(_caller);
1134     kit.null_check_receiver_before_call(method());
1135     _caller = kit.transfer_exceptions_into_jvms();
1136     if (kit.stopped()) {
1137       _exits.add_exception_states_from(_caller);
1138       _exits.set_jvms(_caller);
1139       return NULL;
1140     }
1141   }
1142 
1143   assert(method() != NULL, "parser must have a method");
1144 
1145   // Create an initial safepoint to hold JVM state during parsing
1146   JVMState* jvms = new (C) JVMState(method(), _caller->has_method() ? _caller : NULL);
1147   set_map(new SafePointNode(len, jvms));
1148   jvms->set_map(map());
1149   record_for_igvn(map());
1150   assert(jvms->endoff() == len, "correct jvms sizing");
1151 
1152   SafePointNode* inmap = _caller->map();
1153   assert(inmap != NULL, "must have inmap");
1154   // In case of null check on receiver above
1155   map()->transfer_replaced_nodes_from(inmap, _new_idx);
1156 
1157   uint i;
1158 
1159   // Pass thru the predefined input parameters.
1160   for (i = 0; i < TypeFunc::Parms; i++) {
1161     map()->init_req(i, inmap->in(i));
1162   }
1163 
1164   if (depth() == 1) {
1165     assert(map()->memory()->Opcode() == Op_Parm, "");
1166     // Insert the memory aliasing node
1167     set_all_memory(reset_memory());
1168   }
1169   assert(merged_memory(), "");
1170 
1171   // Now add the locals which are initially bound to arguments:
1172   uint arg_size = tf()->domain()->cnt();
1173   ensure_stack(arg_size - TypeFunc::Parms);  // OSR methods have funny args
1174   for (i = TypeFunc::Parms; i < arg_size; i++) {
1175     map()->init_req(i, inmap->argument(_caller, i - TypeFunc::Parms));
1176   }
1177 
1178   // Clear out the rest of the map (locals and stack)
1179   for (i = arg_size; i < len; i++) {
1180     map()->init_req(i, top());
1181   }
1182 
1183   SafePointNode* entry_map = stop();
1184   return entry_map;
1185 }
1186 
1187 //-----------------------------do_method_entry--------------------------------
1188 // Emit any code needed in the pseudo-block before BCI zero.
1189 // The main thing to do is lock the receiver of a synchronized method.
1190 void Parse::do_method_entry() {
1191   set_parse_bci(InvocationEntryBci); // Pseudo-BCP
1192   set_sp(0);                         // Java Stack Pointer
1193 
1194   NOT_PRODUCT( count_compiled_calls(true/*at_method_entry*/, false/*is_inline*/); )
1195 
1196   if (C->env()->dtrace_method_probes()) {
1197     make_dtrace_method_entry(method());
1198   }
1199 
1200 #ifdef ASSERT
1201   // Narrow receiver type when it is too broad for the method being parsed.
1202   if (!method()->is_static()) {
1203     ciInstanceKlass* callee_holder = method()->holder();
1204     const Type* holder_type = TypeInstPtr::make(TypePtr::BotPTR, callee_holder);
1205 
1206     Node* receiver_obj = local(0);
1207     const TypeInstPtr* receiver_type = _gvn.type(receiver_obj)->isa_instptr();
1208 
1209     if (receiver_type != NULL && !receiver_type->higher_equal(holder_type)) {
1210       // Receiver should always be a subtype of callee holder.
1211       // But, since C2 type system doesn't properly track interfaces,
1212       // the invariant can't be expressed in the type system for default methods.
1213       // Example: for unrelated C <: I and D <: I, (C `meet` D) = Object </: I.
1214       assert(callee_holder->is_interface(), "missing subtype check");
1215 
1216       // Perform dynamic receiver subtype check against callee holder class w/ a halt on failure.
1217       Node* holder_klass = _gvn.makecon(TypeKlassPtr::make(callee_holder));
1218       Node* not_subtype_ctrl = gen_subtype_check(receiver_obj, holder_klass);
1219       assert(!stopped(), "not a subtype");
1220 
1221       Node* halt = _gvn.transform(new HaltNode(not_subtype_ctrl, frameptr(), "failed receiver subtype check"));
1222       C->root()->add_req(halt);
1223     }
1224   }
1225 #endif // ASSERT
1226 
1227   // If the method is synchronized, we need to construct a lock node, attach
1228   // it to the Start node, and pin it there.
1229   if (method()->is_synchronized()) {
1230     // Insert a FastLockNode right after the Start which takes as arguments
1231     // the current thread pointer, the "this" pointer & the address of the
1232     // stack slot pair used for the lock.  The "this" pointer is a projection
1233     // off the start node, but the locking spot has to be constructed by
1234     // creating a ConLNode of 0, and boxing it with a BoxLockNode.  The BoxLockNode
1235     // becomes the second argument to the FastLockNode call.  The
1236     // FastLockNode becomes the new control parent to pin it to the start.
1237 
1238     // Setup Object Pointer
1239     Node *lock_obj = NULL;
1240     if (method()->is_static()) {
1241       ciInstance* mirror = _method->holder()->java_mirror();
1242       const TypeInstPtr *t_lock = TypeInstPtr::make(mirror);
1243       lock_obj = makecon(t_lock);
1244     } else {                  // Else pass the "this" pointer,
1245       lock_obj = local(0);    // which is Parm0 from StartNode
1246     }
1247     // Clear out dead values from the debug info.
1248     kill_dead_locals();
1249     // Build the FastLockNode
1250     _synch_lock = shared_lock(lock_obj);
1251   }
1252 
1253   // Feed profiling data for parameters to the type system so it can
1254   // propagate it as speculative types
1255   record_profiled_parameters_for_speculation();
1256 }
1257 
1258 //------------------------------init_blocks------------------------------------
1259 // Initialize our parser map to contain the types/monitors at method entry.
1260 void Parse::init_blocks() {
1261   // Create the blocks.
1262   _block_count = flow()->block_count();
1263   _blocks = NEW_RESOURCE_ARRAY(Block, _block_count);
1264 
1265   // Initialize the structs.
1266   for (int rpo = 0; rpo < block_count(); rpo++) {
1267     Block* block = rpo_at(rpo);
1268     new(block) Block(this, rpo);
1269   }
1270 
1271   // Collect predecessor and successor information.
1272   for (int rpo = 0; rpo < block_count(); rpo++) {
1273     Block* block = rpo_at(rpo);
1274     block->init_graph(this);
1275   }
1276 }
1277 
1278 //-------------------------------init_node-------------------------------------
1279 Parse::Block::Block(Parse* outer, int rpo) : _live_locals() {
1280   _flow = outer->flow()->rpo_at(rpo);
1281   _pred_count = 0;
1282   _preds_parsed = 0;
1283   _count = 0;
1284   _is_parsed = false;
1285   _is_handler = false;
1286   _has_merged_backedge = false;
1287   _start_map = NULL;
1288   _has_predicates = false;
1289   _num_successors = 0;
1290   _all_successors = 0;
1291   _successors = NULL;
1292   assert(pred_count() == 0 && preds_parsed() == 0, "sanity");
1293   assert(!(is_merged() || is_parsed() || is_handler() || has_merged_backedge()), "sanity");
1294   assert(_live_locals.size() == 0, "sanity");
1295 
1296   // entry point has additional predecessor
1297   if (flow()->is_start())  _pred_count++;
1298   assert(flow()->is_start() == (this == outer->start_block()), "");
1299 }
1300 
1301 //-------------------------------init_graph------------------------------------
1302 void Parse::Block::init_graph(Parse* outer) {
1303   // Create the successor list for this parser block.
1304   GrowableArray<ciTypeFlow::Block*>* tfs = flow()->successors();
1305   GrowableArray<ciTypeFlow::Block*>* tfe = flow()->exceptions();
1306   int ns = tfs->length();
1307   int ne = tfe->length();
1308   _num_successors = ns;
1309   _all_successors = ns+ne;
1310   _successors = (ns+ne == 0) ? NULL : NEW_RESOURCE_ARRAY(Block*, ns+ne);
1311   int p = 0;
1312   for (int i = 0; i < ns+ne; i++) {
1313     ciTypeFlow::Block* tf2 = (i < ns) ? tfs->at(i) : tfe->at(i-ns);
1314     Block* block2 = outer->rpo_at(tf2->rpo());
1315     _successors[i] = block2;
1316 
1317     // Accumulate pred info for the other block, too.
1318     // Note: We also need to set _pred_count for exception blocks since they could
1319     // also have normal predecessors (reached without athrow by an explicit jump).
1320     // This also means that next_path_num can be called along exception paths.
1321     block2->_pred_count++;
1322     if (i >= ns) {
1323       block2->_is_handler = true;
1324     }
1325 
1326     #ifdef ASSERT
1327     // A block's successors must be distinguishable by BCI.
1328     // That is, no bytecode is allowed to branch to two different
1329     // clones of the same code location.
1330     for (int j = 0; j < i; j++) {
1331       Block* block1 = _successors[j];
1332       if (block1 == block2)  continue;  // duplicates are OK
1333       assert(block1->start() != block2->start(), "successors have unique bcis");
1334     }
1335     #endif
1336   }
1337 }
1338 
1339 //---------------------------successor_for_bci---------------------------------
1340 Parse::Block* Parse::Block::successor_for_bci(int bci) {
1341   for (int i = 0; i < all_successors(); i++) {
1342     Block* block2 = successor_at(i);
1343     if (block2->start() == bci)  return block2;
1344   }
1345   // We can actually reach here if ciTypeFlow traps out a block
1346   // due to an unloaded class, and concurrently with compilation the
1347   // class is then loaded, so that a later phase of the parser is
1348   // able to see more of the bytecode CFG.  Or, the flow pass and
1349   // the parser can have a minor difference of opinion about executability
1350   // of bytecodes.  For example, "obj.field = null" is executable even
1351   // if the field's type is an unloaded class; the flow pass used to
1352   // make a trap for such code.
1353   return NULL;
1354 }
1355 
1356 
1357 //-----------------------------stack_type_at-----------------------------------
1358 const Type* Parse::Block::stack_type_at(int i) const {
1359   return get_type(flow()->stack_type_at(i));
1360 }
1361 
1362 
1363 //-----------------------------local_type_at-----------------------------------
1364 const Type* Parse::Block::local_type_at(int i) const {
1365   // Make dead locals fall to bottom.
1366   if (_live_locals.size() == 0) {
1367     MethodLivenessResult live_locals = flow()->outer()->method()->liveness_at_bci(start());
1368     // This bitmap can be zero length if we saw a breakpoint.
1369     // In such cases, pretend they are all live.
1370     ((Block*)this)->_live_locals = live_locals;
1371   }
1372   if (_live_locals.size() > 0 && !_live_locals.at(i))
1373     return Type::BOTTOM;
1374 
1375   return get_type(flow()->local_type_at(i));
1376 }
1377 
1378 
1379 #ifndef PRODUCT
1380 
1381 //----------------------------name_for_bc--------------------------------------
1382 // helper method for BytecodeParseHistogram
1383 static const char* name_for_bc(int i) {
1384   return Bytecodes::is_defined(i) ? Bytecodes::name(Bytecodes::cast(i)) : "xxxunusedxxx";
1385 }
1386 
1387 //----------------------------BytecodeParseHistogram------------------------------------
1388 Parse::BytecodeParseHistogram::BytecodeParseHistogram(Parse *p, Compile *c) {
1389   _parser   = p;
1390   _compiler = c;
1391   if( ! _initialized ) { _initialized = true; reset(); }
1392 }
1393 
1394 //----------------------------current_count------------------------------------
1395 int Parse::BytecodeParseHistogram::current_count(BPHType bph_type) {
1396   switch( bph_type ) {
1397   case BPH_transforms: { return _parser->gvn().made_progress(); }
1398   case BPH_values:     { return _parser->gvn().made_new_values(); }
1399   default: { ShouldNotReachHere(); return 0; }
1400   }
1401 }
1402 
1403 //----------------------------initialized--------------------------------------
1404 bool Parse::BytecodeParseHistogram::initialized() { return _initialized; }
1405 
1406 //----------------------------reset--------------------------------------------
1407 void Parse::BytecodeParseHistogram::reset() {
1408   int i = Bytecodes::number_of_codes;
1409   while (i-- > 0) { _bytecodes_parsed[i] = 0; _nodes_constructed[i] = 0; _nodes_transformed[i] = 0; _new_values[i] = 0; }
1410 }
1411 
1412 //----------------------------set_initial_state--------------------------------
1413 // Record info when starting to parse one bytecode
1414 void Parse::BytecodeParseHistogram::set_initial_state( Bytecodes::Code bc ) {
1415   if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1416     _initial_bytecode    = bc;
1417     _initial_node_count  = _compiler->unique();
1418     _initial_transforms  = current_count(BPH_transforms);
1419     _initial_values      = current_count(BPH_values);
1420   }
1421 }
1422 
1423 //----------------------------record_change--------------------------------
1424 // Record results of parsing one bytecode
1425 void Parse::BytecodeParseHistogram::record_change() {
1426   if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1427     ++_bytecodes_parsed[_initial_bytecode];
1428     _nodes_constructed [_initial_bytecode] += (_compiler->unique() - _initial_node_count);
1429     _nodes_transformed [_initial_bytecode] += (current_count(BPH_transforms) - _initial_transforms);
1430     _new_values        [_initial_bytecode] += (current_count(BPH_values)     - _initial_values);
1431   }
1432 }
1433 
1434 
1435 //----------------------------print--------------------------------------------
1436 void Parse::BytecodeParseHistogram::print(float cutoff) {
1437   ResourceMark rm;
1438   // print profile
1439   int total  = 0;
1440   int i      = 0;
1441   for( i = 0; i < Bytecodes::number_of_codes; ++i ) { total += _bytecodes_parsed[i]; }
1442   int abs_sum = 0;
1443   tty->cr();   //0123456789012345678901234567890123456789012345678901234567890123456789
1444   tty->print_cr("Histogram of %d parsed bytecodes:", total);
1445   if( total == 0 ) { return; }
1446   tty->cr();
1447   tty->print_cr("absolute:  count of compiled bytecodes of this type");
1448   tty->print_cr("relative:  percentage contribution to compiled nodes");
1449   tty->print_cr("nodes   :  Average number of nodes constructed per bytecode");
1450   tty->print_cr("rnodes  :  Significance towards total nodes constructed, (nodes*relative)");
1451   tty->print_cr("transforms: Average amount of tranform progress per bytecode compiled");
1452   tty->print_cr("values  :  Average number of node values improved per bytecode");
1453   tty->print_cr("name    :  Bytecode name");
1454   tty->cr();
1455   tty->print_cr("  absolute  relative   nodes  rnodes  transforms  values   name");
1456   tty->print_cr("----------------------------------------------------------------------");
1457   while (--i > 0) {
1458     int       abs = _bytecodes_parsed[i];
1459     float     rel = abs * 100.0F / total;
1460     float   nodes = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_constructed[i])/_bytecodes_parsed[i];
1461     float  rnodes = _bytecodes_parsed[i] == 0 ? 0 :  rel * nodes;
1462     float  xforms = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_transformed[i])/_bytecodes_parsed[i];
1463     float  values = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _new_values       [i])/_bytecodes_parsed[i];
1464     if (cutoff <= rel) {
1465       tty->print_cr("%10d  %7.2f%%  %6.1f  %6.2f   %6.1f   %6.1f     %s", abs, rel, nodes, rnodes, xforms, values, name_for_bc(i));
1466       abs_sum += abs;
1467     }
1468   }
1469   tty->print_cr("----------------------------------------------------------------------");
1470   float rel_sum = abs_sum * 100.0F / total;
1471   tty->print_cr("%10d  %7.2f%%    (cutoff = %.2f%%)", abs_sum, rel_sum, cutoff);
1472   tty->print_cr("----------------------------------------------------------------------");
1473   tty->cr();
1474 }
1475 #endif
1476 
1477 //----------------------------load_state_from----------------------------------
1478 // Load block/map/sp.  But not do not touch iter/bci.
1479 void Parse::load_state_from(Block* block) {
1480   set_block(block);
1481   // load the block's JVM state:
1482   set_map(block->start_map());
1483   set_sp( block->start_sp());
1484 }
1485 
1486 
1487 //-----------------------------record_state------------------------------------
1488 void Parse::Block::record_state(Parse* p) {
1489   assert(!is_merged(), "can only record state once, on 1st inflow");
1490   assert(start_sp() == p->sp(), "stack pointer must agree with ciTypeFlow");
1491   set_start_map(p->stop());
1492 }
1493 
1494 
1495 //------------------------------do_one_block-----------------------------------
1496 void Parse::do_one_block() {
1497   if (TraceOptoParse) {
1498     Block *b = block();
1499     int ns = b->num_successors();
1500     int nt = b->all_successors();
1501 
1502     tty->print("Parsing block #%d at bci [%d,%d), successors: ",
1503                   block()->rpo(), block()->start(), block()->limit());
1504     for (int i = 0; i < nt; i++) {
1505       tty->print((( i < ns) ? " %d" : " %d(e)"), b->successor_at(i)->rpo());
1506     }
1507     if (b->is_loop_head()) tty->print("  lphd");
1508     tty->cr();
1509   }
1510 
1511   assert(block()->is_merged(), "must be merged before being parsed");
1512   block()->mark_parsed();
1513 
1514   // Set iterator to start of block.
1515   iter().reset_to_bci(block()->start());
1516 
1517   CompileLog* log = C->log();
1518 
1519   // Parse bytecodes
1520   while (!stopped() && !failing()) {
1521     iter().next();
1522 
1523     // Learn the current bci from the iterator:
1524     set_parse_bci(iter().cur_bci());
1525 
1526     if (bci() == block()->limit()) {
1527       // Do not walk into the next block until directed by do_all_blocks.
1528       merge(bci());
1529       break;
1530     }
1531     assert(bci() < block()->limit(), "bci still in block");
1532 
1533     if (log != NULL) {
1534       // Output an optional context marker, to help place actions
1535       // that occur during parsing of this BC.  If there is no log
1536       // output until the next context string, this context string
1537       // will be silently ignored.
1538       log->set_context("bc code='%d' bci='%d'", (int)bc(), bci());
1539     }
1540 
1541     if (block()->has_trap_at(bci())) {
1542       // We must respect the flow pass's traps, because it will refuse
1543       // to produce successors for trapping blocks.
1544       int trap_index = block()->flow()->trap_index();
1545       assert(trap_index != 0, "trap index must be valid");
1546       uncommon_trap(trap_index);
1547       break;
1548     }
1549 
1550     NOT_PRODUCT( parse_histogram()->set_initial_state(bc()); );
1551 
1552 #ifdef ASSERT
1553     int pre_bc_sp = sp();
1554     int inputs, depth;
1555     bool have_se = !stopped() && compute_stack_effects(inputs, depth);
1556     assert(!have_se || pre_bc_sp >= inputs, "have enough stack to execute this BC: pre_bc_sp=%d, inputs=%d", pre_bc_sp, inputs);
1557 #endif //ASSERT
1558 
1559     do_one_bytecode();
1560 
1561     assert(!have_se || stopped() || failing() || (sp() - pre_bc_sp) == depth,
1562            "incorrect depth prediction: sp=%d, pre_bc_sp=%d, depth=%d", sp(), pre_bc_sp, depth);
1563 
1564     do_exceptions();
1565 
1566     NOT_PRODUCT( parse_histogram()->record_change(); );
1567 
1568     if (log != NULL)
1569       log->clear_context();  // skip marker if nothing was printed
1570 
1571     // Fall into next bytecode.  Each bytecode normally has 1 sequential
1572     // successor which is typically made ready by visiting this bytecode.
1573     // If the successor has several predecessors, then it is a merge
1574     // point, starts a new basic block, and is handled like other basic blocks.
1575   }
1576 }
1577 
1578 
1579 //------------------------------merge------------------------------------------
1580 void Parse::set_parse_bci(int bci) {
1581   set_bci(bci);
1582   Node_Notes* nn = C->default_node_notes();
1583   if (nn == NULL)  return;
1584 
1585   // Collect debug info for inlined calls unless -XX:-DebugInlinedCalls.
1586   if (!DebugInlinedCalls && depth() > 1) {
1587     return;
1588   }
1589 
1590   // Update the JVMS annotation, if present.
1591   JVMState* jvms = nn->jvms();
1592   if (jvms != NULL && jvms->bci() != bci) {
1593     // Update the JVMS.
1594     jvms = jvms->clone_shallow(C);
1595     jvms->set_bci(bci);
1596     nn->set_jvms(jvms);
1597   }
1598 }
1599 
1600 //------------------------------merge------------------------------------------
1601 // Merge the current mapping into the basic block starting at bci
1602 void Parse::merge(int target_bci) {
1603   Block* target = successor_for_bci(target_bci);
1604   if (target == NULL) { handle_missing_successor(target_bci); return; }
1605   assert(!target->is_ready(), "our arrival must be expected");
1606   int pnum = target->next_path_num();
1607   merge_common(target, pnum);
1608 }
1609 
1610 //-------------------------merge_new_path--------------------------------------
1611 // Merge the current mapping into the basic block, using a new path
1612 void Parse::merge_new_path(int target_bci) {
1613   Block* target = successor_for_bci(target_bci);
1614   if (target == NULL) { handle_missing_successor(target_bci); return; }
1615   assert(!target->is_ready(), "new path into frozen graph");
1616   int pnum = target->add_new_path();
1617   merge_common(target, pnum);
1618 }
1619 
1620 //-------------------------merge_exception-------------------------------------
1621 // Merge the current mapping into the basic block starting at bci
1622 // The ex_oop must be pushed on the stack, unlike throw_to_exit.
1623 void Parse::merge_exception(int target_bci) {
1624 #ifdef ASSERT
1625   if (target_bci < bci()) {
1626     C->set_exception_backedge();
1627   }
1628 #endif
1629   assert(sp() == 1, "must have only the throw exception on the stack");
1630   Block* target = successor_for_bci(target_bci);
1631   if (target == NULL) { handle_missing_successor(target_bci); return; }
1632   assert(target->is_handler(), "exceptions are handled by special blocks");
1633   int pnum = target->add_new_path();
1634   merge_common(target, pnum);
1635 }
1636 
1637 //--------------------handle_missing_successor---------------------------------
1638 void Parse::handle_missing_successor(int target_bci) {
1639 #ifndef PRODUCT
1640   Block* b = block();
1641   int trap_bci = b->flow()->has_trap()? b->flow()->trap_bci(): -1;
1642   tty->print_cr("### Missing successor at bci:%d for block #%d (trap_bci:%d)", target_bci, b->rpo(), trap_bci);
1643 #endif
1644   ShouldNotReachHere();
1645 }
1646 
1647 //--------------------------merge_common---------------------------------------
1648 void Parse::merge_common(Parse::Block* target, int pnum) {
1649   if (TraceOptoParse) {
1650     tty->print("Merging state at block #%d bci:%d", target->rpo(), target->start());
1651   }
1652 
1653   // Zap extra stack slots to top
1654   assert(sp() == target->start_sp(), "");
1655   clean_stack(sp());
1656 
1657   if (!target->is_merged()) {   // No prior mapping at this bci
1658     if (TraceOptoParse) { tty->print(" with empty state");  }
1659 
1660     // If this path is dead, do not bother capturing it as a merge.
1661     // It is "as if" we had 1 fewer predecessors from the beginning.
1662     if (stopped()) {
1663       if (TraceOptoParse)  tty->print_cr(", but path is dead and doesn't count");
1664       return;
1665     }
1666 
1667     // Make a region if we know there are multiple or unpredictable inputs.
1668     // (Also, if this is a plain fall-through, we might see another region,
1669     // which must not be allowed into this block's map.)
1670     if (pnum > PhiNode::Input         // Known multiple inputs.
1671         || target->is_handler()       // These have unpredictable inputs.
1672         || target->is_loop_head()     // Known multiple inputs
1673         || control()->is_Region()) {  // We must hide this guy.
1674 
1675       int current_bci = bci();
1676       set_parse_bci(target->start()); // Set target bci
1677       if (target->is_SEL_head()) {
1678         DEBUG_ONLY( target->mark_merged_backedge(block()); )
1679         if (target->start() == 0) {
1680           // Add loop predicate for the special case when
1681           // there are backbranches to the method entry.
1682           add_empty_predicates();
1683         }
1684       }
1685       // Add a Region to start the new basic block.  Phis will be added
1686       // later lazily.
1687       int edges = target->pred_count();
1688       if (edges < pnum)  edges = pnum;  // might be a new path!
1689       RegionNode *r = new RegionNode(edges+1);
1690       gvn().set_type(r, Type::CONTROL);
1691       record_for_igvn(r);
1692       // zap all inputs to NULL for debugging (done in Node(uint) constructor)
1693       // for (int j = 1; j < edges+1; j++) { r->init_req(j, NULL); }
1694       r->init_req(pnum, control());
1695       set_control(r);
1696       set_parse_bci(current_bci); // Restore bci
1697     }
1698 
1699     // Convert the existing Parser mapping into a mapping at this bci.
1700     store_state_to(target);
1701     assert(target->is_merged(), "do not come here twice");
1702 
1703   } else {                      // Prior mapping at this bci
1704     if (TraceOptoParse) {  tty->print(" with previous state"); }
1705 #ifdef ASSERT
1706     if (target->is_SEL_head()) {
1707       target->mark_merged_backedge(block());
1708     }
1709 #endif
1710     // We must not manufacture more phis if the target is already parsed.
1711     bool nophi = target->is_parsed();
1712 
1713     SafePointNode* newin = map();// Hang on to incoming mapping
1714     Block* save_block = block(); // Hang on to incoming block;
1715     load_state_from(target);    // Get prior mapping
1716 
1717     assert(newin->jvms()->locoff() == jvms()->locoff(), "JVMS layouts agree");
1718     assert(newin->jvms()->stkoff() == jvms()->stkoff(), "JVMS layouts agree");
1719     assert(newin->jvms()->monoff() == jvms()->monoff(), "JVMS layouts agree");
1720     assert(newin->jvms()->endoff() == jvms()->endoff(), "JVMS layouts agree");
1721 
1722     // Iterate over my current mapping and the old mapping.
1723     // Where different, insert Phi functions.
1724     // Use any existing Phi functions.
1725     assert(control()->is_Region(), "must be merging to a region");
1726     RegionNode* r = control()->as_Region();
1727 
1728     // Compute where to merge into
1729     // Merge incoming control path
1730     r->init_req(pnum, newin->control());
1731 
1732     if (pnum == 1) {            // Last merge for this Region?
1733       if (!block()->flow()->is_irreducible_entry()) {
1734         Node* result = _gvn.transform_no_reclaim(r);
1735         if (r != result && TraceOptoParse) {
1736           tty->print_cr("Block #%d replace %d with %d", block()->rpo(), r->_idx, result->_idx);
1737         }
1738       }
1739       record_for_igvn(r);
1740     }
1741 
1742     // Update all the non-control inputs to map:
1743     assert(TypeFunc::Parms == newin->jvms()->locoff(), "parser map should contain only youngest jvms");
1744     bool check_elide_phi = target->is_SEL_backedge(save_block);
1745     for (uint j = 1; j < newin->req(); j++) {
1746       Node* m = map()->in(j);   // Current state of target.
1747       Node* n = newin->in(j);   // Incoming change to target state.
1748       PhiNode* phi;
1749       if (m->is_Phi() && m->as_Phi()->region() == r)
1750         phi = m->as_Phi();
1751       else
1752         phi = NULL;
1753       if (m != n) {             // Different; must merge
1754         switch (j) {
1755         // Frame pointer and Return Address never changes
1756         case TypeFunc::FramePtr:// Drop m, use the original value
1757         case TypeFunc::ReturnAdr:
1758           break;
1759         case TypeFunc::Memory:  // Merge inputs to the MergeMem node
1760           assert(phi == NULL, "the merge contains phis, not vice versa");
1761           merge_memory_edges(n->as_MergeMem(), pnum, nophi);
1762           continue;
1763         default:                // All normal stuff
1764           if (phi == NULL) {
1765             const JVMState* jvms = map()->jvms();
1766             if (EliminateNestedLocks &&
1767                 jvms->is_mon(j) && jvms->is_monitor_box(j)) {
1768               // BoxLock nodes are not commoning.
1769               // Use old BoxLock node as merged box.
1770               assert(newin->jvms()->is_monitor_box(j), "sanity");
1771               // This assert also tests that nodes are BoxLock.
1772               assert(BoxLockNode::same_slot(n, m), "sanity");
1773               C->gvn_replace_by(n, m);
1774             } else if (!check_elide_phi || !target->can_elide_SEL_phi(j)) {
1775               phi = ensure_phi(j, nophi);
1776             }
1777           }
1778           break;
1779         }
1780       }
1781       // At this point, n might be top if:
1782       //  - there is no phi (because TypeFlow detected a conflict), or
1783       //  - the corresponding control edges is top (a dead incoming path)
1784       // It is a bug if we create a phi which sees a garbage value on a live path.
1785 
1786       if (phi != NULL) {
1787         assert(n != top() || r->in(pnum) == top(), "live value must not be garbage");
1788         assert(phi->region() == r, "");
1789         phi->set_req(pnum, n);  // Then add 'n' to the merge
1790         if (pnum == PhiNode::Input) {
1791           // Last merge for this Phi.
1792           // So far, Phis have had a reasonable type from ciTypeFlow.
1793           // Now _gvn will join that with the meet of current inputs.
1794           // BOTTOM is never permissible here, 'cause pessimistically
1795           // Phis of pointers cannot lose the basic pointer type.
1796           debug_only(const Type* bt1 = phi->bottom_type());
1797           assert(bt1 != Type::BOTTOM, "should not be building conflict phis");
1798           map()->set_req(j, _gvn.transform_no_reclaim(phi));
1799           debug_only(const Type* bt2 = phi->bottom_type());
1800           assert(bt2->higher_equal_speculative(bt1), "must be consistent with type-flow");
1801           record_for_igvn(phi);
1802         }
1803       }
1804     } // End of for all values to be merged
1805 
1806     if (pnum == PhiNode::Input &&
1807         !r->in(0)) {         // The occasional useless Region
1808       assert(control() == r, "");
1809       set_control(r->nonnull_req());
1810     }
1811 
1812     map()->merge_replaced_nodes_with(newin);
1813 
1814     // newin has been subsumed into the lazy merge, and is now dead.
1815     set_block(save_block);
1816 
1817     stop();                     // done with this guy, for now
1818   }
1819 
1820   if (TraceOptoParse) {
1821     tty->print_cr(" on path %d", pnum);
1822   }
1823 
1824   // Done with this parser state.
1825   assert(stopped(), "");
1826 }
1827 
1828 
1829 //--------------------------merge_memory_edges---------------------------------
1830 void Parse::merge_memory_edges(MergeMemNode* n, int pnum, bool nophi) {
1831   // (nophi means we must not create phis, because we already parsed here)
1832   assert(n != NULL, "");
1833   // Merge the inputs to the MergeMems
1834   MergeMemNode* m = merged_memory();
1835 
1836   assert(control()->is_Region(), "must be merging to a region");
1837   RegionNode* r = control()->as_Region();
1838 
1839   PhiNode* base = NULL;
1840   MergeMemNode* remerge = NULL;
1841   for (MergeMemStream mms(m, n); mms.next_non_empty2(); ) {
1842     Node *p = mms.force_memory();
1843     Node *q = mms.memory2();
1844     if (mms.is_empty() && nophi) {
1845       // Trouble:  No new splits allowed after a loop body is parsed.
1846       // Instead, wire the new split into a MergeMem on the backedge.
1847       // The optimizer will sort it out, slicing the phi.
1848       if (remerge == NULL) {
1849         guarantee(base != NULL, "");
1850         assert(base->in(0) != NULL, "should not be xformed away");
1851         remerge = MergeMemNode::make(base->in(pnum));
1852         gvn().set_type(remerge, Type::MEMORY);
1853         base->set_req(pnum, remerge);
1854       }
1855       remerge->set_memory_at(mms.alias_idx(), q);
1856       continue;
1857     }
1858     assert(!q->is_MergeMem(), "");
1859     PhiNode* phi;
1860     if (p != q) {
1861       phi = ensure_memory_phi(mms.alias_idx(), nophi);
1862     } else {
1863       if (p->is_Phi() && p->as_Phi()->region() == r)
1864         phi = p->as_Phi();
1865       else
1866         phi = NULL;
1867     }
1868     // Insert q into local phi
1869     if (phi != NULL) {
1870       assert(phi->region() == r, "");
1871       p = phi;
1872       phi->set_req(pnum, q);
1873       if (mms.at_base_memory()) {
1874         base = phi;  // delay transforming it
1875       } else if (pnum == 1) {
1876         record_for_igvn(phi);
1877         p = _gvn.transform_no_reclaim(phi);
1878       }
1879       mms.set_memory(p);// store back through the iterator
1880     }
1881   }
1882   // Transform base last, in case we must fiddle with remerging.
1883   if (base != NULL && pnum == 1) {
1884     record_for_igvn(base);
1885     m->set_base_memory( _gvn.transform_no_reclaim(base) );
1886   }
1887 }
1888 
1889 
1890 //------------------------ensure_phis_everywhere-------------------------------
1891 void Parse::ensure_phis_everywhere() {
1892   ensure_phi(TypeFunc::I_O);
1893 
1894   // Ensure a phi on all currently known memories.
1895   for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
1896     ensure_memory_phi(mms.alias_idx());
1897     debug_only(mms.set_memory());  // keep the iterator happy
1898   }
1899 
1900   // Note:  This is our only chance to create phis for memory slices.
1901   // If we miss a slice that crops up later, it will have to be
1902   // merged into the base-memory phi that we are building here.
1903   // Later, the optimizer will comb out the knot, and build separate
1904   // phi-loops for each memory slice that matters.
1905 
1906   // Monitors must nest nicely and not get confused amongst themselves.
1907   // Phi-ify everything up to the monitors, though.
1908   uint monoff = map()->jvms()->monoff();
1909   uint nof_monitors = map()->jvms()->nof_monitors();
1910 
1911   assert(TypeFunc::Parms == map()->jvms()->locoff(), "parser map should contain only youngest jvms");
1912   bool check_elide_phi = block()->is_SEL_head();
1913   for (uint i = TypeFunc::Parms; i < monoff; i++) {
1914     if (!check_elide_phi || !block()->can_elide_SEL_phi(i)) {
1915       ensure_phi(i);
1916     }
1917   }
1918 
1919   // Even monitors need Phis, though they are well-structured.
1920   // This is true for OSR methods, and also for the rare cases where
1921   // a monitor object is the subject of a replace_in_map operation.
1922   // See bugs 4426707 and 5043395.
1923   for (uint m = 0; m < nof_monitors; m++) {
1924     ensure_phi(map()->jvms()->monitor_obj_offset(m));
1925   }
1926 }
1927 
1928 
1929 //-----------------------------add_new_path------------------------------------
1930 // Add a previously unaccounted predecessor to this block.
1931 int Parse::Block::add_new_path() {
1932   // If there is no map, return the lowest unused path number.
1933   if (!is_merged())  return pred_count()+1;  // there will be a map shortly
1934 
1935   SafePointNode* map = start_map();
1936   if (!map->control()->is_Region())
1937     return pred_count()+1;  // there may be a region some day
1938   RegionNode* r = map->control()->as_Region();
1939 
1940   // Add new path to the region.
1941   uint pnum = r->req();
1942   r->add_req(NULL);
1943 
1944   for (uint i = 1; i < map->req(); i++) {
1945     Node* n = map->in(i);
1946     if (i == TypeFunc::Memory) {
1947       // Ensure a phi on all currently known memories.
1948       for (MergeMemStream mms(n->as_MergeMem()); mms.next_non_empty(); ) {
1949         Node* phi = mms.memory();
1950         if (phi->is_Phi() && phi->as_Phi()->region() == r) {
1951           assert(phi->req() == pnum, "must be same size as region");
1952           phi->add_req(NULL);
1953         }
1954       }
1955     } else {
1956       if (n->is_Phi() && n->as_Phi()->region() == r) {
1957         assert(n->req() == pnum, "must be same size as region");
1958         n->add_req(NULL);
1959       }
1960     }
1961   }
1962 
1963   return pnum;
1964 }
1965 
1966 //------------------------------ensure_phi-------------------------------------
1967 // Turn the idx'th entry of the current map into a Phi
1968 PhiNode *Parse::ensure_phi(int idx, bool nocreate) {
1969   SafePointNode* map = this->map();
1970   Node* region = map->control();
1971   assert(region->is_Region(), "");
1972 
1973   Node* o = map->in(idx);
1974   assert(o != NULL, "");
1975 
1976   if (o == top())  return NULL; // TOP always merges into TOP
1977 
1978   if (o->is_Phi() && o->as_Phi()->region() == region) {
1979     return o->as_Phi();
1980   }
1981 
1982   // Now use a Phi here for merging
1983   assert(!nocreate, "Cannot build a phi for a block already parsed.");
1984   const JVMState* jvms = map->jvms();
1985   const Type* t = NULL;
1986   if (jvms->is_loc(idx)) {
1987     t = block()->local_type_at(idx - jvms->locoff());
1988   } else if (jvms->is_stk(idx)) {
1989     t = block()->stack_type_at(idx - jvms->stkoff());
1990   } else if (jvms->is_mon(idx)) {
1991     assert(!jvms->is_monitor_box(idx), "no phis for boxes");
1992     t = TypeInstPtr::BOTTOM; // this is sufficient for a lock object
1993   } else if ((uint)idx < TypeFunc::Parms) {
1994     t = o->bottom_type();  // Type::RETURN_ADDRESS or such-like.
1995   } else {
1996     assert(false, "no type information for this phi");
1997   }
1998 
1999   // If the type falls to bottom, then this must be a local that
2000   // is mixing ints and oops or some such.  Forcing it to top
2001   // makes it go dead.
2002   if (t == Type::BOTTOM) {
2003     map->set_req(idx, top());
2004     return NULL;
2005   }
2006 
2007   // Do not create phis for top either.
2008   // A top on a non-null control flow must be an unused even after the.phi.
2009   if (t == Type::TOP || t == Type::HALF) {
2010     map->set_req(idx, top());
2011     return NULL;
2012   }
2013 
2014   PhiNode* phi = PhiNode::make(region, o, t);
2015   gvn().set_type(phi, t);
2016   if (C->do_escape_analysis()) record_for_igvn(phi);
2017   map->set_req(idx, phi);
2018   return phi;
2019 }
2020 
2021 //--------------------------ensure_memory_phi----------------------------------
2022 // Turn the idx'th slice of the current memory into a Phi
2023 PhiNode *Parse::ensure_memory_phi(int idx, bool nocreate) {
2024   MergeMemNode* mem = merged_memory();
2025   Node* region = control();
2026   assert(region->is_Region(), "");
2027 
2028   Node *o = (idx == Compile::AliasIdxBot)? mem->base_memory(): mem->memory_at(idx);
2029   assert(o != NULL && o != top(), "");
2030 
2031   PhiNode* phi;
2032   if (o->is_Phi() && o->as_Phi()->region() == region) {
2033     phi = o->as_Phi();
2034     if (phi == mem->base_memory() && idx >= Compile::AliasIdxRaw) {
2035       // clone the shared base memory phi to make a new memory split
2036       assert(!nocreate, "Cannot build a phi for a block already parsed.");
2037       const Type* t = phi->bottom_type();
2038       const TypePtr* adr_type = C->get_adr_type(idx);
2039       phi = phi->slice_memory(adr_type);
2040       gvn().set_type(phi, t);
2041     }
2042     return phi;
2043   }
2044 
2045   // Now use a Phi here for merging
2046   assert(!nocreate, "Cannot build a phi for a block already parsed.");
2047   const Type* t = o->bottom_type();
2048   const TypePtr* adr_type = C->get_adr_type(idx);
2049   phi = PhiNode::make(region, o, t, adr_type);
2050   gvn().set_type(phi, t);
2051   if (idx == Compile::AliasIdxBot)
2052     mem->set_base_memory(phi);
2053   else
2054     mem->set_memory_at(idx, phi);
2055   return phi;
2056 }
2057 
2058 //------------------------------call_register_finalizer-----------------------
2059 // Check the klass of the receiver and call register_finalizer if the
2060 // class need finalization.
2061 void Parse::call_register_finalizer() {
2062   Node* receiver = local(0);
2063   assert(receiver != NULL && receiver->bottom_type()->isa_instptr() != NULL,
2064          "must have non-null instance type");
2065 
2066   const TypeInstPtr *tinst = receiver->bottom_type()->isa_instptr();
2067   if (tinst != NULL && tinst->klass()->is_loaded() && !tinst->klass_is_exact()) {
2068     // The type isn't known exactly so see if CHA tells us anything.
2069     ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
2070     if (!Dependencies::has_finalizable_subclass(ik)) {
2071       // No finalizable subclasses so skip the dynamic check.
2072       C->dependencies()->assert_has_no_finalizable_subclasses(ik);
2073       return;
2074     }
2075   }
2076 
2077   // Insert a dynamic test for whether the instance needs
2078   // finalization.  In general this will fold up since the concrete
2079   // class is often visible so the access flags are constant.
2080   Node* klass_addr = basic_plus_adr( receiver, receiver, oopDesc::klass_offset_in_bytes() );
2081   Node* klass = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), klass_addr, TypeInstPtr::KLASS));
2082 
2083   Node* access_flags_addr = basic_plus_adr(klass, klass, in_bytes(Klass::access_flags_offset()));
2084   Node* access_flags = make_load(NULL, access_flags_addr, TypeInt::INT, T_INT, MemNode::unordered);
2085 
2086   Node* mask  = _gvn.transform(new AndINode(access_flags, intcon(JVM_ACC_HAS_FINALIZER)));
2087   Node* check = _gvn.transform(new CmpINode(mask, intcon(0)));
2088   Node* test  = _gvn.transform(new BoolNode(check, BoolTest::ne));
2089 
2090   IfNode* iff = create_and_map_if(control(), test, PROB_MAX, COUNT_UNKNOWN);
2091 
2092   RegionNode* result_rgn = new RegionNode(3);
2093   record_for_igvn(result_rgn);
2094 
2095   Node *skip_register = _gvn.transform(new IfFalseNode(iff));
2096   result_rgn->init_req(1, skip_register);
2097 
2098   Node *needs_register = _gvn.transform(new IfTrueNode(iff));
2099   set_control(needs_register);
2100   if (stopped()) {
2101     // There is no slow path.
2102     result_rgn->init_req(2, top());
2103   } else {
2104     Node *call = make_runtime_call(RC_NO_LEAF,
2105                                    OptoRuntime::register_finalizer_Type(),
2106                                    OptoRuntime::register_finalizer_Java(),
2107                                    NULL, TypePtr::BOTTOM,
2108                                    receiver);
2109     make_slow_call_ex(call, env()->Throwable_klass(), true);
2110 
2111     Node* fast_io  = call->in(TypeFunc::I_O);
2112     Node* fast_mem = call->in(TypeFunc::Memory);
2113     // These two phis are pre-filled with copies of of the fast IO and Memory
2114     Node* io_phi   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
2115     Node* mem_phi  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
2116 
2117     result_rgn->init_req(2, control());
2118     io_phi    ->init_req(2, i_o());
2119     mem_phi   ->init_req(2, reset_memory());
2120 
2121     set_all_memory( _gvn.transform(mem_phi) );
2122     set_i_o(        _gvn.transform(io_phi) );
2123   }
2124 
2125   set_control( _gvn.transform(result_rgn) );
2126 }
2127 
2128 // Add check to deoptimize once holder klass is fully initialized.
2129 void Parse::clinit_deopt() {
2130   assert(C->has_method(), "only for normal compilations");
2131   assert(depth() == 1, "only for main compiled method");
2132   assert(is_normal_parse(), "no barrier needed on osr entry");
2133   assert(!method()->holder()->is_not_initialized(), "initialization should have been started");
2134 
2135   set_parse_bci(0);
2136 
2137   Node* holder = makecon(TypeKlassPtr::make(method()->holder()));
2138   guard_klass_being_initialized(holder);
2139 }
2140 
2141 // Add check to deoptimize if RTM state is not ProfileRTM
2142 void Parse::rtm_deopt() {
2143 #if INCLUDE_RTM_OPT
2144   if (C->profile_rtm()) {
2145     assert(C->has_method(), "only for normal compilations");
2146     assert(!C->method()->method_data()->is_empty(), "MDO is needed to record RTM state");
2147     assert(depth() == 1, "generate check only for main compiled method");
2148 
2149     // Set starting bci for uncommon trap.
2150     set_parse_bci(is_osr_parse() ? osr_bci() : 0);
2151 
2152     // Load the rtm_state from the MethodData.
2153     const TypePtr* adr_type = TypeMetadataPtr::make(C->method()->method_data());
2154     Node* mdo = makecon(adr_type);
2155     int offset = MethodData::rtm_state_offset_in_bytes();
2156     Node* adr_node = basic_plus_adr(mdo, mdo, offset);
2157     Node* rtm_state = make_load(control(), adr_node, TypeInt::INT, T_INT, adr_type, MemNode::unordered);
2158 
2159     // Separate Load from Cmp by Opaque.
2160     // In expand_macro_nodes() it will be replaced either
2161     // with this load when there are locks in the code
2162     // or with ProfileRTM (cmp->in(2)) otherwise so that
2163     // the check will fold.
2164     Node* profile_state = makecon(TypeInt::make(ProfileRTM));
2165     Node* opq   = _gvn.transform( new Opaque3Node(C, rtm_state, Opaque3Node::RTM_OPT) );
2166     Node* chk   = _gvn.transform( new CmpINode(opq, profile_state) );
2167     Node* tst   = _gvn.transform( new BoolNode(chk, BoolTest::eq) );
2168     // Branch to failure if state was changed
2169     { BuildCutout unless(this, tst, PROB_ALWAYS);
2170       uncommon_trap(Deoptimization::Reason_rtm_state_change,
2171                     Deoptimization::Action_make_not_entrant);
2172     }
2173   }
2174 #endif
2175 }
2176 
2177 void Parse::decrement_age() {
2178   MethodCounters* mc = method()->ensure_method_counters();
2179   if (mc == NULL) {
2180     C->record_failure("Must have MCs");
2181     return;
2182   }
2183   assert(!is_osr_parse(), "Not doing this for OSRs");
2184 
2185   // Set starting bci for uncommon trap.
2186   set_parse_bci(0);
2187 
2188   const TypePtr* adr_type = TypeRawPtr::make((address)mc);
2189   Node* mc_adr = makecon(adr_type);
2190   Node* cnt_adr = basic_plus_adr(mc_adr, mc_adr, in_bytes(MethodCounters::nmethod_age_offset()));
2191   Node* cnt = make_load(control(), cnt_adr, TypeInt::INT, T_INT, adr_type, MemNode::unordered);
2192   Node* decr = _gvn.transform(new SubINode(cnt, makecon(TypeInt::ONE)));
2193   store_to_memory(control(), cnt_adr, decr, T_INT, adr_type, MemNode::unordered);
2194   Node *chk   = _gvn.transform(new CmpINode(decr, makecon(TypeInt::ZERO)));
2195   Node* tst   = _gvn.transform(new BoolNode(chk, BoolTest::gt));
2196   { BuildCutout unless(this, tst, PROB_ALWAYS);
2197     uncommon_trap(Deoptimization::Reason_tenured,
2198                   Deoptimization::Action_make_not_entrant);
2199   }
2200 }
2201 
2202 //------------------------------return_current---------------------------------
2203 // Append current _map to _exit_return
2204 void Parse::return_current(Node* value) {
2205   if (RegisterFinalizersAtInit &&
2206       method()->intrinsic_id() == vmIntrinsics::_Object_init) {
2207     call_register_finalizer();
2208   }
2209 
2210   // Do not set_parse_bci, so that return goo is credited to the return insn.
2211   set_bci(InvocationEntryBci);
2212   if (method()->is_synchronized() && GenerateSynchronizationCode) {
2213     shared_unlock(_synch_lock->box_node(), _synch_lock->obj_node());
2214   }
2215   if (C->env()->dtrace_method_probes()) {
2216     make_dtrace_method_exit(method());
2217   }
2218   SafePointNode* exit_return = _exits.map();
2219   exit_return->in( TypeFunc::Control  )->add_req( control() );
2220   exit_return->in( TypeFunc::I_O      )->add_req( i_o    () );
2221   Node *mem = exit_return->in( TypeFunc::Memory   );
2222   for (MergeMemStream mms(mem->as_MergeMem(), merged_memory()); mms.next_non_empty2(); ) {
2223     if (mms.is_empty()) {
2224       // get a copy of the base memory, and patch just this one input
2225       const TypePtr* adr_type = mms.adr_type(C);
2226       Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);
2227       assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");
2228       gvn().set_type_bottom(phi);
2229       phi->del_req(phi->req()-1);  // prepare to re-patch
2230       mms.set_memory(phi);
2231     }
2232     mms.memory()->add_req(mms.memory2());
2233   }
2234 
2235   // frame pointer is always same, already captured
2236   if (value != NULL) {
2237     // If returning oops to an interface-return, there is a silent free
2238     // cast from oop to interface allowed by the Verifier.  Make it explicit
2239     // here.
2240     Node* phi = _exits.argument(0);
2241     const TypeInstPtr *tr = phi->bottom_type()->isa_instptr();
2242     if (tr && tr->klass()->is_loaded() &&
2243         tr->klass()->is_interface()) {
2244       const TypeInstPtr *tp = value->bottom_type()->isa_instptr();
2245       if (tp && tp->klass()->is_loaded() &&
2246           !tp->klass()->is_interface()) {
2247         // sharpen the type eagerly; this eases certain assert checking
2248         if (tp->higher_equal(TypeInstPtr::NOTNULL))
2249           tr = tr->join_speculative(TypeInstPtr::NOTNULL)->is_instptr();
2250         value = _gvn.transform(new CheckCastPPNode(0, value, tr));
2251       }
2252     } else {
2253       // Also handle returns of oop-arrays to an arrays-of-interface return
2254       const TypeInstPtr* phi_tip;
2255       const TypeInstPtr* val_tip;
2256       Type::get_arrays_base_elements(phi->bottom_type(), value->bottom_type(), &phi_tip, &val_tip);
2257       if (phi_tip != NULL && phi_tip->is_loaded() && phi_tip->klass()->is_interface() &&
2258           val_tip != NULL && val_tip->is_loaded() && !val_tip->klass()->is_interface()) {
2259         value = _gvn.transform(new CheckCastPPNode(0, value, phi->bottom_type()));
2260       }
2261     }
2262     phi->add_req(value);
2263   }
2264 
2265   if (_first_return) {
2266     _exits.map()->transfer_replaced_nodes_from(map(), _new_idx);
2267     _first_return = false;
2268   } else {
2269     _exits.map()->merge_replaced_nodes_with(map());
2270   }
2271 
2272   stop_and_kill_map();          // This CFG path dies here
2273 }
2274 
2275 
2276 //------------------------------add_safepoint----------------------------------
2277 void Parse::add_safepoint() {
2278   uint parms = TypeFunc::Parms+1;
2279 
2280   // Clear out dead values from the debug info.
2281   kill_dead_locals();
2282 
2283   // Clone the JVM State
2284   SafePointNode *sfpnt = new SafePointNode(parms, NULL);
2285 
2286   // Capture memory state BEFORE a SafePoint.  Since we can block at a
2287   // SafePoint we need our GC state to be safe; i.e. we need all our current
2288   // write barriers (card marks) to not float down after the SafePoint so we
2289   // must read raw memory.  Likewise we need all oop stores to match the card
2290   // marks.  If deopt can happen, we need ALL stores (we need the correct JVM
2291   // state on a deopt).
2292 
2293   // We do not need to WRITE the memory state after a SafePoint.  The control
2294   // edge will keep card-marks and oop-stores from floating up from below a
2295   // SafePoint and our true dependency added here will keep them from floating
2296   // down below a SafePoint.
2297 
2298   // Clone the current memory state
2299   Node* mem = MergeMemNode::make(map()->memory());
2300 
2301   mem = _gvn.transform(mem);
2302 
2303   // Pass control through the safepoint
2304   sfpnt->init_req(TypeFunc::Control  , control());
2305   // Fix edges normally used by a call
2306   sfpnt->init_req(TypeFunc::I_O      , top() );
2307   sfpnt->init_req(TypeFunc::Memory   , mem   );
2308   sfpnt->init_req(TypeFunc::ReturnAdr, top() );
2309   sfpnt->init_req(TypeFunc::FramePtr , top() );
2310 
2311   // Create a node for the polling address
2312   Node *polladr;
2313   Node *thread = _gvn.transform(new ThreadLocalNode());
2314   Node *polling_page_load_addr = _gvn.transform(basic_plus_adr(top(), thread, in_bytes(JavaThread::polling_page_offset())));
2315   polladr = make_load(control(), polling_page_load_addr, TypeRawPtr::BOTTOM, T_ADDRESS, Compile::AliasIdxRaw, MemNode::unordered);
2316   sfpnt->init_req(TypeFunc::Parms+0, _gvn.transform(polladr));
2317 
2318   // Fix up the JVM State edges
2319   add_safepoint_edges(sfpnt);
2320   Node *transformed_sfpnt = _gvn.transform(sfpnt);
2321   set_control(transformed_sfpnt);
2322 
2323   // Provide an edge from root to safepoint.  This makes the safepoint
2324   // appear useful until the parse has completed.
2325   if (transformed_sfpnt->is_SafePoint()) {
2326     assert(C->root() != NULL, "Expect parse is still valid");
2327     C->root()->add_prec(transformed_sfpnt);
2328   }
2329 }
2330 
2331 #ifndef PRODUCT
2332 //------------------------show_parse_info--------------------------------------
2333 void Parse::show_parse_info() {
2334   InlineTree* ilt = NULL;
2335   if (C->ilt() != NULL) {
2336     JVMState* caller_jvms = is_osr_parse() ? caller()->caller() : caller();
2337     ilt = InlineTree::find_subtree_from_root(C->ilt(), caller_jvms, method());
2338   }
2339   if (PrintCompilation && Verbose) {
2340     if (depth() == 1) {
2341       if( ilt->count_inlines() ) {
2342         tty->print("    __inlined %d (%d bytes)", ilt->count_inlines(),
2343                      ilt->count_inline_bcs());
2344         tty->cr();
2345       }
2346     } else {
2347       if (method()->is_synchronized())         tty->print("s");
2348       if (method()->has_exception_handlers())  tty->print("!");
2349       // Check this is not the final compiled version
2350       if (C->trap_can_recompile()) {
2351         tty->print("-");
2352       } else {
2353         tty->print(" ");
2354       }
2355       method()->print_short_name();
2356       if (is_osr_parse()) {
2357         tty->print(" @ %d", osr_bci());
2358       }
2359       tty->print(" (%d bytes)",method()->code_size());
2360       if (ilt->count_inlines()) {
2361         tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2362                    ilt->count_inline_bcs());
2363       }
2364       tty->cr();
2365     }
2366   }
2367   if (PrintOpto && (depth() == 1 || PrintOptoInlining)) {
2368     // Print that we succeeded; suppress this message on the first osr parse.
2369 
2370     if (method()->is_synchronized())         tty->print("s");
2371     if (method()->has_exception_handlers())  tty->print("!");
2372     // Check this is not the final compiled version
2373     if (C->trap_can_recompile() && depth() == 1) {
2374       tty->print("-");
2375     } else {
2376       tty->print(" ");
2377     }
2378     if( depth() != 1 ) { tty->print("   "); }  // missing compile count
2379     for (int i = 1; i < depth(); ++i) { tty->print("  "); }
2380     method()->print_short_name();
2381     if (is_osr_parse()) {
2382       tty->print(" @ %d", osr_bci());
2383     }
2384     if (ilt->caller_bci() != -1) {
2385       tty->print(" @ %d", ilt->caller_bci());
2386     }
2387     tty->print(" (%d bytes)",method()->code_size());
2388     if (ilt->count_inlines()) {
2389       tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2390                  ilt->count_inline_bcs());
2391     }
2392     tty->cr();
2393   }
2394 }
2395 
2396 
2397 //------------------------------dump-------------------------------------------
2398 // Dump information associated with the bytecodes of current _method
2399 void Parse::dump() {
2400   if( method() != NULL ) {
2401     // Iterate over bytecodes
2402     ciBytecodeStream iter(method());
2403     for( Bytecodes::Code bc = iter.next(); bc != ciBytecodeStream::EOBC() ; bc = iter.next() ) {
2404       dump_bci( iter.cur_bci() );
2405       tty->cr();
2406     }
2407   }
2408 }
2409 
2410 // Dump information associated with a byte code index, 'bci'
2411 void Parse::dump_bci(int bci) {
2412   // Output info on merge-points, cloning, and within _jsr..._ret
2413   // NYI
2414   tty->print(" bci:%d", bci);
2415 }
2416 
2417 #endif