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