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