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