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