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