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