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