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