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