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