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