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