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