1 /*
   2  * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "compiler/compileLog.hpp"
  27 #include "gc/shared/collectedHeap.inline.hpp"
  28 #include "libadt/vectset.hpp"
  29 #include "memory/universe.hpp"
  30 #include "opto/addnode.hpp"
  31 #include "opto/arraycopynode.hpp"
  32 #include "opto/callnode.hpp"
  33 #include "opto/castnode.hpp"
  34 #include "opto/cfgnode.hpp"
  35 #include "opto/compile.hpp"
  36 #include "opto/convertnode.hpp"
  37 #include "opto/graphKit.hpp"
  38 #include "opto/intrinsicnode.hpp"
  39 #include "opto/locknode.hpp"
  40 #include "opto/loopnode.hpp"
  41 #include "opto/macro.hpp"
  42 #include "opto/memnode.hpp"
  43 #include "opto/narrowptrnode.hpp"
  44 #include "opto/node.hpp"
  45 #include "opto/opaquenode.hpp"
  46 #include "opto/phaseX.hpp"
  47 #include "opto/rootnode.hpp"
  48 #include "opto/runtime.hpp"
  49 #include "opto/subnode.hpp"
  50 #include "opto/subtypenode.hpp"
  51 #include "opto/type.hpp"
  52 #include "runtime/sharedRuntime.hpp"
  53 #include "utilities/macros.hpp"
  54 #include "utilities/powerOfTwo.hpp"
  55 #if INCLUDE_G1GC
  56 #include "gc/g1/g1ThreadLocalData.hpp"
  57 #endif // INCLUDE_G1GC
  58 #if INCLUDE_SHENANDOAHGC
  59 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  60 #endif
  61 
  62 
  63 //
  64 // Replace any references to "oldref" in inputs to "use" with "newref".
  65 // Returns the number of replacements made.
  66 //
  67 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
  68   int nreplacements = 0;
  69   uint req = use->req();
  70   for (uint j = 0; j < use->len(); j++) {
  71     Node *uin = use->in(j);
  72     if (uin == oldref) {
  73       if (j < req)
  74         use->set_req(j, newref);
  75       else
  76         use->set_prec(j, newref);
  77       nreplacements++;
  78     } else if (j >= req && uin == NULL) {
  79       break;
  80     }
  81   }
  82   return nreplacements;
  83 }
  84 
  85 void PhaseMacroExpand::migrate_outs(Node *old, Node *target) {
  86   assert(old != NULL, "sanity");
  87   for (DUIterator_Fast imax, i = old->fast_outs(imax); i < imax; i++) {
  88     Node* use = old->fast_out(i);
  89     _igvn.rehash_node_delayed(use);
  90     imax -= replace_input(use, old, target);
  91     // back up iterator
  92     --i;
  93   }
  94   assert(old->outcnt() == 0, "all uses must be deleted");
  95 }
  96 
  97 void PhaseMacroExpand::copy_call_debug_info(CallNode *oldcall, CallNode * newcall) {
  98   // Copy debug information and adjust JVMState information
  99   uint old_dbg_start = oldcall->tf()->domain()->cnt();
 100   uint new_dbg_start = newcall->tf()->domain()->cnt();
 101   int jvms_adj  = new_dbg_start - old_dbg_start;
 102   assert (new_dbg_start == newcall->req(), "argument count mismatch");
 103 
 104   // SafePointScalarObject node could be referenced several times in debug info.
 105   // Use Dict to record cloned nodes.
 106   Dict* sosn_map = new Dict(cmpkey,hashkey);
 107   for (uint i = old_dbg_start; i < oldcall->req(); i++) {
 108     Node* old_in = oldcall->in(i);
 109     // Clone old SafePointScalarObjectNodes, adjusting their field contents.
 110     if (old_in != NULL && old_in->is_SafePointScalarObject()) {
 111       SafePointScalarObjectNode* old_sosn = old_in->as_SafePointScalarObject();
 112       uint old_unique = C->unique();
 113       Node* new_in = old_sosn->clone(sosn_map);
 114       if (old_unique != C->unique()) { // New node?
 115         new_in->set_req(0, C->root()); // reset control edge
 116         new_in = transform_later(new_in); // Register new node.
 117       }
 118       old_in = new_in;
 119     }
 120     newcall->add_req(old_in);
 121   }
 122 
 123   // JVMS may be shared so clone it before we modify it
 124   newcall->set_jvms(oldcall->jvms() != NULL ? oldcall->jvms()->clone_deep(C) : NULL);
 125   for (JVMState *jvms = newcall->jvms(); jvms != NULL; jvms = jvms->caller()) {
 126     jvms->set_map(newcall);
 127     jvms->set_locoff(jvms->locoff()+jvms_adj);
 128     jvms->set_stkoff(jvms->stkoff()+jvms_adj);
 129     jvms->set_monoff(jvms->monoff()+jvms_adj);
 130     jvms->set_scloff(jvms->scloff()+jvms_adj);
 131     jvms->set_endoff(jvms->endoff()+jvms_adj);
 132   }
 133 }
 134 
 135 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word, int mask, int bits, bool return_fast_path) {
 136   Node* cmp;
 137   if (mask != 0) {
 138     Node* and_node = transform_later(new AndXNode(word, MakeConX(mask)));
 139     cmp = transform_later(new CmpXNode(and_node, MakeConX(bits)));
 140   } else {
 141     cmp = word;
 142   }
 143   Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
 144   IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
 145   transform_later(iff);
 146 
 147   // Fast path taken.
 148   Node *fast_taken = transform_later(new IfFalseNode(iff));
 149 
 150   // Fast path not-taken, i.e. slow path
 151   Node *slow_taken = transform_later(new IfTrueNode(iff));
 152 
 153   if (return_fast_path) {
 154     region->init_req(edge, slow_taken); // Capture slow-control
 155     return fast_taken;
 156   } else {
 157     region->init_req(edge, fast_taken); // Capture fast-control
 158     return slow_taken;
 159   }
 160 }
 161 
 162 //--------------------copy_predefined_input_for_runtime_call--------------------
 163 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
 164   // Set fixed predefined input arguments
 165   call->init_req( TypeFunc::Control, ctrl );
 166   call->init_req( TypeFunc::I_O    , oldcall->in( TypeFunc::I_O) );
 167   call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ?????
 168   call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) );
 169   call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) );
 170 }
 171 
 172 //------------------------------make_slow_call---------------------------------
 173 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type,
 174                                            address slow_call, const char* leaf_name, Node* slow_path,
 175                                            Node* parm0, Node* parm1, Node* parm2) {
 176 
 177   // Slow-path call
 178  CallNode *call = leaf_name
 179    ? (CallNode*)new CallLeafNode      ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
 180    : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), oldcall->jvms()->bci(), TypeRawPtr::BOTTOM );
 181 
 182   // Slow path call has no side-effects, uses few values
 183   copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
 184   if (parm0 != NULL)  call->init_req(TypeFunc::Parms+0, parm0);
 185   if (parm1 != NULL)  call->init_req(TypeFunc::Parms+1, parm1);
 186   if (parm2 != NULL)  call->init_req(TypeFunc::Parms+2, parm2);
 187   copy_call_debug_info(oldcall, call);
 188   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
 189   _igvn.replace_node(oldcall, call);
 190   transform_later(call);
 191 
 192   return call;
 193 }
 194 
 195 void PhaseMacroExpand::extract_call_projections(CallNode *call) {
 196   _fallthroughproj = NULL;
 197   _fallthroughcatchproj = NULL;
 198   _ioproj_fallthrough = NULL;
 199   _ioproj_catchall = NULL;
 200   _catchallcatchproj = NULL;
 201   _memproj_fallthrough = NULL;
 202   _memproj_catchall = NULL;
 203   _resproj = NULL;
 204   for (DUIterator_Fast imax, i = call->fast_outs(imax); i < imax; i++) {
 205     ProjNode *pn = call->fast_out(i)->as_Proj();
 206     switch (pn->_con) {
 207       case TypeFunc::Control:
 208       {
 209         // For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
 210         _fallthroughproj = pn;
 211         DUIterator_Fast jmax, j = pn->fast_outs(jmax);
 212         const Node *cn = pn->fast_out(j);
 213         if (cn->is_Catch()) {
 214           ProjNode *cpn = NULL;
 215           for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
 216             cpn = cn->fast_out(k)->as_Proj();
 217             assert(cpn->is_CatchProj(), "must be a CatchProjNode");
 218             if (cpn->_con == CatchProjNode::fall_through_index)
 219               _fallthroughcatchproj = cpn;
 220             else {
 221               assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
 222               _catchallcatchproj = cpn;
 223             }
 224           }
 225         }
 226         break;
 227       }
 228       case TypeFunc::I_O:
 229         if (pn->_is_io_use)
 230           _ioproj_catchall = pn;
 231         else
 232           _ioproj_fallthrough = pn;
 233         break;
 234       case TypeFunc::Memory:
 235         if (pn->_is_io_use)
 236           _memproj_catchall = pn;
 237         else
 238           _memproj_fallthrough = pn;
 239         break;
 240       case TypeFunc::Parms:
 241         _resproj = pn;
 242         break;
 243       default:
 244         assert(false, "unexpected projection from allocation node.");
 245     }
 246   }
 247 
 248 }
 249 
 250 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) {
 251   BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 252   bs->eliminate_gc_barrier(this, p2x);
 253 }
 254 
 255 // Search for a memory operation for the specified memory slice.
 256 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
 257   Node *orig_mem = mem;
 258   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 259   const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
 260   while (true) {
 261     if (mem == alloc_mem || mem == start_mem ) {
 262       return mem;  // hit one of our sentinels
 263     } else if (mem->is_MergeMem()) {
 264       mem = mem->as_MergeMem()->memory_at(alias_idx);
 265     } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
 266       Node *in = mem->in(0);
 267       // we can safely skip over safepoints, calls, locks and membars because we
 268       // already know that the object is safe to eliminate.
 269       if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
 270         return in;
 271       } else if (in->is_Call()) {
 272         CallNode *call = in->as_Call();
 273         if (call->may_modify(tinst, phase)) {
 274           assert(call->is_ArrayCopy(), "ArrayCopy is the only call node that doesn't make allocation escape");
 275           if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
 276             return in;
 277           }
 278         }
 279         mem = in->in(TypeFunc::Memory);
 280       } else if (in->is_MemBar()) {
 281         ArrayCopyNode* ac = NULL;
 282         if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
 283           assert(ac != NULL && ac->is_clonebasic(), "Only basic clone is a non escaping clone");
 284           return ac;
 285         }
 286         mem = in->in(TypeFunc::Memory);
 287       } else {
 288         assert(false, "unexpected projection");
 289       }
 290     } else if (mem->is_Store()) {
 291       const TypePtr* atype = mem->as_Store()->adr_type();
 292       int adr_idx = phase->C->get_alias_index(atype);
 293       if (adr_idx == alias_idx) {
 294         assert(atype->isa_oopptr(), "address type must be oopptr");
 295         int adr_offset = atype->offset();
 296         uint adr_iid = atype->is_oopptr()->instance_id();
 297         // Array elements references have the same alias_idx
 298         // but different offset and different instance_id.
 299         if (adr_offset == offset && adr_iid == alloc->_idx)
 300           return mem;
 301       } else {
 302         assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
 303       }
 304       mem = mem->in(MemNode::Memory);
 305     } else if (mem->is_ClearArray()) {
 306       if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
 307         // Can not bypass initialization of the instance
 308         // we are looking.
 309         debug_only(intptr_t offset;)
 310         assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
 311         InitializeNode* init = alloc->as_Allocate()->initialization();
 312         // We are looking for stored value, return Initialize node
 313         // or memory edge from Allocate node.
 314         if (init != NULL)
 315           return init;
 316         else
 317           return alloc->in(TypeFunc::Memory); // It will produce zero value (see callers).
 318       }
 319       // Otherwise skip it (the call updated 'mem' value).
 320     } else if (mem->Opcode() == Op_SCMemProj) {
 321       mem = mem->in(0);
 322       Node* adr = NULL;
 323       if (mem->is_LoadStore()) {
 324         adr = mem->in(MemNode::Address);
 325       } else {
 326         assert(mem->Opcode() == Op_EncodeISOArray ||
 327                mem->Opcode() == Op_StrCompressedCopy, "sanity");
 328         adr = mem->in(3); // Destination array
 329       }
 330       const TypePtr* atype = adr->bottom_type()->is_ptr();
 331       int adr_idx = phase->C->get_alias_index(atype);
 332       if (adr_idx == alias_idx) {
 333         DEBUG_ONLY(mem->dump();)
 334         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 335         return NULL;
 336       }
 337       mem = mem->in(MemNode::Memory);
 338    } else if (mem->Opcode() == Op_StrInflatedCopy) {
 339       Node* adr = mem->in(3); // Destination array
 340       const TypePtr* atype = adr->bottom_type()->is_ptr();
 341       int adr_idx = phase->C->get_alias_index(atype);
 342       if (adr_idx == alias_idx) {
 343         DEBUG_ONLY(mem->dump();)
 344         assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
 345         return NULL;
 346       }
 347       mem = mem->in(MemNode::Memory);
 348     } else {
 349       return mem;
 350     }
 351     assert(mem != orig_mem, "dead memory loop");
 352   }
 353 }
 354 
 355 // Generate loads from source of the arraycopy for fields of
 356 // destination needed at a deoptimization point
 357 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
 358   BasicType bt = ft;
 359   const Type *type = ftype;
 360   if (ft == T_NARROWOOP) {
 361     bt = T_OBJECT;
 362     type = ftype->make_oopptr();
 363   }
 364   Node* res = NULL;
 365   if (ac->is_clonebasic()) {
 366     assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
 367     Node* base = ac->in(ArrayCopyNode::Src);
 368     Node* adr = _igvn.transform(new AddPNode(base, base, MakeConX(offset)));
 369     const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
 370     MergeMemNode* mergemen = MergeMemNode::make(mem);
 371     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 372     res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 373   } else {
 374     if (ac->modifies(offset, offset, &_igvn, true)) {
 375       assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
 376       uint shift = exact_log2(type2aelembytes(bt));
 377       Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
 378       Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
 379       const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
 380       const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
 381 
 382       Node* adr = NULL;
 383       const TypePtr* adr_type = NULL;
 384       if (src_pos_t->is_con() && dest_pos_t->is_con()) {
 385         intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
 386         Node* base = ac->in(ArrayCopyNode::Src);
 387         adr = _igvn.transform(new AddPNode(base, base, MakeConX(off)));
 388         adr_type = _igvn.type(base)->is_ptr()->add_offset(off);
 389         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 390           // Don't emit a new load from src if src == dst but try to get the value from memory instead
 391           return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type->isa_oopptr(), alloc);
 392         }
 393       } else {
 394         Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 395 #ifdef _LP64
 396         diff = _igvn.transform(new ConvI2LNode(diff));
 397 #endif
 398         diff = _igvn.transform(new LShiftXNode(diff, intcon(shift)));
 399 
 400         Node* off = _igvn.transform(new AddXNode(MakeConX(offset), diff));
 401         Node* base = ac->in(ArrayCopyNode::Src);
 402         adr = _igvn.transform(new AddPNode(base, base, off));
 403         adr_type = _igvn.type(base)->is_ptr()->add_offset(Type::OffsetBot);
 404         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 405           // Non constant offset in the array: we can't statically
 406           // determine the value
 407           return NULL;
 408         }
 409       }
 410       MergeMemNode* mergemen = MergeMemNode::make(mem);
 411       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 412       res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 413     }
 414   }
 415   if (res != NULL) {
 416     if (ftype->isa_narrowoop()) {
 417       // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
 418       res = _igvn.transform(new EncodePNode(res, ftype));
 419     }
 420     return res;
 421   }
 422   return NULL;
 423 }
 424 
 425 //
 426 // Given a Memory Phi, compute a value Phi containing the values from stores
 427 // on the input paths.
 428 // Note: this function is recursive, its depth is limited by the "level" argument
 429 // Returns the computed Phi, or NULL if it cannot compute it.
 430 Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, AllocateNode *alloc, Node_Stack *value_phis, int level) {
 431   assert(mem->is_Phi(), "sanity");
 432   int alias_idx = C->get_alias_index(adr_t);
 433   int offset = adr_t->offset();
 434   int instance_id = adr_t->instance_id();
 435 
 436   // Check if an appropriate value phi already exists.
 437   Node* region = mem->in(0);
 438   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
 439     Node* phi = region->fast_out(k);
 440     if (phi->is_Phi() && phi != mem &&
 441         phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
 442       return phi;
 443     }
 444   }
 445   // Check if an appropriate new value phi already exists.
 446   Node* new_phi = value_phis->find(mem->_idx);
 447   if (new_phi != NULL)
 448     return new_phi;
 449 
 450   if (level <= 0) {
 451     return NULL; // Give up: phi tree too deep
 452   }
 453   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 454   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 455 
 456   uint length = mem->req();
 457   GrowableArray <Node *> values(length, length, NULL);
 458 
 459   // create a new Phi for the value
 460   PhiNode *phi = new PhiNode(mem->in(0), phi_type, NULL, mem->_idx, instance_id, alias_idx, offset);
 461   transform_later(phi);
 462   value_phis->push(phi, mem->_idx);
 463 
 464   for (uint j = 1; j < length; j++) {
 465     Node *in = mem->in(j);
 466     if (in == NULL || in->is_top()) {
 467       values.at_put(j, in);
 468     } else  {
 469       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
 470       if (val == start_mem || val == alloc_mem) {
 471         // hit a sentinel, return appropriate 0 value
 472         values.at_put(j, _igvn.zerocon(ft));
 473         continue;
 474       }
 475       if (val->is_Initialize()) {
 476         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 477       }
 478       if (val == NULL) {
 479         return NULL;  // can't find a value on this path
 480       }
 481       if (val == mem) {
 482         values.at_put(j, mem);
 483       } else if (val->is_Store()) {
 484         Node* n = val->in(MemNode::ValueIn);
 485         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 486         n = bs->step_over_gc_barrier(n);
 487         values.at_put(j, n);
 488       } else if(val->is_Proj() && val->in(0) == alloc) {
 489         values.at_put(j, _igvn.zerocon(ft));
 490       } else if (val->is_Phi()) {
 491         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 492         if (val == NULL) {
 493           return NULL;
 494         }
 495         values.at_put(j, val);
 496       } else if (val->Opcode() == Op_SCMemProj) {
 497         assert(val->in(0)->is_LoadStore() ||
 498                val->in(0)->Opcode() == Op_EncodeISOArray ||
 499                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
 500         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 501         return NULL;
 502       } else if (val->is_ArrayCopy()) {
 503         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
 504         if (res == NULL) {
 505           return NULL;
 506         }
 507         values.at_put(j, res);
 508       } else {
 509 #ifdef ASSERT
 510         val->dump();
 511         assert(false, "unknown node on this path");
 512 #endif
 513         return NULL;  // unknown node on this path
 514       }
 515     }
 516   }
 517   // Set Phi's inputs
 518   for (uint j = 1; j < length; j++) {
 519     if (values.at(j) == mem) {
 520       phi->init_req(j, phi);
 521     } else {
 522       phi->init_req(j, values.at(j));
 523     }
 524   }
 525   return phi;
 526 }
 527 
 528 // Search the last value stored into the object's field.
 529 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
 530   assert(adr_t->is_known_instance_field(), "instance required");
 531   int instance_id = adr_t->instance_id();
 532   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 533 
 534   int alias_idx = C->get_alias_index(adr_t);
 535   int offset = adr_t->offset();
 536   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 537   Node *alloc_ctrl = alloc->in(TypeFunc::Control);
 538   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 539   VectorSet visited;
 540 
 541   bool done = sfpt_mem == alloc_mem;
 542   Node *mem = sfpt_mem;
 543   while (!done) {
 544     if (visited.test_set(mem->_idx)) {
 545       return NULL;  // found a loop, give up
 546     }
 547     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 548     if (mem == start_mem || mem == alloc_mem) {
 549       done = true;  // hit a sentinel, return appropriate 0 value
 550     } else if (mem->is_Initialize()) {
 551       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 552       if (mem == NULL) {
 553         done = true; // Something go wrong.
 554       } else if (mem->is_Store()) {
 555         const TypePtr* atype = mem->as_Store()->adr_type();
 556         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 557         done = true;
 558       }
 559     } else if (mem->is_Store()) {
 560       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 561       assert(atype != NULL, "address type must be oopptr");
 562       assert(C->get_alias_index(atype) == alias_idx &&
 563              atype->is_known_instance_field() && atype->offset() == offset &&
 564              atype->instance_id() == instance_id, "store is correct memory slice");
 565       done = true;
 566     } else if (mem->is_Phi()) {
 567       // try to find a phi's unique input
 568       Node *unique_input = NULL;
 569       Node *top = C->top();
 570       for (uint i = 1; i < mem->req(); i++) {
 571         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 572         if (n == NULL || n == top || n == mem) {
 573           continue;
 574         } else if (unique_input == NULL) {
 575           unique_input = n;
 576         } else if (unique_input != n) {
 577           unique_input = top;
 578           break;
 579         }
 580       }
 581       if (unique_input != NULL && unique_input != top) {
 582         mem = unique_input;
 583       } else {
 584         done = true;
 585       }
 586     } else if (mem->is_ArrayCopy()) {
 587       done = true;
 588     } else {
 589       assert(false, "unexpected node");
 590     }
 591   }
 592   if (mem != NULL) {
 593     if (mem == start_mem || mem == alloc_mem) {
 594       // hit a sentinel, return appropriate 0 value
 595       return _igvn.zerocon(ft);
 596     } else if (mem->is_Store()) {
 597       Node* n = mem->in(MemNode::ValueIn);
 598       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 599       n = bs->step_over_gc_barrier(n);
 600       return n;
 601     } else if (mem->is_Phi()) {
 602       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 603       Node_Stack value_phis(8);
 604       Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 605       if (phi != NULL) {
 606         return phi;
 607       } else {
 608         // Kill all new Phis
 609         while(value_phis.is_nonempty()) {
 610           Node* n = value_phis.node();
 611           _igvn.replace_node(n, C->top());
 612           value_phis.pop();
 613         }
 614       }
 615     } else if (mem->is_ArrayCopy()) {
 616       Node* ctl = mem->in(0);
 617       Node* m = mem->in(TypeFunc::Memory);
 618       if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
 619         // pin the loads in the uncommon trap path
 620         ctl = sfpt_ctl;
 621         m = sfpt_mem;
 622       }
 623       return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
 624     }
 625   }
 626   // Something go wrong.
 627   return NULL;
 628 }
 629 
 630 // Check the possibility of scalar replacement.
 631 bool PhaseMacroExpand::can_eliminate_allocation(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 632   //  Scan the uses of the allocation to check for anything that would
 633   //  prevent us from eliminating it.
 634   NOT_PRODUCT( const char* fail_eliminate = NULL; )
 635   DEBUG_ONLY( Node* disq_node = NULL; )
 636   bool  can_eliminate = true;
 637 
 638   Node* res = alloc->result_cast();
 639   const TypeOopPtr* res_type = NULL;
 640   if (res == NULL) {
 641     // All users were eliminated.
 642   } else if (!res->is_CheckCastPP()) {
 643     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 644     can_eliminate = false;
 645   } else {
 646     res_type = _igvn.type(res)->isa_oopptr();
 647     if (res_type == NULL) {
 648       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
 649       can_eliminate = false;
 650     } else if (res_type->isa_aryptr()) {
 651       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 652       if (length < 0) {
 653         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 654         can_eliminate = false;
 655       }
 656     }
 657   }
 658 
 659   if (can_eliminate && res != NULL) {
 660     for (DUIterator_Fast jmax, j = res->fast_outs(jmax);
 661                                j < jmax && can_eliminate; j++) {
 662       Node* use = res->fast_out(j);
 663 
 664       if (use->is_AddP()) {
 665         const TypePtr* addp_type = _igvn.type(use)->is_ptr();
 666         int offset = addp_type->offset();
 667 
 668         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 669           NOT_PRODUCT(fail_eliminate = "Undefined field referrence";)
 670           can_eliminate = false;
 671           break;
 672         }
 673         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 674                                    k < kmax && can_eliminate; k++) {
 675           Node* n = use->fast_out(k);
 676           if (!n->is_Store() && n->Opcode() != Op_CastP2X
 677               SHENANDOAHGC_ONLY(&& (!UseShenandoahGC || !ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(n))) ) {
 678             DEBUG_ONLY(disq_node = n;)
 679             if (n->is_Load() || n->is_LoadStore()) {
 680               NOT_PRODUCT(fail_eliminate = "Field load";)
 681             } else {
 682               NOT_PRODUCT(fail_eliminate = "Not store field referrence";)
 683             }
 684             can_eliminate = false;
 685           }
 686         }
 687       } else if (use->is_ArrayCopy() &&
 688                  (use->as_ArrayCopy()->is_clonebasic() ||
 689                   use->as_ArrayCopy()->is_arraycopy_validated() ||
 690                   use->as_ArrayCopy()->is_copyof_validated() ||
 691                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
 692                  use->in(ArrayCopyNode::Dest) == res) {
 693         // ok to eliminate
 694       } else if (use->is_SafePoint()) {
 695         SafePointNode* sfpt = use->as_SafePoint();
 696         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 697           // Object is passed as argument.
 698           DEBUG_ONLY(disq_node = use;)
 699           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 700           can_eliminate = false;
 701         }
 702         Node* sfptMem = sfpt->memory();
 703         if (sfptMem == NULL || sfptMem->is_top()) {
 704           DEBUG_ONLY(disq_node = use;)
 705           NOT_PRODUCT(fail_eliminate = "NULL or TOP memory";)
 706           can_eliminate = false;
 707         } else {
 708           safepoints.append_if_missing(sfpt);
 709         }
 710       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 711         if (use->is_Phi()) {
 712           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 713             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 714           } else {
 715             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 716           }
 717           DEBUG_ONLY(disq_node = use;)
 718         } else {
 719           if (use->Opcode() == Op_Return) {
 720             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 721           }else {
 722             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 723           }
 724           DEBUG_ONLY(disq_node = use;)
 725         }
 726         can_eliminate = false;
 727       }
 728     }
 729   }
 730 
 731 #ifndef PRODUCT
 732   if (PrintEliminateAllocations) {
 733     if (can_eliminate) {
 734       tty->print("Scalar ");
 735       if (res == NULL)
 736         alloc->dump();
 737       else
 738         res->dump();
 739     } else if (alloc->_is_scalar_replaceable) {
 740       tty->print("NotScalar (%s)", fail_eliminate);
 741       if (res == NULL)
 742         alloc->dump();
 743       else
 744         res->dump();
 745 #ifdef ASSERT
 746       if (disq_node != NULL) {
 747           tty->print("  >>>> ");
 748           disq_node->dump();
 749       }
 750 #endif /*ASSERT*/
 751     }
 752   }
 753 #endif
 754   return can_eliminate;
 755 }
 756 
 757 // Do scalar replacement.
 758 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 759   GrowableArray <SafePointNode *> safepoints_done;
 760 
 761   ciKlass* klass = NULL;
 762   ciInstanceKlass* iklass = NULL;
 763   int nfields = 0;
 764   int array_base = 0;
 765   int element_size = 0;
 766   BasicType basic_elem_type = T_ILLEGAL;
 767   ciType* elem_type = NULL;
 768 
 769   Node* res = alloc->result_cast();
 770   assert(res == NULL || res->is_CheckCastPP(), "unexpected AllocateNode result");
 771   const TypeOopPtr* res_type = NULL;
 772   if (res != NULL) { // Could be NULL when there are no users
 773     res_type = _igvn.type(res)->isa_oopptr();
 774   }
 775 
 776   if (res != NULL) {
 777     klass = res_type->klass();
 778     if (res_type->isa_instptr()) {
 779       // find the fields of the class which will be needed for safepoint debug information
 780       assert(klass->is_instance_klass(), "must be an instance klass.");
 781       iklass = klass->as_instance_klass();
 782       nfields = iklass->nof_nonstatic_fields();
 783     } else {
 784       // find the array's elements which will be needed for safepoint debug information
 785       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 786       assert(klass->is_array_klass() && nfields >= 0, "must be an array klass.");
 787       elem_type = klass->as_array_klass()->element_type();
 788       basic_elem_type = elem_type->basic_type();
 789       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 790       element_size = type2aelembytes(basic_elem_type);
 791     }
 792   }
 793   //
 794   // Process the safepoint uses
 795   //
 796   while (safepoints.length() > 0) {
 797     SafePointNode* sfpt = safepoints.pop();
 798     Node* mem = sfpt->memory();
 799     Node* ctl = sfpt->control();
 800     assert(sfpt->jvms() != NULL, "missed JVMS");
 801     // Fields of scalar objs are referenced only at the end
 802     // of regular debuginfo at the last (youngest) JVMS.
 803     // Record relative start index.
 804     uint first_ind = (sfpt->req() - sfpt->jvms()->scloff());
 805     SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type,
 806 #ifdef ASSERT
 807                                                  alloc,
 808 #endif
 809                                                  first_ind, nfields);
 810     sobj->init_req(0, C->root());
 811     transform_later(sobj);
 812 
 813     // Scan object's fields adding an input to the safepoint for each field.
 814     for (int j = 0; j < nfields; j++) {
 815       intptr_t offset;
 816       ciField* field = NULL;
 817       if (iklass != NULL) {
 818         field = iklass->nonstatic_field_at(j);
 819         offset = field->offset();
 820         elem_type = field->type();
 821         basic_elem_type = field->layout_type();
 822       } else {
 823         offset = array_base + j * (intptr_t)element_size;
 824       }
 825 
 826       const Type *field_type;
 827       // The next code is taken from Parse::do_get_xxx().
 828       if (is_reference_type(basic_elem_type)) {
 829         if (!elem_type->is_loaded()) {
 830           field_type = TypeInstPtr::BOTTOM;
 831         } else if (field != NULL && field->is_static_constant()) {
 832           // This can happen if the constant oop is non-perm.
 833           ciObject* con = field->constant_value().as_object();
 834           // Do not "join" in the previous type; it doesn't add value,
 835           // and may yield a vacuous result if the field is of interface type.
 836           field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 837           assert(field_type != NULL, "field singleton type must be consistent");
 838         } else {
 839           field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 840         }
 841         if (UseCompressedOops) {
 842           field_type = field_type->make_narrowoop();
 843           basic_elem_type = T_NARROWOOP;
 844         }
 845       } else {
 846         field_type = Type::get_const_basic_type(basic_elem_type);
 847       }
 848 
 849       const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 850 
 851       Node *field_val = value_from_mem(mem, ctl, basic_elem_type, field_type, field_addr_type, alloc);
 852       if (field_val == NULL) {
 853         // We weren't able to find a value for this field,
 854         // give up on eliminating this allocation.
 855 
 856         // Remove any extra entries we added to the safepoint.
 857         uint last = sfpt->req() - 1;
 858         for (int k = 0;  k < j; k++) {
 859           sfpt->del_req(last--);
 860         }
 861         _igvn._worklist.push(sfpt);
 862         // rollback processed safepoints
 863         while (safepoints_done.length() > 0) {
 864           SafePointNode* sfpt_done = safepoints_done.pop();
 865           // remove any extra entries we added to the safepoint
 866           last = sfpt_done->req() - 1;
 867           for (int k = 0;  k < nfields; k++) {
 868             sfpt_done->del_req(last--);
 869           }
 870           JVMState *jvms = sfpt_done->jvms();
 871           jvms->set_endoff(sfpt_done->req());
 872           // Now make a pass over the debug information replacing any references
 873           // to SafePointScalarObjectNode with the allocated object.
 874           int start = jvms->debug_start();
 875           int end   = jvms->debug_end();
 876           for (int i = start; i < end; i++) {
 877             if (sfpt_done->in(i)->is_SafePointScalarObject()) {
 878               SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
 879               if (scobj->first_index(jvms) == sfpt_done->req() &&
 880                   scobj->n_fields() == (uint)nfields) {
 881                 assert(scobj->alloc() == alloc, "sanity");
 882                 sfpt_done->set_req(i, res);
 883               }
 884             }
 885           }
 886           _igvn._worklist.push(sfpt_done);
 887         }
 888 #ifndef PRODUCT
 889         if (PrintEliminateAllocations) {
 890           if (field != NULL) {
 891             tty->print("=== At SafePoint node %d can't find value of Field: ",
 892                        sfpt->_idx);
 893             field->print();
 894             int field_idx = C->get_alias_index(field_addr_type);
 895             tty->print(" (alias_idx=%d)", field_idx);
 896           } else { // Array's element
 897             tty->print("=== At SafePoint node %d can't find value of array element [%d]",
 898                        sfpt->_idx, j);
 899           }
 900           tty->print(", which prevents elimination of: ");
 901           if (res == NULL)
 902             alloc->dump();
 903           else
 904             res->dump();
 905         }
 906 #endif
 907         return false;
 908       }
 909       if (UseCompressedOops && field_type->isa_narrowoop()) {
 910         // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 911         // to be able scalar replace the allocation.
 912         if (field_val->is_EncodeP()) {
 913           field_val = field_val->in(1);
 914         } else {
 915           field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 916         }
 917       }
 918       sfpt->add_req(field_val);
 919     }
 920     JVMState *jvms = sfpt->jvms();
 921     jvms->set_endoff(sfpt->req());
 922     // Now make a pass over the debug information replacing any references
 923     // to the allocated object with "sobj"
 924     int start = jvms->debug_start();
 925     int end   = jvms->debug_end();
 926     sfpt->replace_edges_in_range(res, sobj, start, end);
 927     _igvn._worklist.push(sfpt);
 928     safepoints_done.append_if_missing(sfpt); // keep it for rollback
 929   }
 930   return true;
 931 }
 932 
 933 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
 934   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
 935   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
 936   if (ctl_proj != NULL) {
 937     igvn.replace_node(ctl_proj, n->in(0));
 938   }
 939   if (mem_proj != NULL) {
 940     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
 941   }
 942 }
 943 
 944 // Process users of eliminated allocation.
 945 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc) {
 946   Node* res = alloc->result_cast();
 947   if (res != NULL) {
 948     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
 949       Node *use = res->last_out(j);
 950       uint oc1 = res->outcnt();
 951 
 952       if (use->is_AddP()) {
 953         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
 954           Node *n = use->last_out(k);
 955           uint oc2 = use->outcnt();
 956           if (n->is_Store()) {
 957 #ifdef ASSERT
 958             // Verify that there is no dependent MemBarVolatile nodes,
 959             // they should be removed during IGVN, see MemBarNode::Ideal().
 960             for (DUIterator_Fast pmax, p = n->fast_outs(pmax);
 961                                        p < pmax; p++) {
 962               Node* mb = n->fast_out(p);
 963               assert(mb->is_Initialize() || !mb->is_MemBar() ||
 964                      mb->req() <= MemBarNode::Precedent ||
 965                      mb->in(MemBarNode::Precedent) != n,
 966                      "MemBarVolatile should be eliminated for non-escaping object");
 967             }
 968 #endif
 969             _igvn.replace_node(n, n->in(MemNode::Memory));
 970           } else {
 971             eliminate_gc_barrier(n);
 972           }
 973           k -= (oc2 - use->outcnt());
 974         }
 975         _igvn.remove_dead_node(use);
 976       } else if (use->is_ArrayCopy()) {
 977         // Disconnect ArrayCopy node
 978         ArrayCopyNode* ac = use->as_ArrayCopy();
 979         if (ac->is_clonebasic()) {
 980           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
 981           disconnect_projections(ac, _igvn);
 982           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
 983           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
 984           disconnect_projections(membar_before->as_MemBar(), _igvn);
 985           if (membar_after->is_MemBar()) {
 986             disconnect_projections(membar_after->as_MemBar(), _igvn);
 987           }
 988         } else {
 989           assert(ac->is_arraycopy_validated() ||
 990                  ac->is_copyof_validated() ||
 991                  ac->is_copyofrange_validated(), "unsupported");
 992           CallProjections callprojs;
 993           ac->extract_projections(&callprojs, true);
 994 
 995           _igvn.replace_node(callprojs.fallthrough_ioproj, ac->in(TypeFunc::I_O));
 996           _igvn.replace_node(callprojs.fallthrough_memproj, ac->in(TypeFunc::Memory));
 997           _igvn.replace_node(callprojs.fallthrough_catchproj, ac->in(TypeFunc::Control));
 998 
 999           // Set control to top. IGVN will remove the remaining projections
1000           ac->set_req(0, top());
1001           ac->replace_edge(res, top());
1002 
1003           // Disconnect src right away: it can help find new
1004           // opportunities for allocation elimination
1005           Node* src = ac->in(ArrayCopyNode::Src);
1006           ac->replace_edge(src, top());
1007           // src can be top at this point if src and dest of the
1008           // arraycopy were the same
1009           if (src->outcnt() == 0 && !src->is_top()) {
1010             _igvn.remove_dead_node(src);
1011           }
1012         }
1013         _igvn._worklist.push(ac);
1014       } else {
1015         eliminate_gc_barrier(use);
1016       }
1017       j -= (oc1 - res->outcnt());
1018     }
1019     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1020     _igvn.remove_dead_node(res);
1021   }
1022 
1023   //
1024   // Process other users of allocation's projections
1025   //
1026   if (_resproj != NULL && _resproj->outcnt() != 0) {
1027     // First disconnect stores captured by Initialize node.
1028     // If Initialize node is eliminated first in the following code,
1029     // it will kill such stores and DUIterator_Last will assert.
1030     for (DUIterator_Fast jmax, j = _resproj->fast_outs(jmax);  j < jmax; j++) {
1031       Node *use = _resproj->fast_out(j);
1032       if (use->is_AddP()) {
1033         // raw memory addresses used only by the initialization
1034         _igvn.replace_node(use, C->top());
1035         --j; --jmax;
1036       }
1037     }
1038     for (DUIterator_Last jmin, j = _resproj->last_outs(jmin); j >= jmin; ) {
1039       Node *use = _resproj->last_out(j);
1040       uint oc1 = _resproj->outcnt();
1041       if (use->is_Initialize()) {
1042         // Eliminate Initialize node.
1043         InitializeNode *init = use->as_Initialize();
1044         assert(init->outcnt() <= 2, "only a control and memory projection expected");
1045         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1046         if (ctrl_proj != NULL) {
1047           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1048 #ifdef ASSERT
1049           Node* tmp = init->in(TypeFunc::Control);
1050           assert(tmp == _fallthroughcatchproj, "allocation control projection");
1051 #endif
1052         }
1053         Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
1054         if (mem_proj != NULL) {
1055           Node *mem = init->in(TypeFunc::Memory);
1056 #ifdef ASSERT
1057           if (mem->is_MergeMem()) {
1058             assert(mem->in(TypeFunc::Memory) == _memproj_fallthrough, "allocation memory projection");
1059           } else {
1060             assert(mem == _memproj_fallthrough, "allocation memory projection");
1061           }
1062 #endif
1063           _igvn.replace_node(mem_proj, mem);
1064         }
1065       } else  {
1066         assert(false, "only Initialize or AddP expected");
1067       }
1068       j -= (oc1 - _resproj->outcnt());
1069     }
1070   }
1071   if (_fallthroughcatchproj != NULL) {
1072     _igvn.replace_node(_fallthroughcatchproj, alloc->in(TypeFunc::Control));
1073   }
1074   if (_memproj_fallthrough != NULL) {
1075     _igvn.replace_node(_memproj_fallthrough, alloc->in(TypeFunc::Memory));
1076   }
1077   if (_memproj_catchall != NULL) {
1078     _igvn.replace_node(_memproj_catchall, C->top());
1079   }
1080   if (_ioproj_fallthrough != NULL) {
1081     _igvn.replace_node(_ioproj_fallthrough, alloc->in(TypeFunc::I_O));
1082   }
1083   if (_ioproj_catchall != NULL) {
1084     _igvn.replace_node(_ioproj_catchall, C->top());
1085   }
1086   if (_catchallcatchproj != NULL) {
1087     _igvn.replace_node(_catchallcatchproj, C->top());
1088   }
1089 }
1090 
1091 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1092   // Don't do scalar replacement if the frame can be popped by JVMTI:
1093   // if reallocation fails during deoptimization we'll pop all
1094   // interpreter frames for this compiled frame and that won't play
1095   // nice with JVMTI popframe.
1096   if (!EliminateAllocations || JvmtiExport::can_pop_frame() || !alloc->_is_non_escaping) {
1097     return false;
1098   }
1099   Node* klass = alloc->in(AllocateNode::KlassNode);
1100   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1101   Node* res = alloc->result_cast();
1102   // Eliminate boxing allocations which are not used
1103   // regardless scalar replacable status.
1104   bool boxing_alloc = C->eliminate_boxing() &&
1105                       tklass->klass()->is_instance_klass()  &&
1106                       tklass->klass()->as_instance_klass()->is_box_klass();
1107   if (!alloc->_is_scalar_replaceable && (!boxing_alloc || (res != NULL))) {
1108     return false;
1109   }
1110 
1111   extract_call_projections(alloc);
1112 
1113   GrowableArray <SafePointNode *> safepoints;
1114   if (!can_eliminate_allocation(alloc, safepoints)) {
1115     return false;
1116   }
1117 
1118   if (!alloc->_is_scalar_replaceable) {
1119     assert(res == NULL, "sanity");
1120     // We can only eliminate allocation if all debug info references
1121     // are already replaced with SafePointScalarObject because
1122     // we can't search for a fields value without instance_id.
1123     if (safepoints.length() > 0) {
1124       return false;
1125     }
1126   }
1127 
1128   if (!scalar_replacement(alloc, safepoints)) {
1129     return false;
1130   }
1131 
1132   CompileLog* log = C->log();
1133   if (log != NULL) {
1134     log->head("eliminate_allocation type='%d'",
1135               log->identify(tklass->klass()));
1136     JVMState* p = alloc->jvms();
1137     while (p != NULL) {
1138       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1139       p = p->caller();
1140     }
1141     log->tail("eliminate_allocation");
1142   }
1143 
1144   process_users_of_allocation(alloc);
1145 
1146 #ifndef PRODUCT
1147   if (PrintEliminateAllocations) {
1148     if (alloc->is_AllocateArray())
1149       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1150     else
1151       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1152   }
1153 #endif
1154 
1155   return true;
1156 }
1157 
1158 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1159   // EA should remove all uses of non-escaping boxing node.
1160   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != NULL) {
1161     return false;
1162   }
1163 
1164   assert(boxing->result_cast() == NULL, "unexpected boxing node result");
1165 
1166   extract_call_projections(boxing);
1167 
1168   const TypeTuple* r = boxing->tf()->range();
1169   assert(r->cnt() > TypeFunc::Parms, "sanity");
1170   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1171   assert(t != NULL, "sanity");
1172 
1173   CompileLog* log = C->log();
1174   if (log != NULL) {
1175     log->head("eliminate_boxing type='%d'",
1176               log->identify(t->klass()));
1177     JVMState* p = boxing->jvms();
1178     while (p != NULL) {
1179       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1180       p = p->caller();
1181     }
1182     log->tail("eliminate_boxing");
1183   }
1184 
1185   process_users_of_allocation(boxing);
1186 
1187 #ifndef PRODUCT
1188   if (PrintEliminateAllocations) {
1189     tty->print("++++ Eliminated: %d ", boxing->_idx);
1190     boxing->method()->print_short_name(tty);
1191     tty->cr();
1192   }
1193 #endif
1194 
1195   return true;
1196 }
1197 
1198 //---------------------------set_eden_pointers-------------------------
1199 void PhaseMacroExpand::set_eden_pointers(Node* &eden_top_adr, Node* &eden_end_adr) {
1200   if (UseTLAB) {                // Private allocation: load from TLS
1201     Node* thread = transform_later(new ThreadLocalNode());
1202     int tlab_top_offset = in_bytes(JavaThread::tlab_top_offset());
1203     int tlab_end_offset = in_bytes(JavaThread::tlab_end_offset());
1204     eden_top_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_top_offset);
1205     eden_end_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_end_offset);
1206   } else {                      // Shared allocation: load from globals
1207     CollectedHeap* ch = Universe::heap();
1208     address top_adr = (address)ch->top_addr();
1209     address end_adr = (address)ch->end_addr();
1210     eden_top_adr = makecon(TypeRawPtr::make(top_adr));
1211     eden_end_adr = basic_plus_adr(eden_top_adr, end_adr - top_adr);
1212   }
1213 }
1214 
1215 
1216 Node* PhaseMacroExpand::make_load(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) {
1217   Node* adr = basic_plus_adr(base, offset);
1218   const TypePtr* adr_type = adr->bottom_type()->is_ptr();
1219   Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt, MemNode::unordered);
1220   transform_later(value);
1221   return value;
1222 }
1223 
1224 
1225 Node* PhaseMacroExpand::make_store(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) {
1226   Node* adr = basic_plus_adr(base, offset);
1227   mem = StoreNode::make(_igvn, ctl, mem, adr, NULL, value, bt, MemNode::unordered);
1228   transform_later(mem);
1229   return mem;
1230 }
1231 
1232 //=============================================================================
1233 //
1234 //                              A L L O C A T I O N
1235 //
1236 // Allocation attempts to be fast in the case of frequent small objects.
1237 // It breaks down like this:
1238 //
1239 // 1) Size in doublewords is computed.  This is a constant for objects and
1240 // variable for most arrays.  Doubleword units are used to avoid size
1241 // overflow of huge doubleword arrays.  We need doublewords in the end for
1242 // rounding.
1243 //
1244 // 2) Size is checked for being 'too large'.  Too-large allocations will go
1245 // the slow path into the VM.  The slow path can throw any required
1246 // exceptions, and does all the special checks for very large arrays.  The
1247 // size test can constant-fold away for objects.  For objects with
1248 // finalizers it constant-folds the otherway: you always go slow with
1249 // finalizers.
1250 //
1251 // 3) If NOT using TLABs, this is the contended loop-back point.
1252 // Load-Locked the heap top.  If using TLABs normal-load the heap top.
1253 //
1254 // 4) Check that heap top + size*8 < max.  If we fail go the slow ` route.
1255 // NOTE: "top+size*8" cannot wrap the 4Gig line!  Here's why: for largish
1256 // "size*8" we always enter the VM, where "largish" is a constant picked small
1257 // enough that there's always space between the eden max and 4Gig (old space is
1258 // there so it's quite large) and large enough that the cost of entering the VM
1259 // is dwarfed by the cost to initialize the space.
1260 //
1261 // 5) If NOT using TLABs, Store-Conditional the adjusted heap top back
1262 // down.  If contended, repeat at step 3.  If using TLABs normal-store
1263 // adjusted heap top back down; there is no contention.
1264 //
1265 // 6) If !ZeroTLAB then Bulk-clear the object/array.  Fill in klass & mark
1266 // fields.
1267 //
1268 // 7) Merge with the slow-path; cast the raw memory pointer to the correct
1269 // oop flavor.
1270 //
1271 //=============================================================================
1272 // FastAllocateSizeLimit value is in DOUBLEWORDS.
1273 // Allocations bigger than this always go the slow route.
1274 // This value must be small enough that allocation attempts that need to
1275 // trigger exceptions go the slow route.  Also, it must be small enough so
1276 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
1277 //=============================================================================j//
1278 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
1279 // The allocator will coalesce int->oop copies away.  See comment in
1280 // coalesce.cpp about how this works.  It depends critically on the exact
1281 // code shape produced here, so if you are changing this code shape
1282 // make sure the GC info for the heap-top is correct in and around the
1283 // slow-path call.
1284 //
1285 
1286 void PhaseMacroExpand::expand_allocate_common(
1287             AllocateNode* alloc, // allocation node to be expanded
1288             Node* length,  // array length for an array allocation
1289             const TypeFunc* slow_call_type, // Type of slow call
1290             address slow_call_address  // Address of slow call
1291     )
1292 {
1293   Node* ctrl = alloc->in(TypeFunc::Control);
1294   Node* mem  = alloc->in(TypeFunc::Memory);
1295   Node* i_o  = alloc->in(TypeFunc::I_O);
1296   Node* size_in_bytes     = alloc->in(AllocateNode::AllocSize);
1297   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
1298   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1299   assert(ctrl != NULL, "must have control");
1300 
1301   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1302   // they will not be used if "always_slow" is set
1303   enum { slow_result_path = 1, fast_result_path = 2 };
1304   Node *result_region = NULL;
1305   Node *result_phi_rawmem = NULL;
1306   Node *result_phi_rawoop = NULL;
1307   Node *result_phi_i_o = NULL;
1308 
1309   // The initial slow comparison is a size check, the comparison
1310   // we want to do is a BoolTest::gt
1311   bool expand_fast_path = true;
1312   int tv = _igvn.find_int_con(initial_slow_test, -1);
1313   if (tv >= 0) {
1314     // InitialTest has constant result
1315     //   0 - can fit in TLAB
1316     //   1 - always too big or negative
1317     assert(tv <= 1, "0 or 1 if a constant");
1318     expand_fast_path = (tv == 0);
1319     initial_slow_test = NULL;
1320   } else {
1321     initial_slow_test = BoolNode::make_predicate(initial_slow_test, &_igvn);
1322   }
1323 
1324   if (C->env()->dtrace_alloc_probes() ||
1325       (!UseTLAB && !Universe::heap()->supports_inline_contig_alloc())) {
1326     // Force slow-path allocation
1327     expand_fast_path = false;
1328     initial_slow_test = NULL;
1329   }
1330 
1331   bool allocation_has_use = (alloc->result_cast() != NULL);
1332   if (!allocation_has_use) {
1333     InitializeNode* init = alloc->initialization();
1334     if (init != NULL) {
1335       init->remove(&_igvn);
1336     }
1337     if (expand_fast_path && (initial_slow_test == NULL)) {
1338       // Remove allocation node and return.
1339       // Size is a non-negative constant -> no initial check needed -> directly to fast path.
1340       // Also, no usages -> empty fast path -> no fall out to slow path -> nothing left.
1341 #ifndef PRODUCT
1342       if (PrintEliminateAllocations) {
1343         tty->print("NotUsed ");
1344         Node* res = alloc->proj_out_or_null(TypeFunc::Parms);
1345         if (res != NULL) {
1346           res->dump();
1347         } else {
1348           alloc->dump();
1349         }
1350       }
1351 #endif
1352       yank_alloc_node(alloc);
1353       return;
1354     }
1355   }
1356 
1357   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1358   Node *slow_region = NULL;
1359   Node *toobig_false = ctrl;
1360 
1361   // generate the initial test if necessary
1362   if (initial_slow_test != NULL ) {
1363     assert (expand_fast_path, "Only need test if there is a fast path");
1364     slow_region = new RegionNode(3);
1365 
1366     // Now make the initial failure test.  Usually a too-big test but
1367     // might be a TRUE for finalizers or a fancy class check for
1368     // newInstance0.
1369     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1370     transform_later(toobig_iff);
1371     // Plug the failing-too-big test into the slow-path region
1372     Node *toobig_true = new IfTrueNode( toobig_iff );
1373     transform_later(toobig_true);
1374     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1375     toobig_false = new IfFalseNode( toobig_iff );
1376     transform_later(toobig_false);
1377   } else {
1378     // No initial test, just fall into next case
1379     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1380     toobig_false = ctrl;
1381     debug_only(slow_region = NodeSentinel);
1382   }
1383 
1384   // If we are here there are several possibilities
1385   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1386   // no_initial_check means a constant allocation.
1387   // - If check always evaluates to false -> expand_fast_path is false (see above)
1388   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1389   // if !allocation_has_use the fast path is empty
1390   // if !allocation_has_use && no_initial_check
1391   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1392   //   removed by yank_alloc_node above.
1393 
1394   Node *slow_mem = mem;  // save the current memory state for slow path
1395   // generate the fast allocation code unless we know that the initial test will always go slow
1396   if (expand_fast_path) {
1397     // Fast path modifies only raw memory.
1398     if (mem->is_MergeMem()) {
1399       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1400     }
1401 
1402     // allocate the Region and Phi nodes for the result
1403     result_region = new RegionNode(3);
1404     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1405     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1406 
1407     // Grab regular I/O before optional prefetch may change it.
1408     // Slow-path does no I/O so just set it to the original I/O.
1409     result_phi_i_o->init_req(slow_result_path, i_o);
1410 
1411     // Name successful fast-path variables
1412     Node* fast_oop_ctrl;
1413     Node* fast_oop_rawmem;
1414     if (allocation_has_use) {
1415       Node* needgc_ctrl = NULL;
1416       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1417 
1418       intx prefetch_lines = length != NULL ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1419       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1420       Node* fast_oop = bs->obj_allocate(this, ctrl, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1421                                         fast_oop_ctrl, fast_oop_rawmem,
1422                                         prefetch_lines);
1423 
1424       if (initial_slow_test != NULL) {
1425         // This completes all paths into the slow merge point
1426         slow_region->init_req(need_gc_path, needgc_ctrl);
1427         transform_later(slow_region);
1428       } else {
1429         // No initial slow path needed!
1430         // Just fall from the need-GC path straight into the VM call.
1431         slow_region = needgc_ctrl;
1432       }
1433 
1434       InitializeNode* init = alloc->initialization();
1435       fast_oop_rawmem = initialize_object(alloc,
1436                                           fast_oop_ctrl, fast_oop_rawmem, fast_oop,
1437                                           klass_node, length, size_in_bytes);
1438       expand_initialize_membar(alloc, init, fast_oop_ctrl, fast_oop_rawmem);
1439       expand_dtrace_alloc_probe(alloc, fast_oop, fast_oop_ctrl, fast_oop_rawmem);
1440 
1441       result_phi_rawoop->init_req(fast_result_path, fast_oop);
1442     } else {
1443       assert (initial_slow_test != NULL, "sanity");
1444       fast_oop_ctrl   = toobig_false;
1445       fast_oop_rawmem = mem;
1446       transform_later(slow_region);
1447     }
1448 
1449     // Plug in the successful fast-path into the result merge point
1450     result_region    ->init_req(fast_result_path, fast_oop_ctrl);
1451     result_phi_i_o   ->init_req(fast_result_path, i_o);
1452     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1453   } else {
1454     slow_region = ctrl;
1455     result_phi_i_o = i_o; // Rename it to use in the following code.
1456   }
1457 
1458   // Generate slow-path call
1459   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1460                                OptoRuntime::stub_name(slow_call_address),
1461                                alloc->jvms()->bci(),
1462                                TypePtr::BOTTOM);
1463   call->init_req(TypeFunc::Control,   slow_region);
1464   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1465   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1466   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1467   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1468 
1469   call->init_req(TypeFunc::Parms+0, klass_node);
1470   if (length != NULL) {
1471     call->init_req(TypeFunc::Parms+1, length);
1472   }
1473 
1474   // Copy debug information and adjust JVMState information, then replace
1475   // allocate node with the call
1476   copy_call_debug_info((CallNode *) alloc,  call);
1477   if (expand_fast_path) {
1478     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1479   } else {
1480     // Hook i_o projection to avoid its elimination during allocation
1481     // replacement (when only a slow call is generated).
1482     call->set_req(TypeFunc::I_O, result_phi_i_o);
1483   }
1484   _igvn.replace_node(alloc, call);
1485   transform_later(call);
1486 
1487   // Identify the output projections from the allocate node and
1488   // adjust any references to them.
1489   // The control and io projections look like:
1490   //
1491   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1492   //  Allocate                   Catch
1493   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1494   //
1495   //  We are interested in the CatchProj nodes.
1496   //
1497   extract_call_projections(call);
1498 
1499   // An allocate node has separate memory projections for the uses on
1500   // the control and i_o paths. Replace the control memory projection with
1501   // result_phi_rawmem (unless we are only generating a slow call when
1502   // both memory projections are combined)
1503   if (expand_fast_path && _memproj_fallthrough != NULL) {
1504     migrate_outs(_memproj_fallthrough, result_phi_rawmem);
1505   }
1506   // Now change uses of _memproj_catchall to use _memproj_fallthrough and delete
1507   // _memproj_catchall so we end up with a call that has only 1 memory projection.
1508   if (_memproj_catchall != NULL ) {
1509     if (_memproj_fallthrough == NULL) {
1510       _memproj_fallthrough = new ProjNode(call, TypeFunc::Memory);
1511       transform_later(_memproj_fallthrough);
1512     }
1513     migrate_outs(_memproj_catchall, _memproj_fallthrough);
1514     _igvn.remove_dead_node(_memproj_catchall);
1515   }
1516 
1517   // An allocate node has separate i_o projections for the uses on the control
1518   // and i_o paths. Always replace the control i_o projection with result i_o
1519   // otherwise incoming i_o become dead when only a slow call is generated
1520   // (it is different from memory projections where both projections are
1521   // combined in such case).
1522   if (_ioproj_fallthrough != NULL) {
1523     migrate_outs(_ioproj_fallthrough, result_phi_i_o);
1524   }
1525   // Now change uses of _ioproj_catchall to use _ioproj_fallthrough and delete
1526   // _ioproj_catchall so we end up with a call that has only 1 i_o projection.
1527   if (_ioproj_catchall != NULL ) {
1528     if (_ioproj_fallthrough == NULL) {
1529       _ioproj_fallthrough = new ProjNode(call, TypeFunc::I_O);
1530       transform_later(_ioproj_fallthrough);
1531     }
1532     migrate_outs(_ioproj_catchall, _ioproj_fallthrough);
1533     _igvn.remove_dead_node(_ioproj_catchall);
1534   }
1535 
1536   // if we generated only a slow call, we are done
1537   if (!expand_fast_path) {
1538     // Now we can unhook i_o.
1539     if (result_phi_i_o->outcnt() > 1) {
1540       call->set_req(TypeFunc::I_O, top());
1541     } else {
1542       assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1543       // Case of new array with negative size known during compilation.
1544       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1545       // following code since call to runtime will throw exception.
1546       // As result there will be no users of i_o after the call.
1547       // Leave i_o attached to this call to avoid problems in preceding graph.
1548     }
1549     return;
1550   }
1551 
1552   if (_fallthroughcatchproj != NULL) {
1553     ctrl = _fallthroughcatchproj->clone();
1554     transform_later(ctrl);
1555     _igvn.replace_node(_fallthroughcatchproj, result_region);
1556   } else {
1557     ctrl = top();
1558   }
1559   Node *slow_result;
1560   if (_resproj == NULL) {
1561     // no uses of the allocation result
1562     slow_result = top();
1563   } else {
1564     slow_result = _resproj->clone();
1565     transform_later(slow_result);
1566     _igvn.replace_node(_resproj, result_phi_rawoop);
1567   }
1568 
1569   // Plug slow-path into result merge point
1570   result_region->init_req( slow_result_path, ctrl);
1571   transform_later(result_region);
1572   if (allocation_has_use) {
1573     result_phi_rawoop->init_req(slow_result_path, slow_result);
1574     transform_later(result_phi_rawoop);
1575   }
1576   result_phi_rawmem->init_req(slow_result_path, _memproj_fallthrough);
1577   transform_later(result_phi_rawmem);
1578   transform_later(result_phi_i_o);
1579   // This completes all paths into the result merge point
1580 }
1581 
1582 // Remove alloc node that has no uses.
1583 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1584   Node* ctrl = alloc->in(TypeFunc::Control);
1585   Node* mem  = alloc->in(TypeFunc::Memory);
1586   Node* i_o  = alloc->in(TypeFunc::I_O);
1587 
1588   extract_call_projections(alloc);
1589   if (_resproj != NULL) {
1590     for (DUIterator_Fast imax, i = _resproj->fast_outs(imax); i < imax; i++) {
1591       Node* use = _resproj->fast_out(i);
1592       use->isa_MemBar()->remove(&_igvn);
1593       --imax;
1594       --i; // back up iterator
1595     }
1596     assert(_resproj->outcnt() == 0, "all uses must be deleted");
1597     _igvn.remove_dead_node(_resproj);
1598   }
1599   if (_fallthroughcatchproj != NULL) {
1600     migrate_outs(_fallthroughcatchproj, ctrl);
1601     _igvn.remove_dead_node(_fallthroughcatchproj);
1602   }
1603   if (_catchallcatchproj != NULL) {
1604     _igvn.rehash_node_delayed(_catchallcatchproj);
1605     _catchallcatchproj->set_req(0, top());
1606   }
1607   if (_fallthroughproj != NULL) {
1608     Node* catchnode = _fallthroughproj->unique_ctrl_out();
1609     _igvn.remove_dead_node(catchnode);
1610     _igvn.remove_dead_node(_fallthroughproj);
1611   }
1612   if (_memproj_fallthrough != NULL) {
1613     migrate_outs(_memproj_fallthrough, mem);
1614     _igvn.remove_dead_node(_memproj_fallthrough);
1615   }
1616   if (_ioproj_fallthrough != NULL) {
1617     migrate_outs(_ioproj_fallthrough, i_o);
1618     _igvn.remove_dead_node(_ioproj_fallthrough);
1619   }
1620   if (_memproj_catchall != NULL) {
1621     _igvn.rehash_node_delayed(_memproj_catchall);
1622     _memproj_catchall->set_req(0, top());
1623   }
1624   if (_ioproj_catchall != NULL) {
1625     _igvn.rehash_node_delayed(_ioproj_catchall);
1626     _ioproj_catchall->set_req(0, top());
1627   }
1628 #ifndef PRODUCT
1629   if (PrintEliminateAllocations) {
1630     if (alloc->is_AllocateArray()) {
1631       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1632     } else {
1633       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1634     }
1635   }
1636 #endif
1637   _igvn.remove_dead_node(alloc);
1638 }
1639 
1640 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1641                                                 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1642   // If initialization is performed by an array copy, any required
1643   // MemBarStoreStore was already added. If the object does not
1644   // escape no need for a MemBarStoreStore. If the object does not
1645   // escape in its initializer and memory barrier (MemBarStoreStore or
1646   // stronger) is already added at exit of initializer, also no need
1647   // for a MemBarStoreStore. Otherwise we need a MemBarStoreStore
1648   // so that stores that initialize this object can't be reordered
1649   // with a subsequent store that makes this object accessible by
1650   // other threads.
1651   // Other threads include java threads and JVM internal threads
1652   // (for example concurrent GC threads). Current concurrent GC
1653   // implementation: G1 will not scan newly created object,
1654   // so it's safe to skip storestore barrier when allocation does
1655   // not escape.
1656   if (!alloc->does_not_escape_thread() &&
1657     !alloc->is_allocation_MemBar_redundant() &&
1658     (init == NULL || !init->is_complete_with_arraycopy())) {
1659     if (init == NULL || init->req() < InitializeNode::RawStores) {
1660       // No InitializeNode or no stores captured by zeroing
1661       // elimination. Simply add the MemBarStoreStore after object
1662       // initialization.
1663       MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1664       transform_later(mb);
1665 
1666       mb->init_req(TypeFunc::Memory, fast_oop_rawmem);
1667       mb->init_req(TypeFunc::Control, fast_oop_ctrl);
1668       fast_oop_ctrl = new ProjNode(mb, TypeFunc::Control);
1669       transform_later(fast_oop_ctrl);
1670       fast_oop_rawmem = new ProjNode(mb, TypeFunc::Memory);
1671       transform_later(fast_oop_rawmem);
1672     } else {
1673       // Add the MemBarStoreStore after the InitializeNode so that
1674       // all stores performing the initialization that were moved
1675       // before the InitializeNode happen before the storestore
1676       // barrier.
1677 
1678       Node* init_ctrl = init->proj_out_or_null(TypeFunc::Control);
1679       Node* init_mem = init->proj_out_or_null(TypeFunc::Memory);
1680 
1681       MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1682       transform_later(mb);
1683 
1684       Node* ctrl = new ProjNode(init, TypeFunc::Control);
1685       transform_later(ctrl);
1686       Node* mem = new ProjNode(init, TypeFunc::Memory);
1687       transform_later(mem);
1688 
1689       // The MemBarStoreStore depends on control and memory coming
1690       // from the InitializeNode
1691       mb->init_req(TypeFunc::Memory, mem);
1692       mb->init_req(TypeFunc::Control, ctrl);
1693 
1694       ctrl = new ProjNode(mb, TypeFunc::Control);
1695       transform_later(ctrl);
1696       mem = new ProjNode(mb, TypeFunc::Memory);
1697       transform_later(mem);
1698 
1699       // All nodes that depended on the InitializeNode for control
1700       // and memory must now depend on the MemBarNode that itself
1701       // depends on the InitializeNode
1702       if (init_ctrl != NULL) {
1703         _igvn.replace_node(init_ctrl, ctrl);
1704       }
1705       if (init_mem != NULL) {
1706         _igvn.replace_node(init_mem, mem);
1707       }
1708     }
1709   }
1710 }
1711 
1712 void PhaseMacroExpand::expand_dtrace_alloc_probe(AllocateNode* alloc, Node* oop,
1713                                                 Node*& ctrl, Node*& rawmem) {
1714   if (C->env()->dtrace_extended_probes()) {
1715     // Slow-path call
1716     int size = TypeFunc::Parms + 2;
1717     CallLeafNode *call = new CallLeafNode(OptoRuntime::dtrace_object_alloc_Type(),
1718                                           CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_object_alloc_base),
1719                                           "dtrace_object_alloc",
1720                                           TypeRawPtr::BOTTOM);
1721 
1722     // Get base of thread-local storage area
1723     Node* thread = new ThreadLocalNode();
1724     transform_later(thread);
1725 
1726     call->init_req(TypeFunc::Parms + 0, thread);
1727     call->init_req(TypeFunc::Parms + 1, oop);
1728     call->init_req(TypeFunc::Control, ctrl);
1729     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1730     call->init_req(TypeFunc::Memory , ctrl);
1731     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1732     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1733     transform_later(call);
1734     ctrl = new ProjNode(call, TypeFunc::Control);
1735     transform_later(ctrl);
1736     rawmem = new ProjNode(call, TypeFunc::Memory);
1737     transform_later(rawmem);
1738   }
1739 }
1740 
1741 // Helper for PhaseMacroExpand::expand_allocate_common.
1742 // Initializes the newly-allocated storage.
1743 Node*
1744 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1745                                     Node* control, Node* rawmem, Node* object,
1746                                     Node* klass_node, Node* length,
1747                                     Node* size_in_bytes) {
1748   InitializeNode* init = alloc->initialization();
1749   // Store the klass & mark bits
1750   Node* mark_node = alloc->make_ideal_mark(&_igvn, object, control, rawmem);
1751   if (!mark_node->is_Con()) {
1752     transform_later(mark_node);
1753   }
1754   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1755 
1756   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1757   int header_size = alloc->minimum_header_size();  // conservatively small
1758 
1759   // Array length
1760   if (length != NULL) {         // Arrays need length field
1761     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1762     // conservatively small header size:
1763     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1764     ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1765     if (k->is_array_klass())    // we know the exact header size in most cases:
1766       header_size = Klass::layout_helper_header_size(k->layout_helper());
1767   }
1768 
1769   // Clear the object body, if necessary.
1770   if (init == NULL) {
1771     // The init has somehow disappeared; be cautious and clear everything.
1772     //
1773     // This can happen if a node is allocated but an uncommon trap occurs
1774     // immediately.  In this case, the Initialize gets associated with the
1775     // trap, and may be placed in a different (outer) loop, if the Allocate
1776     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1777     // there can be two Allocates to one Initialize.  The answer in all these
1778     // edge cases is safety first.  It is always safe to clear immediately
1779     // within an Allocate, and then (maybe or maybe not) clear some more later.
1780     if (!(UseTLAB && ZeroTLAB)) {
1781       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1782                                             header_size, size_in_bytes,
1783                                             &_igvn);
1784     }
1785   } else {
1786     if (!init->is_complete()) {
1787       // Try to win by zeroing only what the init does not store.
1788       // We can also try to do some peephole optimizations,
1789       // such as combining some adjacent subword stores.
1790       rawmem = init->complete_stores(control, rawmem, object,
1791                                      header_size, size_in_bytes, &_igvn);
1792     }
1793     // We have no more use for this link, since the AllocateNode goes away:
1794     init->set_req(InitializeNode::RawAddress, top());
1795     // (If we keep the link, it just confuses the register allocator,
1796     // who thinks he sees a real use of the address by the membar.)
1797   }
1798 
1799   return rawmem;
1800 }
1801 
1802 // Generate prefetch instructions for next allocations.
1803 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
1804                                         Node*& contended_phi_rawmem,
1805                                         Node* old_eden_top, Node* new_eden_top,
1806                                         intx lines) {
1807    enum { fall_in_path = 1, pf_path = 2 };
1808    if( UseTLAB && AllocatePrefetchStyle == 2 ) {
1809       // Generate prefetch allocation with watermark check.
1810       // As an allocation hits the watermark, we will prefetch starting
1811       // at a "distance" away from watermark.
1812 
1813       Node *pf_region = new RegionNode(3);
1814       Node *pf_phi_rawmem = new PhiNode( pf_region, Type::MEMORY,
1815                                                 TypeRawPtr::BOTTOM );
1816       // I/O is used for Prefetch
1817       Node *pf_phi_abio = new PhiNode( pf_region, Type::ABIO );
1818 
1819       Node *thread = new ThreadLocalNode();
1820       transform_later(thread);
1821 
1822       Node *eden_pf_adr = new AddPNode( top()/*not oop*/, thread,
1823                    _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) );
1824       transform_later(eden_pf_adr);
1825 
1826       Node *old_pf_wm = new LoadPNode(needgc_false,
1827                                    contended_phi_rawmem, eden_pf_adr,
1828                                    TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM,
1829                                    MemNode::unordered);
1830       transform_later(old_pf_wm);
1831 
1832       // check against new_eden_top
1833       Node *need_pf_cmp = new CmpPNode( new_eden_top, old_pf_wm );
1834       transform_later(need_pf_cmp);
1835       Node *need_pf_bol = new BoolNode( need_pf_cmp, BoolTest::ge );
1836       transform_later(need_pf_bol);
1837       IfNode *need_pf_iff = new IfNode( needgc_false, need_pf_bol,
1838                                        PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
1839       transform_later(need_pf_iff);
1840 
1841       // true node, add prefetchdistance
1842       Node *need_pf_true = new IfTrueNode( need_pf_iff );
1843       transform_later(need_pf_true);
1844 
1845       Node *need_pf_false = new IfFalseNode( need_pf_iff );
1846       transform_later(need_pf_false);
1847 
1848       Node *new_pf_wmt = new AddPNode( top(), old_pf_wm,
1849                                     _igvn.MakeConX(AllocatePrefetchDistance) );
1850       transform_later(new_pf_wmt );
1851       new_pf_wmt->set_req(0, need_pf_true);
1852 
1853       Node *store_new_wmt = new StorePNode(need_pf_true,
1854                                        contended_phi_rawmem, eden_pf_adr,
1855                                        TypeRawPtr::BOTTOM, new_pf_wmt,
1856                                        MemNode::unordered);
1857       transform_later(store_new_wmt);
1858 
1859       // adding prefetches
1860       pf_phi_abio->init_req( fall_in_path, i_o );
1861 
1862       Node *prefetch_adr;
1863       Node *prefetch;
1864       uint step_size = AllocatePrefetchStepSize;
1865       uint distance = 0;
1866 
1867       for ( intx i = 0; i < lines; i++ ) {
1868         prefetch_adr = new AddPNode( old_pf_wm, new_pf_wmt,
1869                                             _igvn.MakeConX(distance) );
1870         transform_later(prefetch_adr);
1871         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1872         transform_later(prefetch);
1873         distance += step_size;
1874         i_o = prefetch;
1875       }
1876       pf_phi_abio->set_req( pf_path, i_o );
1877 
1878       pf_region->init_req( fall_in_path, need_pf_false );
1879       pf_region->init_req( pf_path, need_pf_true );
1880 
1881       pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem );
1882       pf_phi_rawmem->init_req( pf_path, store_new_wmt );
1883 
1884       transform_later(pf_region);
1885       transform_later(pf_phi_rawmem);
1886       transform_later(pf_phi_abio);
1887 
1888       needgc_false = pf_region;
1889       contended_phi_rawmem = pf_phi_rawmem;
1890       i_o = pf_phi_abio;
1891    } else if( UseTLAB && AllocatePrefetchStyle == 3 ) {
1892       // Insert a prefetch instruction for each allocation.
1893       // This code is used to generate 1 prefetch instruction per cache line.
1894 
1895       // Generate several prefetch instructions.
1896       uint step_size = AllocatePrefetchStepSize;
1897       uint distance = AllocatePrefetchDistance;
1898 
1899       // Next cache address.
1900       Node *cache_adr = new AddPNode(old_eden_top, old_eden_top,
1901                                      _igvn.MakeConX(step_size + distance));
1902       transform_later(cache_adr);
1903       cache_adr = new CastP2XNode(needgc_false, cache_adr);
1904       transform_later(cache_adr);
1905       // Address is aligned to execute prefetch to the beginning of cache line size
1906       // (it is important when BIS instruction is used on SPARC as prefetch).
1907       Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1));
1908       cache_adr = new AndXNode(cache_adr, mask);
1909       transform_later(cache_adr);
1910       cache_adr = new CastX2PNode(cache_adr);
1911       transform_later(cache_adr);
1912 
1913       // Prefetch
1914       Node *prefetch = new PrefetchAllocationNode( contended_phi_rawmem, cache_adr );
1915       prefetch->set_req(0, needgc_false);
1916       transform_later(prefetch);
1917       contended_phi_rawmem = prefetch;
1918       Node *prefetch_adr;
1919       distance = step_size;
1920       for ( intx i = 1; i < lines; i++ ) {
1921         prefetch_adr = new AddPNode( cache_adr, cache_adr,
1922                                             _igvn.MakeConX(distance) );
1923         transform_later(prefetch_adr);
1924         prefetch = new PrefetchAllocationNode( contended_phi_rawmem, prefetch_adr );
1925         transform_later(prefetch);
1926         distance += step_size;
1927         contended_phi_rawmem = prefetch;
1928       }
1929    } else if( AllocatePrefetchStyle > 0 ) {
1930       // Insert a prefetch for each allocation only on the fast-path
1931       Node *prefetch_adr;
1932       Node *prefetch;
1933       // Generate several prefetch instructions.
1934       uint step_size = AllocatePrefetchStepSize;
1935       uint distance = AllocatePrefetchDistance;
1936       for ( intx i = 0; i < lines; i++ ) {
1937         prefetch_adr = new AddPNode( old_eden_top, new_eden_top,
1938                                             _igvn.MakeConX(distance) );
1939         transform_later(prefetch_adr);
1940         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1941         // Do not let it float too high, since if eden_top == eden_end,
1942         // both might be null.
1943         if( i == 0 ) { // Set control for first prefetch, next follows it
1944           prefetch->init_req(0, needgc_false);
1945         }
1946         transform_later(prefetch);
1947         distance += step_size;
1948         i_o = prefetch;
1949       }
1950    }
1951    return i_o;
1952 }
1953 
1954 
1955 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
1956   expand_allocate_common(alloc, NULL,
1957                          OptoRuntime::new_instance_Type(),
1958                          OptoRuntime::new_instance_Java());
1959 }
1960 
1961 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
1962   Node* length = alloc->in(AllocateNode::ALength);
1963   InitializeNode* init = alloc->initialization();
1964   Node* klass_node = alloc->in(AllocateNode::KlassNode);
1965   ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1966   address slow_call_address;  // Address of slow call
1967   if (init != NULL && init->is_complete_with_arraycopy() &&
1968       k->is_type_array_klass()) {
1969     // Don't zero type array during slow allocation in VM since
1970     // it will be initialized later by arraycopy in compiled code.
1971     slow_call_address = OptoRuntime::new_array_nozero_Java();
1972   } else {
1973     slow_call_address = OptoRuntime::new_array_Java();
1974   }
1975   expand_allocate_common(alloc, length,
1976                          OptoRuntime::new_array_Type(),
1977                          slow_call_address);
1978 }
1979 
1980 //-------------------mark_eliminated_box----------------------------------
1981 //
1982 // During EA obj may point to several objects but after few ideal graph
1983 // transformations (CCP) it may point to only one non escaping object
1984 // (but still using phi), corresponding locks and unlocks will be marked
1985 // for elimination. Later obj could be replaced with a new node (new phi)
1986 // and which does not have escape information. And later after some graph
1987 // reshape other locks and unlocks (which were not marked for elimination
1988 // before) are connected to this new obj (phi) but they still will not be
1989 // marked for elimination since new obj has no escape information.
1990 // Mark all associated (same box and obj) lock and unlock nodes for
1991 // elimination if some of them marked already.
1992 void PhaseMacroExpand::mark_eliminated_box(Node* oldbox, Node* obj) {
1993   if (oldbox->as_BoxLock()->is_eliminated())
1994     return; // This BoxLock node was processed already.
1995 
1996   // New implementation (EliminateNestedLocks) has separate BoxLock
1997   // node for each locked region so mark all associated locks/unlocks as
1998   // eliminated even if different objects are referenced in one locked region
1999   // (for example, OSR compilation of nested loop inside locked scope).
2000   if (EliminateNestedLocks ||
2001       oldbox->as_BoxLock()->is_simple_lock_region(NULL, obj)) {
2002     // Box is used only in one lock region. Mark this box as eliminated.
2003     _igvn.hash_delete(oldbox);
2004     oldbox->as_BoxLock()->set_eliminated(); // This changes box's hash value
2005      _igvn.hash_insert(oldbox);
2006 
2007     for (uint i = 0; i < oldbox->outcnt(); i++) {
2008       Node* u = oldbox->raw_out(i);
2009       if (u->is_AbstractLock() && !u->as_AbstractLock()->is_non_esc_obj()) {
2010         AbstractLockNode* alock = u->as_AbstractLock();
2011         // Check lock's box since box could be referenced by Lock's debug info.
2012         if (alock->box_node() == oldbox) {
2013           // Mark eliminated all related locks and unlocks.
2014 #ifdef ASSERT
2015           alock->log_lock_optimization(C, "eliminate_lock_set_non_esc4");
2016 #endif
2017           alock->set_non_esc_obj();
2018         }
2019       }
2020     }
2021     return;
2022   }
2023 
2024   // Create new "eliminated" BoxLock node and use it in monitor debug info
2025   // instead of oldbox for the same object.
2026   BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
2027 
2028   // Note: BoxLock node is marked eliminated only here and it is used
2029   // to indicate that all associated lock and unlock nodes are marked
2030   // for elimination.
2031   newbox->set_eliminated();
2032   transform_later(newbox);
2033 
2034   // Replace old box node with new box for all users of the same object.
2035   for (uint i = 0; i < oldbox->outcnt();) {
2036     bool next_edge = true;
2037 
2038     Node* u = oldbox->raw_out(i);
2039     if (u->is_AbstractLock()) {
2040       AbstractLockNode* alock = u->as_AbstractLock();
2041       if (alock->box_node() == oldbox && alock->obj_node()->eqv_uncast(obj)) {
2042         // Replace Box and mark eliminated all related locks and unlocks.
2043 #ifdef ASSERT
2044         alock->log_lock_optimization(C, "eliminate_lock_set_non_esc5");
2045 #endif
2046         alock->set_non_esc_obj();
2047         _igvn.rehash_node_delayed(alock);
2048         alock->set_box_node(newbox);
2049         next_edge = false;
2050       }
2051     }
2052     if (u->is_FastLock() && u->as_FastLock()->obj_node()->eqv_uncast(obj)) {
2053       FastLockNode* flock = u->as_FastLock();
2054       assert(flock->box_node() == oldbox, "sanity");
2055       _igvn.rehash_node_delayed(flock);
2056       flock->set_box_node(newbox);
2057       next_edge = false;
2058     }
2059 
2060     // Replace old box in monitor debug info.
2061     if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
2062       SafePointNode* sfn = u->as_SafePoint();
2063       JVMState* youngest_jvms = sfn->jvms();
2064       int max_depth = youngest_jvms->depth();
2065       for (int depth = 1; depth <= max_depth; depth++) {
2066         JVMState* jvms = youngest_jvms->of_depth(depth);
2067         int num_mon  = jvms->nof_monitors();
2068         // Loop over monitors
2069         for (int idx = 0; idx < num_mon; idx++) {
2070           Node* obj_node = sfn->monitor_obj(jvms, idx);
2071           Node* box_node = sfn->monitor_box(jvms, idx);
2072           if (box_node == oldbox && obj_node->eqv_uncast(obj)) {
2073             int j = jvms->monitor_box_offset(idx);
2074             _igvn.replace_input_of(u, j, newbox);
2075             next_edge = false;
2076           }
2077         }
2078       }
2079     }
2080     if (next_edge) i++;
2081   }
2082 }
2083 
2084 //-----------------------mark_eliminated_locking_nodes-----------------------
2085 void PhaseMacroExpand::mark_eliminated_locking_nodes(AbstractLockNode *alock) {
2086   if (EliminateNestedLocks) {
2087     if (alock->is_nested()) {
2088        assert(alock->box_node()->as_BoxLock()->is_eliminated(), "sanity");
2089        return;
2090     } else if (!alock->is_non_esc_obj()) { // Not eliminated or coarsened
2091       // Only Lock node has JVMState needed here.
2092       // Not that preceding claim is documented anywhere else.
2093       if (alock->jvms() != NULL) {
2094         if (alock->as_Lock()->is_nested_lock_region()) {
2095           // Mark eliminated related nested locks and unlocks.
2096           Node* obj = alock->obj_node();
2097           BoxLockNode* box_node = alock->box_node()->as_BoxLock();
2098           assert(!box_node->is_eliminated(), "should not be marked yet");
2099           // Note: BoxLock node is marked eliminated only here
2100           // and it is used to indicate that all associated lock
2101           // and unlock nodes are marked for elimination.
2102           box_node->set_eliminated(); // Box's hash is always NO_HASH here
2103           for (uint i = 0; i < box_node->outcnt(); i++) {
2104             Node* u = box_node->raw_out(i);
2105             if (u->is_AbstractLock()) {
2106               alock = u->as_AbstractLock();
2107               if (alock->box_node() == box_node) {
2108                 // Verify that this Box is referenced only by related locks.
2109                 assert(alock->obj_node()->eqv_uncast(obj), "");
2110                 // Mark all related locks and unlocks.
2111 #ifdef ASSERT
2112                 alock->log_lock_optimization(C, "eliminate_lock_set_nested");
2113 #endif
2114                 alock->set_nested();
2115               }
2116             }
2117           }
2118         } else {
2119 #ifdef ASSERT
2120           alock->log_lock_optimization(C, "eliminate_lock_NOT_nested_lock_region");
2121           if (C->log() != NULL)
2122             alock->as_Lock()->is_nested_lock_region(C); // rerun for debugging output
2123 #endif
2124         }
2125       }
2126       return;
2127     }
2128     // Process locks for non escaping object
2129     assert(alock->is_non_esc_obj(), "");
2130   } // EliminateNestedLocks
2131 
2132   if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2133     // Look for all locks of this object and mark them and
2134     // corresponding BoxLock nodes as eliminated.
2135     Node* obj = alock->obj_node();
2136     for (uint j = 0; j < obj->outcnt(); j++) {
2137       Node* o = obj->raw_out(j);
2138       if (o->is_AbstractLock() &&
2139           o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2140         alock = o->as_AbstractLock();
2141         Node* box = alock->box_node();
2142         // Replace old box node with new eliminated box for all users
2143         // of the same object and mark related locks as eliminated.
2144         mark_eliminated_box(box, obj);
2145       }
2146     }
2147   }
2148 }
2149 
2150 // we have determined that this lock/unlock can be eliminated, we simply
2151 // eliminate the node without expanding it.
2152 //
2153 // Note:  The membar's associated with the lock/unlock are currently not
2154 //        eliminated.  This should be investigated as a future enhancement.
2155 //
2156 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2157 
2158   if (!alock->is_eliminated()) {
2159     return false;
2160   }
2161 #ifdef ASSERT
2162   if (!alock->is_coarsened()) {
2163     // Check that new "eliminated" BoxLock node is created.
2164     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2165     assert(oldbox->is_eliminated(), "should be done already");
2166   }
2167 #endif
2168 
2169   alock->log_lock_optimization(C, "eliminate_lock");
2170 
2171 #ifndef PRODUCT
2172   if (PrintEliminateLocks) {
2173     if (alock->is_Lock()) {
2174       tty->print_cr("++++ Eliminated: %d Lock", alock->_idx);
2175     } else {
2176       tty->print_cr("++++ Eliminated: %d Unlock", alock->_idx);
2177     }
2178   }
2179 #endif
2180 
2181   Node* mem  = alock->in(TypeFunc::Memory);
2182   Node* ctrl = alock->in(TypeFunc::Control);
2183   guarantee(ctrl != NULL, "missing control projection, cannot replace_node() with NULL");
2184 
2185   extract_call_projections(alock);
2186   // There are 2 projections from the lock.  The lock node will
2187   // be deleted when its last use is subsumed below.
2188   assert(alock->outcnt() == 2 &&
2189          _fallthroughproj != NULL &&
2190          _memproj_fallthrough != NULL,
2191          "Unexpected projections from Lock/Unlock");
2192 
2193   Node* fallthroughproj = _fallthroughproj;
2194   Node* memproj_fallthrough = _memproj_fallthrough;
2195 
2196   // The memory projection from a lock/unlock is RawMem
2197   // The input to a Lock is merged memory, so extract its RawMem input
2198   // (unless the MergeMem has been optimized away.)
2199   if (alock->is_Lock()) {
2200     // Seach for MemBarAcquireLock node and delete it also.
2201     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2202     assert(membar != NULL && membar->Opcode() == Op_MemBarAcquireLock, "");
2203     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2204     Node* memproj = membar->proj_out(TypeFunc::Memory);
2205     _igvn.replace_node(ctrlproj, fallthroughproj);
2206     _igvn.replace_node(memproj, memproj_fallthrough);
2207 
2208     // Delete FastLock node also if this Lock node is unique user
2209     // (a loop peeling may clone a Lock node).
2210     Node* flock = alock->as_Lock()->fastlock_node();
2211     if (flock->outcnt() == 1) {
2212       assert(flock->unique_out() == alock, "sanity");
2213       _igvn.replace_node(flock, top());
2214     }
2215   }
2216 
2217   // Seach for MemBarReleaseLock node and delete it also.
2218   if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2219     MemBarNode* membar = ctrl->in(0)->as_MemBar();
2220     assert(membar->Opcode() == Op_MemBarReleaseLock &&
2221            mem->is_Proj() && membar == mem->in(0), "");
2222     _igvn.replace_node(fallthroughproj, ctrl);
2223     _igvn.replace_node(memproj_fallthrough, mem);
2224     fallthroughproj = ctrl;
2225     memproj_fallthrough = mem;
2226     ctrl = membar->in(TypeFunc::Control);
2227     mem  = membar->in(TypeFunc::Memory);
2228   }
2229 
2230   _igvn.replace_node(fallthroughproj, ctrl);
2231   _igvn.replace_node(memproj_fallthrough, mem);
2232   return true;
2233 }
2234 
2235 
2236 //------------------------------expand_lock_node----------------------
2237 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
2238 
2239   Node* ctrl = lock->in(TypeFunc::Control);
2240   Node* mem = lock->in(TypeFunc::Memory);
2241   Node* obj = lock->obj_node();
2242   Node* box = lock->box_node();
2243   Node* flock = lock->fastlock_node();
2244 
2245   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2246 
2247   // Make the merge point
2248   Node *region;
2249   Node *mem_phi;
2250   Node *slow_path;
2251 
2252   if (UseOptoBiasInlining) {
2253     /*
2254      *  See the full description in MacroAssembler::biased_locking_enter().
2255      *
2256      *  if( (mark_word & biased_lock_mask) == biased_lock_pattern ) {
2257      *    // The object is biased.
2258      *    proto_node = klass->prototype_header;
2259      *    o_node = thread | proto_node;
2260      *    x_node = o_node ^ mark_word;
2261      *    if( (x_node & ~age_mask) == 0 ) { // Biased to the current thread ?
2262      *      // Done.
2263      *    } else {
2264      *      if( (x_node & biased_lock_mask) != 0 ) {
2265      *        // The klass's prototype header is no longer biased.
2266      *        cas(&mark_word, mark_word, proto_node)
2267      *        goto cas_lock;
2268      *      } else {
2269      *        // The klass's prototype header is still biased.
2270      *        if( (x_node & epoch_mask) != 0 ) { // Expired epoch?
2271      *          old = mark_word;
2272      *          new = o_node;
2273      *        } else {
2274      *          // Different thread or anonymous biased.
2275      *          old = mark_word & (epoch_mask | age_mask | biased_lock_mask);
2276      *          new = thread | old;
2277      *        }
2278      *        // Try to rebias.
2279      *        if( cas(&mark_word, old, new) == 0 ) {
2280      *          // Done.
2281      *        } else {
2282      *          goto slow_path; // Failed.
2283      *        }
2284      *      }
2285      *    }
2286      *  } else {
2287      *    // The object is not biased.
2288      *    cas_lock:
2289      *    if( FastLock(obj) == 0 ) {
2290      *      // Done.
2291      *    } else {
2292      *      slow_path:
2293      *      OptoRuntime::complete_monitor_locking_Java(obj);
2294      *    }
2295      *  }
2296      */
2297 
2298     region  = new RegionNode(5);
2299     // create a Phi for the memory state
2300     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2301 
2302     Node* fast_lock_region  = new RegionNode(3);
2303     Node* fast_lock_mem_phi = new PhiNode( fast_lock_region, Type::MEMORY, TypeRawPtr::BOTTOM);
2304 
2305     // First, check mark word for the biased lock pattern.
2306     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2307 
2308     // Get fast path - mark word has the biased lock pattern.
2309     ctrl = opt_bits_test(ctrl, fast_lock_region, 1, mark_node,
2310                          markWord::biased_lock_mask_in_place,
2311                          markWord::biased_lock_pattern, true);
2312     // fast_lock_region->in(1) is set to slow path.
2313     fast_lock_mem_phi->init_req(1, mem);
2314 
2315     // Now check that the lock is biased to the current thread and has
2316     // the same epoch and bias as Klass::_prototype_header.
2317 
2318     // Special-case a fresh allocation to avoid building nodes:
2319     Node* klass_node = AllocateNode::Ideal_klass(obj, &_igvn);
2320     if (klass_node == NULL) {
2321       Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
2322       klass_node = transform_later(LoadKlassNode::make(_igvn, NULL, mem, k_adr, _igvn.type(k_adr)->is_ptr()));
2323 #ifdef _LP64
2324       if (UseCompressedClassPointers && klass_node->is_DecodeNKlass()) {
2325         assert(klass_node->in(1)->Opcode() == Op_LoadNKlass, "sanity");
2326         klass_node->in(1)->init_req(0, ctrl);
2327       } else
2328 #endif
2329       klass_node->init_req(0, ctrl);
2330     }
2331     Node *proto_node = make_load(ctrl, mem, klass_node, in_bytes(Klass::prototype_header_offset()), TypeX_X, TypeX_X->basic_type());
2332 
2333     Node* thread = transform_later(new ThreadLocalNode());
2334     Node* cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2335     Node* o_node = transform_later(new OrXNode(cast_thread, proto_node));
2336     Node* x_node = transform_later(new XorXNode(o_node, mark_node));
2337 
2338     // Get slow path - mark word does NOT match the value.
2339     STATIC_ASSERT(markWord::age_mask_in_place <= INT_MAX);
2340     Node* not_biased_ctrl =  opt_bits_test(ctrl, region, 3, x_node,
2341                                       (~(int)markWord::age_mask_in_place), 0);
2342     // region->in(3) is set to fast path - the object is biased to the current thread.
2343     mem_phi->init_req(3, mem);
2344 
2345 
2346     // Mark word does NOT match the value (thread | Klass::_prototype_header).
2347 
2348 
2349     // First, check biased pattern.
2350     // Get fast path - _prototype_header has the same biased lock pattern.
2351     ctrl =  opt_bits_test(not_biased_ctrl, fast_lock_region, 2, x_node,
2352                           markWord::biased_lock_mask_in_place, 0, true);
2353 
2354     not_biased_ctrl = fast_lock_region->in(2); // Slow path
2355     // fast_lock_region->in(2) - the prototype header is no longer biased
2356     // and we have to revoke the bias on this object.
2357     // We are going to try to reset the mark of this object to the prototype
2358     // value and fall through to the CAS-based locking scheme.
2359     Node* adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
2360     Node* cas = new StoreXConditionalNode(not_biased_ctrl, mem, adr,
2361                                           proto_node, mark_node);
2362     transform_later(cas);
2363     Node* proj = transform_later(new SCMemProjNode(cas));
2364     fast_lock_mem_phi->init_req(2, proj);
2365 
2366 
2367     // Second, check epoch bits.
2368     Node* rebiased_region  = new RegionNode(3);
2369     Node* old_phi = new PhiNode( rebiased_region, TypeX_X);
2370     Node* new_phi = new PhiNode( rebiased_region, TypeX_X);
2371 
2372     // Get slow path - mark word does NOT match epoch bits.
2373     Node* epoch_ctrl =  opt_bits_test(ctrl, rebiased_region, 1, x_node,
2374                                       markWord::epoch_mask_in_place, 0);
2375     // The epoch of the current bias is not valid, attempt to rebias the object
2376     // toward the current thread.
2377     rebiased_region->init_req(2, epoch_ctrl);
2378     old_phi->init_req(2, mark_node);
2379     new_phi->init_req(2, o_node);
2380 
2381     // rebiased_region->in(1) is set to fast path.
2382     // The epoch of the current bias is still valid but we know
2383     // nothing about the owner; it might be set or it might be clear.
2384     Node* cmask   = MakeConX(markWord::biased_lock_mask_in_place |
2385                              markWord::age_mask_in_place |
2386                              markWord::epoch_mask_in_place);
2387     Node* old = transform_later(new AndXNode(mark_node, cmask));
2388     cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2389     Node* new_mark = transform_later(new OrXNode(cast_thread, old));
2390     old_phi->init_req(1, old);
2391     new_phi->init_req(1, new_mark);
2392 
2393     transform_later(rebiased_region);
2394     transform_later(old_phi);
2395     transform_later(new_phi);
2396 
2397     // Try to acquire the bias of the object using an atomic operation.
2398     // If this fails we will go in to the runtime to revoke the object's bias.
2399     cas = new StoreXConditionalNode(rebiased_region, mem, adr, new_phi, old_phi);
2400     transform_later(cas);
2401     proj = transform_later(new SCMemProjNode(cas));
2402 
2403     // Get slow path - Failed to CAS.
2404     not_biased_ctrl = opt_bits_test(rebiased_region, region, 4, cas, 0, 0);
2405     mem_phi->init_req(4, proj);
2406     // region->in(4) is set to fast path - the object is rebiased to the current thread.
2407 
2408     // Failed to CAS.
2409     slow_path  = new RegionNode(3);
2410     Node *slow_mem = new PhiNode( slow_path, Type::MEMORY, TypeRawPtr::BOTTOM);
2411 
2412     slow_path->init_req(1, not_biased_ctrl); // Capture slow-control
2413     slow_mem->init_req(1, proj);
2414 
2415     // Call CAS-based locking scheme (FastLock node).
2416 
2417     transform_later(fast_lock_region);
2418     transform_later(fast_lock_mem_phi);
2419 
2420     // Get slow path - FastLock failed to lock the object.
2421     ctrl = opt_bits_test(fast_lock_region, region, 2, flock, 0, 0);
2422     mem_phi->init_req(2, fast_lock_mem_phi);
2423     // region->in(2) is set to fast path - the object is locked to the current thread.
2424 
2425     slow_path->init_req(2, ctrl); // Capture slow-control
2426     slow_mem->init_req(2, fast_lock_mem_phi);
2427 
2428     transform_later(slow_path);
2429     transform_later(slow_mem);
2430     // Reset lock's memory edge.
2431     lock->set_req(TypeFunc::Memory, slow_mem);
2432 
2433   } else {
2434     region  = new RegionNode(3);
2435     // create a Phi for the memory state
2436     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2437 
2438     // Optimize test; set region slot 2
2439     slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2440     mem_phi->init_req(2, mem);
2441   }
2442 
2443   // Make slow path call
2444   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2445                                   OptoRuntime::complete_monitor_locking_Java(), NULL, slow_path,
2446                                   obj, box, NULL);
2447 
2448   extract_call_projections(call);
2449 
2450   // Slow path can only throw asynchronous exceptions, which are always
2451   // de-opted.  So the compiler thinks the slow-call can never throw an
2452   // exception.  If it DOES throw an exception we would need the debug
2453   // info removed first (since if it throws there is no monitor).
2454   assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
2455            _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
2456 
2457   // Capture slow path
2458   // disconnect fall-through projection from call and create a new one
2459   // hook up users of fall-through projection to region
2460   Node *slow_ctrl = _fallthroughproj->clone();
2461   transform_later(slow_ctrl);
2462   _igvn.hash_delete(_fallthroughproj);
2463   _fallthroughproj->disconnect_inputs(NULL, C);
2464   region->init_req(1, slow_ctrl);
2465   // region inputs are now complete
2466   transform_later(region);
2467   _igvn.replace_node(_fallthroughproj, region);
2468 
2469   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2470   mem_phi->init_req(1, memproj );
2471   transform_later(mem_phi);
2472   _igvn.replace_node(_memproj_fallthrough, mem_phi);
2473 }
2474 
2475 //------------------------------expand_unlock_node----------------------
2476 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2477 
2478   Node* ctrl = unlock->in(TypeFunc::Control);
2479   Node* mem = unlock->in(TypeFunc::Memory);
2480   Node* obj = unlock->obj_node();
2481   Node* box = unlock->box_node();
2482 
2483   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2484 
2485   // No need for a null check on unlock
2486 
2487   // Make the merge point
2488   Node *region;
2489   Node *mem_phi;
2490 
2491   if (UseOptoBiasInlining) {
2492     // Check for biased locking unlock case, which is a no-op.
2493     // See the full description in MacroAssembler::biased_locking_exit().
2494     region  = new RegionNode(4);
2495     // create a Phi for the memory state
2496     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2497     mem_phi->init_req(3, mem);
2498 
2499     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2500     ctrl = opt_bits_test(ctrl, region, 3, mark_node,
2501                          markWord::biased_lock_mask_in_place,
2502                          markWord::biased_lock_pattern);
2503   } else {
2504     region  = new RegionNode(3);
2505     // create a Phi for the memory state
2506     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2507   }
2508 
2509   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2510   funlock = transform_later( funlock )->as_FastUnlock();
2511   // Optimize test; set region slot 2
2512   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2513   Node *thread = transform_later(new ThreadLocalNode());
2514 
2515   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2516                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2517                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2518 
2519   extract_call_projections(call);
2520 
2521   assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
2522            _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
2523 
2524   // No exceptions for unlocking
2525   // Capture slow path
2526   // disconnect fall-through projection from call and create a new one
2527   // hook up users of fall-through projection to region
2528   Node *slow_ctrl = _fallthroughproj->clone();
2529   transform_later(slow_ctrl);
2530   _igvn.hash_delete(_fallthroughproj);
2531   _fallthroughproj->disconnect_inputs(NULL, C);
2532   region->init_req(1, slow_ctrl);
2533   // region inputs are now complete
2534   transform_later(region);
2535   _igvn.replace_node(_fallthroughproj, region);
2536 
2537   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2538   mem_phi->init_req(1, memproj );
2539   mem_phi->init_req(2, mem);
2540   transform_later(mem_phi);
2541   _igvn.replace_node(_memproj_fallthrough, mem_phi);
2542 }
2543 
2544 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2545   assert(check->in(SubTypeCheckNode::Control) == NULL, "should be pinned");
2546   Node* bol = check->unique_out();
2547   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2548   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2549   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2550 
2551   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2552     Node* iff = bol->last_out(i);
2553     assert(iff->is_If(), "where's the if?");
2554 
2555     if (iff->in(0)->is_top()) {
2556       _igvn.replace_input_of(iff, 1, C->top());
2557       continue;
2558     }
2559 
2560     Node* iftrue = iff->as_If()->proj_out(1);
2561     Node* iffalse = iff->as_If()->proj_out(0);
2562     Node* ctrl = iff->in(0);
2563 
2564     Node* subklass = NULL;
2565     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2566       subklass = obj_or_subklass;
2567     } else {
2568       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2569       subklass = _igvn.transform(LoadKlassNode::make(_igvn, NULL, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2570     }
2571 
2572     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, NULL, _igvn);
2573 
2574     _igvn.replace_input_of(iff, 0, C->top());
2575     _igvn.replace_node(iftrue, not_subtype_ctrl);
2576     _igvn.replace_node(iffalse, ctrl);
2577   }
2578   _igvn.replace_node(check, C->top());
2579 }
2580 
2581 //---------------------------eliminate_macro_nodes----------------------
2582 // Eliminate scalar replaced allocations and associated locks.
2583 void PhaseMacroExpand::eliminate_macro_nodes() {
2584   if (C->macro_count() == 0)
2585     return;
2586 
2587   // First, attempt to eliminate locks
2588   int cnt = C->macro_count();
2589   for (int i=0; i < cnt; i++) {
2590     Node *n = C->macro_node(i);
2591     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2592       // Before elimination mark all associated (same box and obj)
2593       // lock and unlock nodes.
2594       mark_eliminated_locking_nodes(n->as_AbstractLock());
2595     }
2596   }
2597   bool progress = true;
2598   while (progress) {
2599     progress = false;
2600     for (int i = C->macro_count(); i > 0; i--) {
2601       Node * n = C->macro_node(i-1);
2602       bool success = false;
2603       debug_only(int old_macro_count = C->macro_count(););
2604       if (n->is_AbstractLock()) {
2605         success = eliminate_locking_node(n->as_AbstractLock());
2606       }
2607       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2608       progress = progress || success;
2609     }
2610   }
2611   // Next, attempt to eliminate allocations
2612   _has_locks = false;
2613   progress = true;
2614   while (progress) {
2615     progress = false;
2616     for (int i = C->macro_count(); i > 0; i--) {
2617       Node * n = C->macro_node(i-1);
2618       bool success = false;
2619       debug_only(int old_macro_count = C->macro_count(););
2620       switch (n->class_id()) {
2621       case Node::Class_Allocate:
2622       case Node::Class_AllocateArray:
2623         success = eliminate_allocate_node(n->as_Allocate());
2624         break;
2625       case Node::Class_CallStaticJava:
2626         success = eliminate_boxing_node(n->as_CallStaticJava());
2627         break;
2628       case Node::Class_Lock:
2629       case Node::Class_Unlock:
2630         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2631         _has_locks = true;
2632         break;
2633       case Node::Class_ArrayCopy:
2634         break;
2635       case Node::Class_OuterStripMinedLoop:
2636         break;
2637       case Node::Class_SubTypeCheck:
2638         break;
2639       case Node::Class_Opaque1:
2640         break;
2641       default:
2642         assert(n->Opcode() == Op_LoopLimit ||
2643                n->Opcode() == Op_Opaque2   ||
2644                n->Opcode() == Op_Opaque3   ||
2645                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2646                "unknown node type in macro list");
2647       }
2648       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2649       progress = progress || success;
2650     }
2651   }
2652 }
2653 
2654 //------------------------------expand_macro_nodes----------------------
2655 //  Returns true if a failure occurred.
2656 bool PhaseMacroExpand::expand_macro_nodes() {
2657   // Last attempt to eliminate macro nodes.
2658   eliminate_macro_nodes();
2659 
2660   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2661   bool progress = true;
2662   while (progress) {
2663     progress = false;
2664     for (int i = C->macro_count(); i > 0; i--) {
2665       Node* n = C->macro_node(i-1);
2666       bool success = false;
2667       debug_only(int old_macro_count = C->macro_count(););
2668       if (n->Opcode() == Op_LoopLimit) {
2669         // Remove it from macro list and put on IGVN worklist to optimize.
2670         C->remove_macro_node(n);
2671         _igvn._worklist.push(n);
2672         success = true;
2673       } else if (n->Opcode() == Op_CallStaticJava) {
2674         // Remove it from macro list and put on IGVN worklist to optimize.
2675         C->remove_macro_node(n);
2676         _igvn._worklist.push(n);
2677         success = true;
2678       } else if (n->is_Opaque1() || n->Opcode() == Op_Opaque2) {
2679         _igvn.replace_node(n, n->in(1));
2680         success = true;
2681 #if INCLUDE_RTM_OPT
2682       } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2683         assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2684         assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2685         Node* cmp = n->unique_out();
2686 #ifdef ASSERT
2687         // Validate graph.
2688         assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2689         BoolNode* bol = cmp->unique_out()->as_Bool();
2690         assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2691                (bol->_test._test == BoolTest::ne), "");
2692         IfNode* ifn = bol->unique_out()->as_If();
2693         assert((ifn->outcnt() == 2) &&
2694                ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != NULL, "");
2695 #endif
2696         Node* repl = n->in(1);
2697         if (!_has_locks) {
2698           // Remove RTM state check if there are no locks in the code.
2699           // Replace input to compare the same value.
2700           repl = (cmp->in(1) == n) ? cmp->in(2) : cmp->in(1);
2701         }
2702         _igvn.replace_node(n, repl);
2703         success = true;
2704 #endif
2705       } else if (n->Opcode() == Op_OuterStripMinedLoop) {
2706         n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
2707         C->remove_macro_node(n);
2708         success = true;
2709       }
2710       assert(!success || (C->macro_count() == (old_macro_count - 1)), "elimination must have deleted one node from macro list");
2711       progress = progress || success;
2712     }
2713   }
2714 
2715   // Clean up the graph so we're less likely to hit the maximum node
2716   // limit
2717   _igvn.set_delay_transform(false);
2718   _igvn.optimize();
2719   if (C->failing())  return true;
2720   _igvn.set_delay_transform(true);
2721 
2722 
2723   // Because we run IGVN after each expansion, some macro nodes may go
2724   // dead and be removed from the list as we iterate over it. Move
2725   // Allocate nodes (processed in a second pass) at the beginning of
2726   // the list and then iterate from the last element of the list until
2727   // an Allocate node is seen. This is robust to random deletion in
2728   // the list due to nodes going dead.
2729   C->sort_macro_nodes();
2730 
2731   // expand arraycopy "macro" nodes first
2732   // For ReduceBulkZeroing, we must first process all arraycopy nodes
2733   // before the allocate nodes are expanded.
2734   while (C->macro_count() > 0) {
2735     int macro_count = C->macro_count();
2736     Node * n = C->macro_node(macro_count-1);
2737     assert(n->is_macro(), "only macro nodes expected here");
2738     if (_igvn.type(n) == Type::TOP || (n->in(0) != NULL && n->in(0)->is_top())) {
2739       // node is unreachable, so don't try to expand it
2740       C->remove_macro_node(n);
2741       continue;
2742     }
2743     if (n->is_Allocate()) {
2744       break;
2745     }
2746     // Make sure expansion will not cause node limit to be exceeded.
2747     // Worst case is a macro node gets expanded into about 200 nodes.
2748     // Allow 50% more for optimization.
2749     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2750       return true;
2751     }
2752 
2753     debug_only(int old_macro_count = C->macro_count(););
2754     switch (n->class_id()) {
2755     case Node::Class_Lock:
2756       expand_lock_node(n->as_Lock());
2757       assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2758       break;
2759     case Node::Class_Unlock:
2760       expand_unlock_node(n->as_Unlock());
2761       assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2762       break;
2763     case Node::Class_ArrayCopy:
2764       expand_arraycopy_node(n->as_ArrayCopy());
2765       assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2766       break;
2767     case Node::Class_SubTypeCheck:
2768       expand_subtypecheck_node(n->as_SubTypeCheck());
2769       assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2770       break;
2771     default:
2772       assert(false, "unknown node type in macro list");
2773     }
2774     assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2775     if (C->failing())  return true;
2776 
2777     // Clean up the graph so we're less likely to hit the maximum node
2778     // limit
2779     _igvn.set_delay_transform(false);
2780     _igvn.optimize();
2781     if (C->failing())  return true;
2782     _igvn.set_delay_transform(true);
2783   }
2784 
2785   // All nodes except Allocate nodes are expanded now. There could be
2786   // new optimization opportunities (such as folding newly created
2787   // load from a just allocated object). Run IGVN.
2788 
2789   // expand "macro" nodes
2790   // nodes are removed from the macro list as they are processed
2791   while (C->macro_count() > 0) {
2792     int macro_count = C->macro_count();
2793     Node * n = C->macro_node(macro_count-1);
2794     assert(n->is_macro(), "only macro nodes expected here");
2795     if (_igvn.type(n) == Type::TOP || (n->in(0) != NULL && n->in(0)->is_top())) {
2796       // node is unreachable, so don't try to expand it
2797       C->remove_macro_node(n);
2798       continue;
2799     }
2800     // Make sure expansion will not cause node limit to be exceeded.
2801     // Worst case is a macro node gets expanded into about 200 nodes.
2802     // Allow 50% more for optimization.
2803     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2804       return true;
2805     }
2806     switch (n->class_id()) {
2807     case Node::Class_Allocate:
2808       expand_allocate(n->as_Allocate());
2809       break;
2810     case Node::Class_AllocateArray:
2811       expand_allocate_array(n->as_AllocateArray());
2812       break;
2813     default:
2814       assert(false, "unknown node type in macro list");
2815     }
2816     assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2817     if (C->failing())  return true;
2818 
2819     // Clean up the graph so we're less likely to hit the maximum node
2820     // limit
2821     _igvn.set_delay_transform(false);
2822     _igvn.optimize();
2823     if (C->failing())  return true;
2824     _igvn.set_delay_transform(true);
2825   }
2826 
2827   _igvn.set_delay_transform(false);
2828   return false;
2829 }