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