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