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