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