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