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