1 /*
   2  * Copyright (c) 2005, 2023, 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 == nullptr) {
  78       break;
  79     }
  80   }
  81   return nreplacements;
  82 }
  83 
  84 void PhaseMacroExpand::migrate_outs(Node *old, Node *target) {
  85   assert(old != nullptr, "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 != nullptr)  call->init_req(TypeFunc::Parms+0, parm0);
 146   if (parm1 != nullptr)  call->init_req(TypeFunc::Parms+1, parm1);
 147   if (parm2 != nullptr)  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 = nullptr;
 188         if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
 189           if (ac != nullptr) {
 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 != nullptr) {
 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 = nullptr;
 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 nullptr;
 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 nullptr;
 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 = nullptr;
 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 = nullptr;
 297       const TypePtr* adr_type = nullptr;
 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 nullptr;
 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 != nullptr) {
 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 nullptr;
 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 != nullptr)
 362     return new_phi;
 363 
 364   if (level <= 0) {
 365     return nullptr; // 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, nullptr);
 372 
 373   // create a new Phi for the value
 374   PhiNode *phi = new PhiNode(mem->in(0), phi_type, nullptr, 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 == nullptr || 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 == nullptr) {
 393         return nullptr;  // 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 == nullptr) {
 410           return nullptr;
 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 nullptr;
 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 == nullptr) {
 422           return nullptr;
 423         }
 424         values.at_put(j, res);
 425       } else {
 426         DEBUG_ONLY( val->dump(); )
 427         assert(false, "unknown node on this path");
 428         return nullptr;  // 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 nullptr;  // 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 == nullptr) {
 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 != nullptr, "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 = nullptr;
 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 == nullptr || n == top || n == mem) {
 488           continue;
 489         } else if (unique_input == nullptr) {
 490           unique_input = n;
 491         } else if (unique_input != n) {
 492           unique_input = top;
 493           break;
 494         }
 495       }
 496       if (unique_input != nullptr && 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 != nullptr) {
 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 != nullptr) {
 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 nullptr;
 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 = nullptr; )
 551   DEBUG_ONLY( Node* disq_node = nullptr; )
 552   bool  can_eliminate = true;
 553 
 554   Node* res = alloc->result_cast();
 555   const TypeOopPtr* res_type = nullptr;
 556   if (res == nullptr) {
 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 == nullptr) {
 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 != nullptr) {
 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 == nullptr || 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 == nullptr)
 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 == nullptr)
 658         alloc->dump();
 659       else
 660         res->dump();
 661 #ifdef ASSERT
 662       if (disq_node != nullptr) {
 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 = nullptr;
 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 = nullptr;
 684 
 685   Node* res = alloc->result_cast();
 686   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
 687   const TypeOopPtr* res_type = nullptr;
 688   if (res != nullptr) { // Could be null when there are no users
 689     res_type = _igvn.type(res)->isa_oopptr();
 690   }
 691 
 692   if (res != nullptr) {
 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() != nullptr, "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 = nullptr;
 733       if (iklass != nullptr) {
 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 != nullptr && 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 != nullptr, "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 == nullptr) {
 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 != nullptr) {
 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 == nullptr)
 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 != nullptr) {
 853     igvn.replace_node(ctl_proj, n->in(0));
 854   }
 855   if (mem_proj != nullptr) {
 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 != nullptr) {
 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 != nullptr && _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 != nullptr) {
 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 == nullptr || 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 != nullptr) {
 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 != nullptr) {
 989     _igvn.replace_node(_callprojs.fallthrough_catchproj, alloc->in(TypeFunc::Control));
 990   }
 991   if (_callprojs.fallthrough_memproj != nullptr) {
 992     _igvn.replace_node(_callprojs.fallthrough_memproj, alloc->in(TypeFunc::Memory));
 993   }
 994   if (_callprojs.catchall_memproj != nullptr) {
 995     _igvn.replace_node(_callprojs.catchall_memproj, C->top());
 996   }
 997   if (_callprojs.fallthrough_ioproj != nullptr) {
 998     _igvn.replace_node(_callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
 999   }
1000   if (_callprojs.catchall_ioproj != nullptr) {
1001     _igvn.replace_node(_callprojs.catchall_ioproj, C->top());
1002   }
1003   if (_callprojs.catchall_catchproj != nullptr) {
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 != nullptr))) {
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 == nullptr, "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 != nullptr) {
1052     log->head("eliminate_allocation type='%d'",
1053               log->identify(tklass->klass()));
1054     JVMState* p = alloc->jvms();
1055     while (p != nullptr) {
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) != nullptr) {
1079     return false;
1080   }
1081 
1082   assert(boxing->result_cast() == nullptr, "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 != nullptr, "sanity");
1090 
1091   CompileLog* log = C->log();
1092   if (log != nullptr) {
1093     log->head("eliminate_boxing type='%d'",
1094               log->identify(t->klass()));
1095     JVMState* p = boxing->jvms();
1096     while (p != nullptr) {
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, nullptr, 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             Node* valid_length_test // whether length is valid or not
1210     )
1211 {
1212   Node* ctrl = alloc->in(TypeFunc::Control);
1213   Node* mem  = alloc->in(TypeFunc::Memory);
1214   Node* i_o  = alloc->in(TypeFunc::I_O);
1215   Node* size_in_bytes     = alloc->in(AllocateNode::AllocSize);
1216   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
1217   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1218   assert(ctrl != nullptr, "must have control");
1219 
1220   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1221   // they will not be used if "always_slow" is set
1222   enum { slow_result_path = 1, fast_result_path = 2 };
1223   Node *result_region = nullptr;
1224   Node *result_phi_rawmem = nullptr;
1225   Node *result_phi_rawoop = nullptr;
1226   Node *result_phi_i_o = nullptr;
1227 
1228   // The initial slow comparison is a size check, the comparison
1229   // we want to do is a BoolTest::gt
1230   bool expand_fast_path = true;
1231   int tv = _igvn.find_int_con(initial_slow_test, -1);
1232   if (tv >= 0) {
1233     // InitialTest has constant result
1234     //   0 - can fit in TLAB
1235     //   1 - always too big or negative
1236     assert(tv <= 1, "0 or 1 if a constant");
1237     expand_fast_path = (tv == 0);
1238     initial_slow_test = nullptr;
1239   } else {
1240     initial_slow_test = BoolNode::make_predicate(initial_slow_test, &_igvn);
1241   }
1242 
1243   if (C->env()->dtrace_alloc_probes() ||
1244       (!UseTLAB && !Universe::heap()->supports_inline_contig_alloc())) {
1245     // Force slow-path allocation
1246     expand_fast_path = false;
1247     initial_slow_test = nullptr;
1248   }
1249 
1250   bool allocation_has_use = (alloc->result_cast() != nullptr);
1251   if (!allocation_has_use) {
1252     InitializeNode* init = alloc->initialization();
1253     if (init != nullptr) {
1254       init->remove(&_igvn);
1255     }
1256     if (expand_fast_path && (initial_slow_test == nullptr)) {
1257       // Remove allocation node and return.
1258       // Size is a non-negative constant -> no initial check needed -> directly to fast path.
1259       // Also, no usages -> empty fast path -> no fall out to slow path -> nothing left.
1260 #ifndef PRODUCT
1261       if (PrintEliminateAllocations) {
1262         tty->print("NotUsed ");
1263         Node* res = alloc->proj_out_or_null(TypeFunc::Parms);
1264         if (res != nullptr) {
1265           res->dump();
1266         } else {
1267           alloc->dump();
1268         }
1269       }
1270 #endif
1271       yank_alloc_node(alloc);
1272       return;
1273     }
1274   }
1275 
1276   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1277   Node *slow_region = nullptr;
1278   Node *toobig_false = ctrl;
1279 
1280   // generate the initial test if necessary
1281   if (initial_slow_test != nullptr ) {
1282     assert (expand_fast_path, "Only need test if there is a fast path");
1283     slow_region = new RegionNode(3);
1284 
1285     // Now make the initial failure test.  Usually a too-big test but
1286     // might be a TRUE for finalizers or a fancy class check for
1287     // newInstance0.
1288     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1289     transform_later(toobig_iff);
1290     // Plug the failing-too-big test into the slow-path region
1291     Node *toobig_true = new IfTrueNode( toobig_iff );
1292     transform_later(toobig_true);
1293     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1294     toobig_false = new IfFalseNode( toobig_iff );
1295     transform_later(toobig_false);
1296   } else {
1297     // No initial test, just fall into next case
1298     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1299     toobig_false = ctrl;
1300     debug_only(slow_region = NodeSentinel);
1301   }
1302 
1303   // If we are here there are several possibilities
1304   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1305   // no_initial_check means a constant allocation.
1306   // - If check always evaluates to false -> expand_fast_path is false (see above)
1307   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1308   // if !allocation_has_use the fast path is empty
1309   // if !allocation_has_use && no_initial_check
1310   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1311   //   removed by yank_alloc_node above.
1312 
1313   Node *slow_mem = mem;  // save the current memory state for slow path
1314   // generate the fast allocation code unless we know that the initial test will always go slow
1315   if (expand_fast_path) {
1316     // Fast path modifies only raw memory.
1317     if (mem->is_MergeMem()) {
1318       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1319     }
1320 
1321     // allocate the Region and Phi nodes for the result
1322     result_region = new RegionNode(3);
1323     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1324     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1325 
1326     // Grab regular I/O before optional prefetch may change it.
1327     // Slow-path does no I/O so just set it to the original I/O.
1328     result_phi_i_o->init_req(slow_result_path, i_o);
1329 
1330     // Name successful fast-path variables
1331     Node* fast_oop_ctrl;
1332     Node* fast_oop_rawmem;
1333     if (allocation_has_use) {
1334       Node* needgc_ctrl = nullptr;
1335       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1336 
1337       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1338       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1339       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1340                                         fast_oop_ctrl, fast_oop_rawmem,
1341                                         prefetch_lines);
1342 
1343       if (initial_slow_test != nullptr) {
1344         // This completes all paths into the slow merge point
1345         slow_region->init_req(need_gc_path, needgc_ctrl);
1346         transform_later(slow_region);
1347       } else {
1348         // No initial slow path needed!
1349         // Just fall from the need-GC path straight into the VM call.
1350         slow_region = needgc_ctrl;
1351       }
1352 
1353       InitializeNode* init = alloc->initialization();
1354       fast_oop_rawmem = initialize_object(alloc,
1355                                           fast_oop_ctrl, fast_oop_rawmem, fast_oop,
1356                                           klass_node, length, size_in_bytes);
1357       expand_initialize_membar(alloc, init, fast_oop_ctrl, fast_oop_rawmem);
1358       expand_dtrace_alloc_probe(alloc, fast_oop, fast_oop_ctrl, fast_oop_rawmem);
1359 
1360       result_phi_rawoop->init_req(fast_result_path, fast_oop);
1361     } else {
1362       assert (initial_slow_test != nullptr, "sanity");
1363       fast_oop_ctrl   = toobig_false;
1364       fast_oop_rawmem = mem;
1365       transform_later(slow_region);
1366     }
1367 
1368     // Plug in the successful fast-path into the result merge point
1369     result_region    ->init_req(fast_result_path, fast_oop_ctrl);
1370     result_phi_i_o   ->init_req(fast_result_path, i_o);
1371     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1372   } else {
1373     slow_region = ctrl;
1374     result_phi_i_o = i_o; // Rename it to use in the following code.
1375   }
1376 
1377   // Generate slow-path call
1378   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1379                                OptoRuntime::stub_name(slow_call_address),
1380                                TypePtr::BOTTOM);
1381   call->init_req(TypeFunc::Control,   slow_region);
1382   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1383   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1384   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1385   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1386 
1387   call->init_req(TypeFunc::Parms+0, klass_node);
1388   if (length != nullptr) {
1389     call->init_req(TypeFunc::Parms+1, length);
1390   }
1391 
1392   // Copy debug information and adjust JVMState information, then replace
1393   // allocate node with the call
1394   call->copy_call_debug_info(&_igvn, alloc);
1395   // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify
1396   // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough
1397   // path dies).
1398   if (valid_length_test != nullptr) {
1399     call->add_req(valid_length_test);
1400   }
1401   if (expand_fast_path) {
1402     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1403   } else {
1404     // Hook i_o projection to avoid its elimination during allocation
1405     // replacement (when only a slow call is generated).
1406     call->set_req(TypeFunc::I_O, result_phi_i_o);
1407   }
1408   _igvn.replace_node(alloc, call);
1409   transform_later(call);
1410 
1411   // Identify the output projections from the allocate node and
1412   // adjust any references to them.
1413   // The control and io projections look like:
1414   //
1415   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1416   //  Allocate                   Catch
1417   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1418   //
1419   //  We are interested in the CatchProj nodes.
1420   //
1421   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1422 
1423   // An allocate node has separate memory projections for the uses on
1424   // the control and i_o paths. Replace the control memory projection with
1425   // result_phi_rawmem (unless we are only generating a slow call when
1426   // both memory projections are combined)
1427   if (expand_fast_path && _callprojs.fallthrough_memproj != nullptr) {
1428     migrate_outs(_callprojs.fallthrough_memproj, result_phi_rawmem);
1429   }
1430   // Now change uses of catchall_memproj to use fallthrough_memproj and delete
1431   // catchall_memproj so we end up with a call that has only 1 memory projection.
1432   if (_callprojs.catchall_memproj != nullptr ) {
1433     if (_callprojs.fallthrough_memproj == nullptr) {
1434       _callprojs.fallthrough_memproj = new ProjNode(call, TypeFunc::Memory);
1435       transform_later(_callprojs.fallthrough_memproj);
1436     }
1437     migrate_outs(_callprojs.catchall_memproj, _callprojs.fallthrough_memproj);
1438     _igvn.remove_dead_node(_callprojs.catchall_memproj);
1439   }
1440 
1441   // An allocate node has separate i_o projections for the uses on the control
1442   // and i_o paths. Always replace the control i_o projection with result i_o
1443   // otherwise incoming i_o become dead when only a slow call is generated
1444   // (it is different from memory projections where both projections are
1445   // combined in such case).
1446   if (_callprojs.fallthrough_ioproj != nullptr) {
1447     migrate_outs(_callprojs.fallthrough_ioproj, result_phi_i_o);
1448   }
1449   // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete
1450   // catchall_ioproj so we end up with a call that has only 1 i_o projection.
1451   if (_callprojs.catchall_ioproj != nullptr ) {
1452     if (_callprojs.fallthrough_ioproj == nullptr) {
1453       _callprojs.fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O);
1454       transform_later(_callprojs.fallthrough_ioproj);
1455     }
1456     migrate_outs(_callprojs.catchall_ioproj, _callprojs.fallthrough_ioproj);
1457     _igvn.remove_dead_node(_callprojs.catchall_ioproj);
1458   }
1459 
1460   // if we generated only a slow call, we are done
1461   if (!expand_fast_path) {
1462     // Now we can unhook i_o.
1463     if (result_phi_i_o->outcnt() > 1) {
1464       call->set_req(TypeFunc::I_O, top());
1465     } else {
1466       assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1467       // Case of new array with negative size known during compilation.
1468       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1469       // following code since call to runtime will throw exception.
1470       // As result there will be no users of i_o after the call.
1471       // Leave i_o attached to this call to avoid problems in preceding graph.
1472     }
1473     return;
1474   }
1475 
1476   if (_callprojs.fallthrough_catchproj != nullptr) {
1477     ctrl = _callprojs.fallthrough_catchproj->clone();
1478     transform_later(ctrl);
1479     _igvn.replace_node(_callprojs.fallthrough_catchproj, result_region);
1480   } else {
1481     ctrl = top();
1482   }
1483   Node *slow_result;
1484   if (_callprojs.resproj == nullptr) {
1485     // no uses of the allocation result
1486     slow_result = top();
1487   } else {
1488     slow_result = _callprojs.resproj->clone();
1489     transform_later(slow_result);
1490     _igvn.replace_node(_callprojs.resproj, result_phi_rawoop);
1491   }
1492 
1493   // Plug slow-path into result merge point
1494   result_region->init_req( slow_result_path, ctrl);
1495   transform_later(result_region);
1496   if (allocation_has_use) {
1497     result_phi_rawoop->init_req(slow_result_path, slow_result);
1498     transform_later(result_phi_rawoop);
1499   }
1500   result_phi_rawmem->init_req(slow_result_path, _callprojs.fallthrough_memproj);
1501   transform_later(result_phi_rawmem);
1502   transform_later(result_phi_i_o);
1503   // This completes all paths into the result merge point
1504 }
1505 
1506 // Remove alloc node that has no uses.
1507 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1508   Node* ctrl = alloc->in(TypeFunc::Control);
1509   Node* mem  = alloc->in(TypeFunc::Memory);
1510   Node* i_o  = alloc->in(TypeFunc::I_O);
1511 
1512   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1513   if (_callprojs.resproj != nullptr) {
1514     for (DUIterator_Fast imax, i = _callprojs.resproj->fast_outs(imax); i < imax; i++) {
1515       Node* use = _callprojs.resproj->fast_out(i);
1516       use->isa_MemBar()->remove(&_igvn);
1517       --imax;
1518       --i; // back up iterator
1519     }
1520     assert(_callprojs.resproj->outcnt() == 0, "all uses must be deleted");
1521     _igvn.remove_dead_node(_callprojs.resproj);
1522   }
1523   if (_callprojs.fallthrough_catchproj != nullptr) {
1524     migrate_outs(_callprojs.fallthrough_catchproj, ctrl);
1525     _igvn.remove_dead_node(_callprojs.fallthrough_catchproj);
1526   }
1527   if (_callprojs.catchall_catchproj != nullptr) {
1528     _igvn.rehash_node_delayed(_callprojs.catchall_catchproj);
1529     _callprojs.catchall_catchproj->set_req(0, top());
1530   }
1531   if (_callprojs.fallthrough_proj != nullptr) {
1532     Node* catchnode = _callprojs.fallthrough_proj->unique_ctrl_out();
1533     _igvn.remove_dead_node(catchnode);
1534     _igvn.remove_dead_node(_callprojs.fallthrough_proj);
1535   }
1536   if (_callprojs.fallthrough_memproj != nullptr) {
1537     migrate_outs(_callprojs.fallthrough_memproj, mem);
1538     _igvn.remove_dead_node(_callprojs.fallthrough_memproj);
1539   }
1540   if (_callprojs.fallthrough_ioproj != nullptr) {
1541     migrate_outs(_callprojs.fallthrough_ioproj, i_o);
1542     _igvn.remove_dead_node(_callprojs.fallthrough_ioproj);
1543   }
1544   if (_callprojs.catchall_memproj != nullptr) {
1545     _igvn.rehash_node_delayed(_callprojs.catchall_memproj);
1546     _callprojs.catchall_memproj->set_req(0, top());
1547   }
1548   if (_callprojs.catchall_ioproj != nullptr) {
1549     _igvn.rehash_node_delayed(_callprojs.catchall_ioproj);
1550     _callprojs.catchall_ioproj->set_req(0, top());
1551   }
1552 #ifndef PRODUCT
1553   if (PrintEliminateAllocations) {
1554     if (alloc->is_AllocateArray()) {
1555       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1556     } else {
1557       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1558     }
1559   }
1560 #endif
1561   _igvn.remove_dead_node(alloc);
1562 }
1563 
1564 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1565                                                 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1566   // If initialization is performed by an array copy, any required
1567   // MemBarStoreStore was already added. If the object does not
1568   // escape no need for a MemBarStoreStore. If the object does not
1569   // escape in its initializer and memory barrier (MemBarStoreStore or
1570   // stronger) is already added at exit of initializer, also no need
1571   // for a MemBarStoreStore. Otherwise we need a MemBarStoreStore
1572   // so that stores that initialize this object can't be reordered
1573   // with a subsequent store that makes this object accessible by
1574   // other threads.
1575   // Other threads include java threads and JVM internal threads
1576   // (for example concurrent GC threads). Current concurrent GC
1577   // implementation: G1 will not scan newly created object,
1578   // so it's safe to skip storestore barrier when allocation does
1579   // not escape.
1580   if (!alloc->does_not_escape_thread() &&
1581     !alloc->is_allocation_MemBar_redundant() &&
1582     (init == nullptr || !init->is_complete_with_arraycopy())) {
1583     if (init == nullptr || init->req() < InitializeNode::RawStores) {
1584       // No InitializeNode or no stores captured by zeroing
1585       // elimination. Simply add the MemBarStoreStore after object
1586       // initialization.
1587       MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1588       transform_later(mb);
1589 
1590       mb->init_req(TypeFunc::Memory, fast_oop_rawmem);
1591       mb->init_req(TypeFunc::Control, fast_oop_ctrl);
1592       fast_oop_ctrl = new ProjNode(mb, TypeFunc::Control);
1593       transform_later(fast_oop_ctrl);
1594       fast_oop_rawmem = new ProjNode(mb, TypeFunc::Memory);
1595       transform_later(fast_oop_rawmem);
1596     } else {
1597       // Add the MemBarStoreStore after the InitializeNode so that
1598       // all stores performing the initialization that were moved
1599       // before the InitializeNode happen before the storestore
1600       // barrier.
1601 
1602       Node* init_ctrl = init->proj_out_or_null(TypeFunc::Control);
1603       Node* init_mem = init->proj_out_or_null(TypeFunc::Memory);
1604 
1605       MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1606       transform_later(mb);
1607 
1608       Node* ctrl = new ProjNode(init, TypeFunc::Control);
1609       transform_later(ctrl);
1610       Node* mem = new ProjNode(init, TypeFunc::Memory);
1611       transform_later(mem);
1612 
1613       // The MemBarStoreStore depends on control and memory coming
1614       // from the InitializeNode
1615       mb->init_req(TypeFunc::Memory, mem);
1616       mb->init_req(TypeFunc::Control, ctrl);
1617 
1618       ctrl = new ProjNode(mb, TypeFunc::Control);
1619       transform_later(ctrl);
1620       mem = new ProjNode(mb, TypeFunc::Memory);
1621       transform_later(mem);
1622 
1623       // All nodes that depended on the InitializeNode for control
1624       // and memory must now depend on the MemBarNode that itself
1625       // depends on the InitializeNode
1626       if (init_ctrl != nullptr) {
1627         _igvn.replace_node(init_ctrl, ctrl);
1628       }
1629       if (init_mem != nullptr) {
1630         _igvn.replace_node(init_mem, mem);
1631       }
1632     }
1633   }
1634 }
1635 
1636 void PhaseMacroExpand::expand_dtrace_alloc_probe(AllocateNode* alloc, Node* oop,
1637                                                 Node*& ctrl, Node*& rawmem) {
1638   if (C->env()->dtrace_extended_probes()) {
1639     // Slow-path call
1640     int size = TypeFunc::Parms + 2;
1641     CallLeafNode *call = new CallLeafNode(OptoRuntime::dtrace_object_alloc_Type(),
1642                                           CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_object_alloc_base),
1643                                           "dtrace_object_alloc",
1644                                           TypeRawPtr::BOTTOM);
1645 
1646     // Get base of thread-local storage area
1647     Node* thread = new ThreadLocalNode();
1648     transform_later(thread);
1649 
1650     call->init_req(TypeFunc::Parms + 0, thread);
1651     call->init_req(TypeFunc::Parms + 1, oop);
1652     call->init_req(TypeFunc::Control, ctrl);
1653     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1654     call->init_req(TypeFunc::Memory , ctrl);
1655     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1656     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1657     transform_later(call);
1658     ctrl = new ProjNode(call, TypeFunc::Control);
1659     transform_later(ctrl);
1660     rawmem = new ProjNode(call, TypeFunc::Memory);
1661     transform_later(rawmem);
1662   }
1663 }
1664 
1665 // Helper for PhaseMacroExpand::expand_allocate_common.
1666 // Initializes the newly-allocated storage.
1667 Node*
1668 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1669                                     Node* control, Node* rawmem, Node* object,
1670                                     Node* klass_node, Node* length,
1671                                     Node* size_in_bytes) {
1672   InitializeNode* init = alloc->initialization();
1673   // Store the klass & mark bits
1674   Node* mark_node = alloc->make_ideal_mark(&_igvn, object, control, rawmem);
1675   if (!mark_node->is_Con()) {
1676     transform_later(mark_node);
1677   }
1678   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1679 
1680   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1681   int header_size = alloc->minimum_header_size();  // conservatively small
1682 
1683   // Array length
1684   if (length != nullptr) {         // Arrays need length field
1685     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1686     // conservatively small header size:
1687     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1688     ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1689     if (k->is_array_klass())    // we know the exact header size in most cases:
1690       header_size = Klass::layout_helper_header_size(k->layout_helper());
1691   }
1692 
1693   // Clear the object body, if necessary.
1694   if (init == nullptr) {
1695     // The init has somehow disappeared; be cautious and clear everything.
1696     //
1697     // This can happen if a node is allocated but an uncommon trap occurs
1698     // immediately.  In this case, the Initialize gets associated with the
1699     // trap, and may be placed in a different (outer) loop, if the Allocate
1700     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1701     // there can be two Allocates to one Initialize.  The answer in all these
1702     // edge cases is safety first.  It is always safe to clear immediately
1703     // within an Allocate, and then (maybe or maybe not) clear some more later.
1704     if (!(UseTLAB && ZeroTLAB)) {
1705       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1706                                             header_size, size_in_bytes,
1707                                             &_igvn);
1708     }
1709   } else {
1710     if (!init->is_complete()) {
1711       // Try to win by zeroing only what the init does not store.
1712       // We can also try to do some peephole optimizations,
1713       // such as combining some adjacent subword stores.
1714       rawmem = init->complete_stores(control, rawmem, object,
1715                                      header_size, size_in_bytes, &_igvn);
1716     }
1717     // We have no more use for this link, since the AllocateNode goes away:
1718     init->set_req(InitializeNode::RawAddress, top());
1719     // (If we keep the link, it just confuses the register allocator,
1720     // who thinks he sees a real use of the address by the membar.)
1721   }
1722 
1723   return rawmem;
1724 }
1725 
1726 // Generate prefetch instructions for next allocations.
1727 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
1728                                         Node*& contended_phi_rawmem,
1729                                         Node* old_eden_top, Node* new_eden_top,
1730                                         intx lines) {
1731    enum { fall_in_path = 1, pf_path = 2 };
1732    if( UseTLAB && AllocatePrefetchStyle == 2 ) {
1733       // Generate prefetch allocation with watermark check.
1734       // As an allocation hits the watermark, we will prefetch starting
1735       // at a "distance" away from watermark.
1736 
1737       Node *pf_region = new RegionNode(3);
1738       Node *pf_phi_rawmem = new PhiNode( pf_region, Type::MEMORY,
1739                                                 TypeRawPtr::BOTTOM );
1740       // I/O is used for Prefetch
1741       Node *pf_phi_abio = new PhiNode( pf_region, Type::ABIO );
1742 
1743       Node *thread = new ThreadLocalNode();
1744       transform_later(thread);
1745 
1746       Node *eden_pf_adr = new AddPNode( top()/*not oop*/, thread,
1747                    _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) );
1748       transform_later(eden_pf_adr);
1749 
1750       Node *old_pf_wm = new LoadPNode(needgc_false,
1751                                    contended_phi_rawmem, eden_pf_adr,
1752                                    TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM,
1753                                    MemNode::unordered);
1754       transform_later(old_pf_wm);
1755 
1756       // check against new_eden_top
1757       Node *need_pf_cmp = new CmpPNode( new_eden_top, old_pf_wm );
1758       transform_later(need_pf_cmp);
1759       Node *need_pf_bol = new BoolNode( need_pf_cmp, BoolTest::ge );
1760       transform_later(need_pf_bol);
1761       IfNode *need_pf_iff = new IfNode( needgc_false, need_pf_bol,
1762                                        PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
1763       transform_later(need_pf_iff);
1764 
1765       // true node, add prefetchdistance
1766       Node *need_pf_true = new IfTrueNode( need_pf_iff );
1767       transform_later(need_pf_true);
1768 
1769       Node *need_pf_false = new IfFalseNode( need_pf_iff );
1770       transform_later(need_pf_false);
1771 
1772       Node *new_pf_wmt = new AddPNode( top(), old_pf_wm,
1773                                     _igvn.MakeConX(AllocatePrefetchDistance) );
1774       transform_later(new_pf_wmt );
1775       new_pf_wmt->set_req(0, need_pf_true);
1776 
1777       Node *store_new_wmt = new StorePNode(need_pf_true,
1778                                        contended_phi_rawmem, eden_pf_adr,
1779                                        TypeRawPtr::BOTTOM, new_pf_wmt,
1780                                        MemNode::unordered);
1781       transform_later(store_new_wmt);
1782 
1783       // adding prefetches
1784       pf_phi_abio->init_req( fall_in_path, i_o );
1785 
1786       Node *prefetch_adr;
1787       Node *prefetch;
1788       uint step_size = AllocatePrefetchStepSize;
1789       uint distance = 0;
1790 
1791       for ( intx i = 0; i < lines; i++ ) {
1792         prefetch_adr = new AddPNode( old_pf_wm, new_pf_wmt,
1793                                             _igvn.MakeConX(distance) );
1794         transform_later(prefetch_adr);
1795         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1796         transform_later(prefetch);
1797         distance += step_size;
1798         i_o = prefetch;
1799       }
1800       pf_phi_abio->set_req( pf_path, i_o );
1801 
1802       pf_region->init_req( fall_in_path, need_pf_false );
1803       pf_region->init_req( pf_path, need_pf_true );
1804 
1805       pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem );
1806       pf_phi_rawmem->init_req( pf_path, store_new_wmt );
1807 
1808       transform_later(pf_region);
1809       transform_later(pf_phi_rawmem);
1810       transform_later(pf_phi_abio);
1811 
1812       needgc_false = pf_region;
1813       contended_phi_rawmem = pf_phi_rawmem;
1814       i_o = pf_phi_abio;
1815    } else if( UseTLAB && AllocatePrefetchStyle == 3 ) {
1816       // Insert a prefetch instruction for each allocation.
1817       // This code is used to generate 1 prefetch instruction per cache line.
1818 
1819       // Generate several prefetch instructions.
1820       uint step_size = AllocatePrefetchStepSize;
1821       uint distance = AllocatePrefetchDistance;
1822 
1823       // Next cache address.
1824       Node *cache_adr = new AddPNode(old_eden_top, old_eden_top,
1825                                      _igvn.MakeConX(step_size + distance));
1826       transform_later(cache_adr);
1827       cache_adr = new CastP2XNode(needgc_false, cache_adr);
1828       transform_later(cache_adr);
1829       // Address is aligned to execute prefetch to the beginning of cache line size
1830       // (it is important when BIS instruction is used on SPARC as prefetch).
1831       Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1));
1832       cache_adr = new AndXNode(cache_adr, mask);
1833       transform_later(cache_adr);
1834       cache_adr = new CastX2PNode(cache_adr);
1835       transform_later(cache_adr);
1836 
1837       // Prefetch
1838       Node *prefetch = new PrefetchAllocationNode( contended_phi_rawmem, cache_adr );
1839       prefetch->set_req(0, needgc_false);
1840       transform_later(prefetch);
1841       contended_phi_rawmem = prefetch;
1842       Node *prefetch_adr;
1843       distance = step_size;
1844       for ( intx i = 1; i < lines; i++ ) {
1845         prefetch_adr = new AddPNode( cache_adr, cache_adr,
1846                                             _igvn.MakeConX(distance) );
1847         transform_later(prefetch_adr);
1848         prefetch = new PrefetchAllocationNode( contended_phi_rawmem, prefetch_adr );
1849         transform_later(prefetch);
1850         distance += step_size;
1851         contended_phi_rawmem = prefetch;
1852       }
1853    } else if( AllocatePrefetchStyle > 0 ) {
1854       // Insert a prefetch for each allocation only on the fast-path
1855       Node *prefetch_adr;
1856       Node *prefetch;
1857       // Generate several prefetch instructions.
1858       uint step_size = AllocatePrefetchStepSize;
1859       uint distance = AllocatePrefetchDistance;
1860       for ( intx i = 0; i < lines; i++ ) {
1861         prefetch_adr = new AddPNode( old_eden_top, new_eden_top,
1862                                             _igvn.MakeConX(distance) );
1863         transform_later(prefetch_adr);
1864         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1865         // Do not let it float too high, since if eden_top == eden_end,
1866         // both might be null.
1867         if( i == 0 ) { // Set control for first prefetch, next follows it
1868           prefetch->init_req(0, needgc_false);
1869         }
1870         transform_later(prefetch);
1871         distance += step_size;
1872         i_o = prefetch;
1873       }
1874    }
1875    return i_o;
1876 }
1877 
1878 
1879 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
1880   expand_allocate_common(alloc, nullptr,
1881                          OptoRuntime::new_instance_Type(),
1882                          OptoRuntime::new_instance_Java(), nullptr);
1883 }
1884 
1885 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
1886   Node* length = alloc->in(AllocateNode::ALength);
1887   Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest);
1888   InitializeNode* init = alloc->initialization();
1889   Node* klass_node = alloc->in(AllocateNode::KlassNode);
1890   ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1891   address slow_call_address;  // Address of slow call
1892   if (init != nullptr && init->is_complete_with_arraycopy() &&
1893       k->is_type_array_klass()) {
1894     // Don't zero type array during slow allocation in VM since
1895     // it will be initialized later by arraycopy in compiled code.
1896     slow_call_address = OptoRuntime::new_array_nozero_Java();
1897   } else {
1898     slow_call_address = OptoRuntime::new_array_Java();
1899   }
1900   expand_allocate_common(alloc, length,
1901                          OptoRuntime::new_array_Type(),
1902                          slow_call_address, valid_length_test);
1903 }
1904 
1905 //-------------------mark_eliminated_box----------------------------------
1906 //
1907 // During EA obj may point to several objects but after few ideal graph
1908 // transformations (CCP) it may point to only one non escaping object
1909 // (but still using phi), corresponding locks and unlocks will be marked
1910 // for elimination. Later obj could be replaced with a new node (new phi)
1911 // and which does not have escape information. And later after some graph
1912 // reshape other locks and unlocks (which were not marked for elimination
1913 // before) are connected to this new obj (phi) but they still will not be
1914 // marked for elimination since new obj has no escape information.
1915 // Mark all associated (same box and obj) lock and unlock nodes for
1916 // elimination if some of them marked already.
1917 void PhaseMacroExpand::mark_eliminated_box(Node* oldbox, Node* obj) {
1918   if (oldbox->as_BoxLock()->is_eliminated()) {
1919     return; // This BoxLock node was processed already.
1920   }
1921   // New implementation (EliminateNestedLocks) has separate BoxLock
1922   // node for each locked region so mark all associated locks/unlocks as
1923   // eliminated even if different objects are referenced in one locked region
1924   // (for example, OSR compilation of nested loop inside locked scope).
1925   if (EliminateNestedLocks ||
1926       oldbox->as_BoxLock()->is_simple_lock_region(nullptr, obj, nullptr)) {
1927     // Box is used only in one lock region. Mark this box as eliminated.
1928     _igvn.hash_delete(oldbox);
1929     oldbox->as_BoxLock()->set_eliminated(); // This changes box's hash value
1930      _igvn.hash_insert(oldbox);
1931 
1932     for (uint i = 0; i < oldbox->outcnt(); i++) {
1933       Node* u = oldbox->raw_out(i);
1934       if (u->is_AbstractLock() && !u->as_AbstractLock()->is_non_esc_obj()) {
1935         AbstractLockNode* alock = u->as_AbstractLock();
1936         // Check lock's box since box could be referenced by Lock's debug info.
1937         if (alock->box_node() == oldbox) {
1938           // Mark eliminated all related locks and unlocks.
1939 #ifdef ASSERT
1940           alock->log_lock_optimization(C, "eliminate_lock_set_non_esc4");
1941 #endif
1942           alock->set_non_esc_obj();
1943         }
1944       }
1945     }
1946     return;
1947   }
1948 
1949   // Create new "eliminated" BoxLock node and use it in monitor debug info
1950   // instead of oldbox for the same object.
1951   BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
1952 
1953   // Note: BoxLock node is marked eliminated only here and it is used
1954   // to indicate that all associated lock and unlock nodes are marked
1955   // for elimination.
1956   newbox->set_eliminated();
1957   transform_later(newbox);
1958 
1959   // Replace old box node with new box for all users of the same object.
1960   for (uint i = 0; i < oldbox->outcnt();) {
1961     bool next_edge = true;
1962 
1963     Node* u = oldbox->raw_out(i);
1964     if (u->is_AbstractLock()) {
1965       AbstractLockNode* alock = u->as_AbstractLock();
1966       if (alock->box_node() == oldbox && alock->obj_node()->eqv_uncast(obj)) {
1967         // Replace Box and mark eliminated all related locks and unlocks.
1968 #ifdef ASSERT
1969         alock->log_lock_optimization(C, "eliminate_lock_set_non_esc5");
1970 #endif
1971         alock->set_non_esc_obj();
1972         _igvn.rehash_node_delayed(alock);
1973         alock->set_box_node(newbox);
1974         next_edge = false;
1975       }
1976     }
1977     if (u->is_FastLock() && u->as_FastLock()->obj_node()->eqv_uncast(obj)) {
1978       FastLockNode* flock = u->as_FastLock();
1979       assert(flock->box_node() == oldbox, "sanity");
1980       _igvn.rehash_node_delayed(flock);
1981       flock->set_box_node(newbox);
1982       next_edge = false;
1983     }
1984 
1985     // Replace old box in monitor debug info.
1986     if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
1987       SafePointNode* sfn = u->as_SafePoint();
1988       JVMState* youngest_jvms = sfn->jvms();
1989       int max_depth = youngest_jvms->depth();
1990       for (int depth = 1; depth <= max_depth; depth++) {
1991         JVMState* jvms = youngest_jvms->of_depth(depth);
1992         int num_mon  = jvms->nof_monitors();
1993         // Loop over monitors
1994         for (int idx = 0; idx < num_mon; idx++) {
1995           Node* obj_node = sfn->monitor_obj(jvms, idx);
1996           Node* box_node = sfn->monitor_box(jvms, idx);
1997           if (box_node == oldbox && obj_node->eqv_uncast(obj)) {
1998             int j = jvms->monitor_box_offset(idx);
1999             _igvn.replace_input_of(u, j, newbox);
2000             next_edge = false;
2001           }
2002         }
2003       }
2004     }
2005     if (next_edge) i++;
2006   }
2007 }
2008 
2009 //-----------------------mark_eliminated_locking_nodes-----------------------
2010 void PhaseMacroExpand::mark_eliminated_locking_nodes(AbstractLockNode *alock) {
2011   if (EliminateNestedLocks) {
2012     if (alock->is_nested()) {
2013        assert(alock->box_node()->as_BoxLock()->is_eliminated(), "sanity");
2014        return;
2015     } else if (!alock->is_non_esc_obj()) { // Not eliminated or coarsened
2016       // Only Lock node has JVMState needed here.
2017       // Not that preceding claim is documented anywhere else.
2018       if (alock->jvms() != nullptr) {
2019         if (alock->as_Lock()->is_nested_lock_region()) {
2020           // Mark eliminated related nested locks and unlocks.
2021           Node* obj = alock->obj_node();
2022           BoxLockNode* box_node = alock->box_node()->as_BoxLock();
2023           assert(!box_node->is_eliminated(), "should not be marked yet");
2024           // Note: BoxLock node is marked eliminated only here
2025           // and it is used to indicate that all associated lock
2026           // and unlock nodes are marked for elimination.
2027           box_node->set_eliminated(); // Box's hash is always NO_HASH here
2028           for (uint i = 0; i < box_node->outcnt(); i++) {
2029             Node* u = box_node->raw_out(i);
2030             if (u->is_AbstractLock()) {
2031               alock = u->as_AbstractLock();
2032               if (alock->box_node() == box_node) {
2033                 // Verify that this Box is referenced only by related locks.
2034                 assert(alock->obj_node()->eqv_uncast(obj), "");
2035                 // Mark all related locks and unlocks.
2036 #ifdef ASSERT
2037                 alock->log_lock_optimization(C, "eliminate_lock_set_nested");
2038 #endif
2039                 alock->set_nested();
2040               }
2041             }
2042           }
2043         } else {
2044 #ifdef ASSERT
2045           alock->log_lock_optimization(C, "eliminate_lock_NOT_nested_lock_region");
2046           if (C->log() != nullptr)
2047             alock->as_Lock()->is_nested_lock_region(C); // rerun for debugging output
2048 #endif
2049         }
2050       }
2051       return;
2052     }
2053     // Process locks for non escaping object
2054     assert(alock->is_non_esc_obj(), "");
2055   } // EliminateNestedLocks
2056 
2057   if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2058     // Look for all locks of this object and mark them and
2059     // corresponding BoxLock nodes as eliminated.
2060     Node* obj = alock->obj_node();
2061     for (uint j = 0; j < obj->outcnt(); j++) {
2062       Node* o = obj->raw_out(j);
2063       if (o->is_AbstractLock() &&
2064           o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2065         alock = o->as_AbstractLock();
2066         Node* box = alock->box_node();
2067         // Replace old box node with new eliminated box for all users
2068         // of the same object and mark related locks as eliminated.
2069         mark_eliminated_box(box, obj);
2070       }
2071     }
2072   }
2073 }
2074 
2075 // we have determined that this lock/unlock can be eliminated, we simply
2076 // eliminate the node without expanding it.
2077 //
2078 // Note:  The membar's associated with the lock/unlock are currently not
2079 //        eliminated.  This should be investigated as a future enhancement.
2080 //
2081 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2082 
2083   if (!alock->is_eliminated()) {
2084     return false;
2085   }
2086 #ifdef ASSERT
2087   if (!alock->is_coarsened()) {
2088     // Check that new "eliminated" BoxLock node is created.
2089     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2090     assert(oldbox->is_eliminated(), "should be done already");
2091   }
2092 #endif
2093 
2094   alock->log_lock_optimization(C, "eliminate_lock");
2095 
2096 #ifndef PRODUCT
2097   if (PrintEliminateLocks) {
2098     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2099   }
2100 #endif
2101 
2102   Node* mem  = alock->in(TypeFunc::Memory);
2103   Node* ctrl = alock->in(TypeFunc::Control);
2104   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2105 
2106   alock->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2107   // There are 2 projections from the lock.  The lock node will
2108   // be deleted when its last use is subsumed below.
2109   assert(alock->outcnt() == 2 &&
2110          _callprojs.fallthrough_proj != nullptr &&
2111          _callprojs.fallthrough_memproj != nullptr,
2112          "Unexpected projections from Lock/Unlock");
2113 
2114   Node* fallthroughproj = _callprojs.fallthrough_proj;
2115   Node* memproj_fallthrough = _callprojs.fallthrough_memproj;
2116 
2117   // The memory projection from a lock/unlock is RawMem
2118   // The input to a Lock is merged memory, so extract its RawMem input
2119   // (unless the MergeMem has been optimized away.)
2120   if (alock->is_Lock()) {
2121     // Seach for MemBarAcquireLock node and delete it also.
2122     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2123     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2124     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2125     Node* memproj = membar->proj_out(TypeFunc::Memory);
2126     _igvn.replace_node(ctrlproj, fallthroughproj);
2127     _igvn.replace_node(memproj, memproj_fallthrough);
2128 
2129     // Delete FastLock node also if this Lock node is unique user
2130     // (a loop peeling may clone a Lock node).
2131     Node* flock = alock->as_Lock()->fastlock_node();
2132     if (flock->outcnt() == 1) {
2133       assert(flock->unique_out() == alock, "sanity");
2134       _igvn.replace_node(flock, top());
2135     }
2136   }
2137 
2138   // Seach for MemBarReleaseLock node and delete it also.
2139   if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2140     MemBarNode* membar = ctrl->in(0)->as_MemBar();
2141     assert(membar->Opcode() == Op_MemBarReleaseLock &&
2142            mem->is_Proj() && membar == mem->in(0), "");
2143     _igvn.replace_node(fallthroughproj, ctrl);
2144     _igvn.replace_node(memproj_fallthrough, mem);
2145     fallthroughproj = ctrl;
2146     memproj_fallthrough = mem;
2147     ctrl = membar->in(TypeFunc::Control);
2148     mem  = membar->in(TypeFunc::Memory);
2149   }
2150 
2151   _igvn.replace_node(fallthroughproj, ctrl);
2152   _igvn.replace_node(memproj_fallthrough, mem);
2153   return true;
2154 }
2155 
2156 
2157 //------------------------------expand_lock_node----------------------
2158 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
2159 
2160   Node* ctrl = lock->in(TypeFunc::Control);
2161   Node* mem = lock->in(TypeFunc::Memory);
2162   Node* obj = lock->obj_node();
2163   Node* box = lock->box_node();
2164   Node* flock = lock->fastlock_node();
2165 
2166   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2167 
2168   // Make the merge point
2169   Node *region;
2170   Node *mem_phi;
2171   Node *slow_path;
2172 
2173   if (UseOptoBiasInlining) {
2174     /*
2175      *  See the full description in MacroAssembler::biased_locking_enter().
2176      *
2177      *  if( (mark_word & biased_lock_mask) == biased_lock_pattern ) {
2178      *    // The object is biased.
2179      *    proto_node = klass->prototype_header;
2180      *    o_node = thread | proto_node;
2181      *    x_node = o_node ^ mark_word;
2182      *    if( (x_node & ~age_mask) == 0 ) { // Biased to the current thread ?
2183      *      // Done.
2184      *    } else {
2185      *      if( (x_node & biased_lock_mask) != 0 ) {
2186      *        // The klass's prototype header is no longer biased.
2187      *        cas(&mark_word, mark_word, proto_node)
2188      *        goto cas_lock;
2189      *      } else {
2190      *        // The klass's prototype header is still biased.
2191      *        if( (x_node & epoch_mask) != 0 ) { // Expired epoch?
2192      *          old = mark_word;
2193      *          new = o_node;
2194      *        } else {
2195      *          // Different thread or anonymous biased.
2196      *          old = mark_word & (epoch_mask | age_mask | biased_lock_mask);
2197      *          new = thread | old;
2198      *        }
2199      *        // Try to rebias.
2200      *        if( cas(&mark_word, old, new) == 0 ) {
2201      *          // Done.
2202      *        } else {
2203      *          goto slow_path; // Failed.
2204      *        }
2205      *      }
2206      *    }
2207      *  } else {
2208      *    // The object is not biased.
2209      *    cas_lock:
2210      *    if( FastLock(obj) == 0 ) {
2211      *      // Done.
2212      *    } else {
2213      *      slow_path:
2214      *      OptoRuntime::complete_monitor_locking_Java(obj);
2215      *    }
2216      *  }
2217      */
2218 
2219     region  = new RegionNode(5);
2220     // create a Phi for the memory state
2221     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2222 
2223     Node* fast_lock_region  = new RegionNode(3);
2224     Node* fast_lock_mem_phi = new PhiNode( fast_lock_region, Type::MEMORY, TypeRawPtr::BOTTOM);
2225 
2226     // First, check mark word for the biased lock pattern.
2227     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2228 
2229     // Get fast path - mark word has the biased lock pattern.
2230     ctrl = opt_bits_test(ctrl, fast_lock_region, 1, mark_node,
2231                          markWord::biased_lock_mask_in_place,
2232                          markWord::biased_lock_pattern, true);
2233     // fast_lock_region->in(1) is set to slow path.
2234     fast_lock_mem_phi->init_req(1, mem);
2235 
2236     // Now check that the lock is biased to the current thread and has
2237     // the same epoch and bias as Klass::_prototype_header.
2238 
2239     // Special-case a fresh allocation to avoid building nodes:
2240     Node* klass_node = AllocateNode::Ideal_klass(obj, &_igvn);
2241     if (klass_node == NULL) {
2242       Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
2243       klass_node = transform_later(LoadKlassNode::make(_igvn, NULL, mem, k_adr, _igvn.type(k_adr)->is_ptr()));
2244 #ifdef _LP64
2245       if (UseCompressedClassPointers && klass_node->is_DecodeNKlass()) {
2246         assert(klass_node->in(1)->Opcode() == Op_LoadNKlass, "sanity");
2247         klass_node->in(1)->init_req(0, ctrl);
2248       } else
2249 #endif
2250       klass_node->init_req(0, ctrl);
2251     }
2252     Node *proto_node = make_load(ctrl, mem, klass_node, in_bytes(Klass::prototype_header_offset()), TypeX_X, TypeX_X->basic_type());
2253 
2254     Node* thread = transform_later(new ThreadLocalNode());
2255     Node* cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2256     Node* o_node = transform_later(new OrXNode(cast_thread, proto_node));
2257     Node* x_node = transform_later(new XorXNode(o_node, mark_node));
2258 
2259     // Get slow path - mark word does NOT match the value.
2260     STATIC_ASSERT(markWord::age_mask_in_place <= INT_MAX);
2261     Node* not_biased_ctrl =  opt_bits_test(ctrl, region, 3, x_node,
2262                                       (~(int)markWord::age_mask_in_place), 0);
2263     // region->in(3) is set to fast path - the object is biased to the current thread.
2264     mem_phi->init_req(3, mem);
2265 
2266 
2267     // Mark word does NOT match the value (thread | Klass::_prototype_header).
2268 
2269 
2270     // First, check biased pattern.
2271     // Get fast path - _prototype_header has the same biased lock pattern.
2272     ctrl =  opt_bits_test(not_biased_ctrl, fast_lock_region, 2, x_node,
2273                           markWord::biased_lock_mask_in_place, 0, true);
2274 
2275     not_biased_ctrl = fast_lock_region->in(2); // Slow path
2276     // fast_lock_region->in(2) - the prototype header is no longer biased
2277     // and we have to revoke the bias on this object.
2278     // We are going to try to reset the mark of this object to the prototype
2279     // value and fall through to the CAS-based locking scheme.
2280     Node* adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
2281     Node* cas = new StoreXConditionalNode(not_biased_ctrl, mem, adr,
2282                                           proto_node, mark_node);
2283     transform_later(cas);
2284     Node* proj = transform_later(new SCMemProjNode(cas));
2285     fast_lock_mem_phi->init_req(2, proj);
2286 
2287 
2288     // Second, check epoch bits.
2289     Node* rebiased_region  = new RegionNode(3);
2290     Node* old_phi = new PhiNode( rebiased_region, TypeX_X);
2291     Node* new_phi = new PhiNode( rebiased_region, TypeX_X);
2292 
2293     // Get slow path - mark word does NOT match epoch bits.
2294     Node* epoch_ctrl =  opt_bits_test(ctrl, rebiased_region, 1, x_node,
2295                                       markWord::epoch_mask_in_place, 0);
2296     // The epoch of the current bias is not valid, attempt to rebias the object
2297     // toward the current thread.
2298     rebiased_region->init_req(2, epoch_ctrl);
2299     old_phi->init_req(2, mark_node);
2300     new_phi->init_req(2, o_node);
2301 
2302     // rebiased_region->in(1) is set to fast path.
2303     // The epoch of the current bias is still valid but we know
2304     // nothing about the owner; it might be set or it might be clear.
2305     Node* cmask   = MakeConX(markWord::biased_lock_mask_in_place |
2306                              markWord::age_mask_in_place |
2307                              markWord::epoch_mask_in_place);
2308     Node* old = transform_later(new AndXNode(mark_node, cmask));
2309     cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2310     Node* new_mark = transform_later(new OrXNode(cast_thread, old));
2311     old_phi->init_req(1, old);
2312     new_phi->init_req(1, new_mark);
2313 
2314     transform_later(rebiased_region);
2315     transform_later(old_phi);
2316     transform_later(new_phi);
2317 
2318     // Try to acquire the bias of the object using an atomic operation.
2319     // If this fails we will go in to the runtime to revoke the object's bias.
2320     cas = new StoreXConditionalNode(rebiased_region, mem, adr, new_phi, old_phi);
2321     transform_later(cas);
2322     proj = transform_later(new SCMemProjNode(cas));
2323 
2324     // Get slow path - Failed to CAS.
2325     not_biased_ctrl = opt_bits_test(rebiased_region, region, 4, cas, 0, 0);
2326     mem_phi->init_req(4, proj);
2327     // region->in(4) is set to fast path - the object is rebiased to the current thread.
2328 
2329     // Failed to CAS.
2330     slow_path  = new RegionNode(3);
2331     Node *slow_mem = new PhiNode( slow_path, Type::MEMORY, TypeRawPtr::BOTTOM);
2332 
2333     slow_path->init_req(1, not_biased_ctrl); // Capture slow-control
2334     slow_mem->init_req(1, proj);
2335 
2336     // Call CAS-based locking scheme (FastLock node).
2337 
2338     transform_later(fast_lock_region);
2339     transform_later(fast_lock_mem_phi);
2340 
2341     // Get slow path - FastLock failed to lock the object.
2342     ctrl = opt_bits_test(fast_lock_region, region, 2, flock, 0, 0);
2343     mem_phi->init_req(2, fast_lock_mem_phi);
2344     // region->in(2) is set to fast path - the object is locked to the current thread.
2345 
2346     slow_path->init_req(2, ctrl); // Capture slow-control
2347     slow_mem->init_req(2, fast_lock_mem_phi);
2348 
2349     transform_later(slow_path);
2350     transform_later(slow_mem);
2351     // Reset lock's memory edge.
2352     lock->set_req(TypeFunc::Memory, slow_mem);
2353 
2354   } else {
2355     region  = new RegionNode(3);
2356     // create a Phi for the memory state
2357     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2358 
2359     // Optimize test; set region slot 2
2360     slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2361     mem_phi->init_req(2, mem);
2362   }
2363 
2364   // Make slow path call
2365   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2366                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2367                                   obj, box, nullptr);
2368 
2369   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2370 
2371   // Slow path can only throw asynchronous exceptions, which are always
2372   // de-opted.  So the compiler thinks the slow-call can never throw an
2373   // exception.  If it DOES throw an exception we would need the debug
2374   // info removed first (since if it throws there is no monitor).
2375   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2376          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2377 
2378   // Capture slow path
2379   // disconnect fall-through projection from call and create a new one
2380   // hook up users of fall-through projection to region
2381   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2382   transform_later(slow_ctrl);
2383   _igvn.hash_delete(_callprojs.fallthrough_proj);
2384   _callprojs.fallthrough_proj->disconnect_inputs(C);
2385   region->init_req(1, slow_ctrl);
2386   // region inputs are now complete
2387   transform_later(region);
2388   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2389 
2390   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2391   mem_phi->init_req(1, memproj );
2392   transform_later(mem_phi);
2393   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2394 }
2395 
2396 //------------------------------expand_unlock_node----------------------
2397 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2398 
2399   Node* ctrl = unlock->in(TypeFunc::Control);
2400   Node* mem = unlock->in(TypeFunc::Memory);
2401   Node* obj = unlock->obj_node();
2402   Node* box = unlock->box_node();
2403 
2404   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2405 
2406   // No need for a null check on unlock
2407 
2408   // Make the merge point
2409   Node *region;
2410   Node *mem_phi;
2411 
2412   if (UseOptoBiasInlining) {
2413     // Check for biased locking unlock case, which is a no-op.
2414     // See the full description in MacroAssembler::biased_locking_exit().
2415     region  = new RegionNode(4);
2416     // create a Phi for the memory state
2417     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2418     mem_phi->init_req(3, mem);
2419 
2420     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2421     ctrl = opt_bits_test(ctrl, region, 3, mark_node,
2422                          markWord::biased_lock_mask_in_place,
2423                          markWord::biased_lock_pattern);
2424   } else {
2425     region  = new RegionNode(3);
2426     // create a Phi for the memory state
2427     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2428   }
2429 
2430   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2431   funlock = transform_later( funlock )->as_FastUnlock();
2432   // Optimize test; set region slot 2
2433   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2434   Node *thread = transform_later(new ThreadLocalNode());
2435 
2436   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2437                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2438                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2439 
2440   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2441   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2442          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2443 
2444   // No exceptions for unlocking
2445   // Capture slow path
2446   // disconnect fall-through projection from call and create a new one
2447   // hook up users of fall-through projection to region
2448   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2449   transform_later(slow_ctrl);
2450   _igvn.hash_delete(_callprojs.fallthrough_proj);
2451   _callprojs.fallthrough_proj->disconnect_inputs(C);
2452   region->init_req(1, slow_ctrl);
2453   // region inputs are now complete
2454   transform_later(region);
2455   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2456 
2457   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2458   mem_phi->init_req(1, memproj );
2459   mem_phi->init_req(2, mem);
2460   transform_later(mem_phi);
2461   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2462 }
2463 
2464 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2465   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2466   Node* bol = check->unique_out();
2467   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2468   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2469   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2470 
2471   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2472     Node* iff = bol->last_out(i);
2473     assert(iff->is_If(), "where's the if?");
2474 
2475     if (iff->in(0)->is_top()) {
2476       _igvn.replace_input_of(iff, 1, C->top());
2477       continue;
2478     }
2479 
2480     Node* iftrue = iff->as_If()->proj_out(1);
2481     Node* iffalse = iff->as_If()->proj_out(0);
2482     Node* ctrl = iff->in(0);
2483 
2484     Node* subklass = nullptr;
2485     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2486       subklass = obj_or_subklass;
2487     } else {
2488       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2489       subklass = _igvn.transform(LoadKlassNode::make(_igvn, nullptr, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2490     }
2491 
2492     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn);
2493 
2494     _igvn.replace_input_of(iff, 0, C->top());
2495     _igvn.replace_node(iftrue, not_subtype_ctrl);
2496     _igvn.replace_node(iffalse, ctrl);
2497   }
2498   _igvn.replace_node(check, C->top());
2499 }
2500 
2501 //---------------------------eliminate_macro_nodes----------------------
2502 // Eliminate scalar replaced allocations and associated locks.
2503 void PhaseMacroExpand::eliminate_macro_nodes() {
2504   if (C->macro_count() == 0)
2505     return;
2506 
2507   // Before elimination may re-mark (change to Nested or NonEscObj)
2508   // all associated (same box and obj) lock and unlock nodes.
2509   int cnt = C->macro_count();
2510   for (int i=0; i < cnt; i++) {
2511     Node *n = C->macro_node(i);
2512     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2513       mark_eliminated_locking_nodes(n->as_AbstractLock());
2514     }
2515   }
2516   // Re-marking may break consistency of Coarsened locks.
2517   if (!C->coarsened_locks_consistent()) {
2518     return; // recompile without Coarsened locks if broken
2519   }
2520 
2521   // First, attempt to eliminate locks
2522   bool progress = true;
2523   while (progress) {
2524     progress = false;
2525     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2526       Node* n = C->macro_node(i - 1);
2527       bool success = false;
2528       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2529       if (n->is_AbstractLock()) {
2530         success = eliminate_locking_node(n->as_AbstractLock());
2531       }
2532       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2533       progress = progress || success;
2534     }
2535   }
2536   // Next, attempt to eliminate allocations
2537   _has_locks = false;
2538   progress = true;
2539   while (progress) {
2540     progress = false;
2541     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2542       Node* n = C->macro_node(i - 1);
2543       bool success = false;
2544       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2545       switch (n->class_id()) {
2546       case Node::Class_Allocate:
2547       case Node::Class_AllocateArray:
2548         success = eliminate_allocate_node(n->as_Allocate());
2549         break;
2550       case Node::Class_CallStaticJava:
2551         success = eliminate_boxing_node(n->as_CallStaticJava());
2552         break;
2553       case Node::Class_Lock:
2554       case Node::Class_Unlock:
2555         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2556         _has_locks = true;
2557         break;
2558       case Node::Class_ArrayCopy:
2559         break;
2560       case Node::Class_OuterStripMinedLoop:
2561         break;
2562       case Node::Class_SubTypeCheck:
2563         break;
2564       case Node::Class_Opaque1:
2565         break;
2566       default:
2567         assert(n->Opcode() == Op_LoopLimit ||
2568                n->Opcode() == Op_Opaque2   ||
2569                n->Opcode() == Op_Opaque3   ||
2570                n->Opcode() == Op_Opaque4   ||
2571                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2572                "unknown node type in macro list");
2573       }
2574       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2575       progress = progress || success;
2576     }
2577   }
2578 }
2579 
2580 //------------------------------expand_macro_nodes----------------------
2581 //  Returns true if a failure occurred.
2582 bool PhaseMacroExpand::expand_macro_nodes() {
2583   // Last attempt to eliminate macro nodes.
2584   eliminate_macro_nodes();
2585   if (C->failing())  return true;
2586 
2587   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2588   bool progress = true;
2589   while (progress) {
2590     progress = false;
2591     for (int i = C->macro_count(); i > 0; i--) {
2592       Node* n = C->macro_node(i-1);
2593       bool success = false;
2594       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2595       if (n->Opcode() == Op_LoopLimit) {
2596         // Remove it from macro list and put on IGVN worklist to optimize.
2597         C->remove_macro_node(n);
2598         _igvn._worklist.push(n);
2599         success = true;
2600       } else if (n->Opcode() == Op_CallStaticJava) {
2601         // Remove it from macro list and put on IGVN worklist to optimize.
2602         C->remove_macro_node(n);
2603         _igvn._worklist.push(n);
2604         success = true;
2605       } else if (n->is_Opaque1() || n->Opcode() == Op_Opaque2) {
2606         _igvn.replace_node(n, n->in(1));
2607         success = true;
2608 #if INCLUDE_RTM_OPT
2609       } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2610         assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2611         assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2612         Node* cmp = n->unique_out();
2613 #ifdef ASSERT
2614         // Validate graph.
2615         assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2616         BoolNode* bol = cmp->unique_out()->as_Bool();
2617         assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2618                (bol->_test._test == BoolTest::ne), "");
2619         IfNode* ifn = bol->unique_out()->as_If();
2620         assert((ifn->outcnt() == 2) &&
2621                ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != nullptr, "");
2622 #endif
2623         Node* repl = n->in(1);
2624         if (!_has_locks) {
2625           // Remove RTM state check if there are no locks in the code.
2626           // Replace input to compare the same value.
2627           repl = (cmp->in(1) == n) ? cmp->in(2) : cmp->in(1);
2628         }
2629         _igvn.replace_node(n, repl);
2630         success = true;
2631 #endif
2632       } else if (n->Opcode() == Op_Opaque4) {
2633         // With Opaque4 nodes, the expectation is that the test of input 1
2634         // is always equal to the constant value of input 2. So we can
2635         // remove the Opaque4 and replace it by input 2. In debug builds,
2636         // leave the non constant test in instead to sanity check that it
2637         // never fails (if it does, that subgraph was constructed so, at
2638         // runtime, a Halt node is executed).
2639 #ifdef ASSERT
2640         _igvn.replace_node(n, n->in(1));
2641 #else
2642         _igvn.replace_node(n, n->in(2));
2643 #endif
2644         success = true;
2645       } else if (n->Opcode() == Op_OuterStripMinedLoop) {
2646         n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
2647         C->remove_macro_node(n);
2648         success = true;
2649       }
2650       assert(!success || (C->macro_count() == (old_macro_count - 1)), "elimination must have deleted one node from macro list");
2651       progress = progress || success;
2652     }
2653   }
2654 
2655   // Clean up the graph so we're less likely to hit the maximum node
2656   // limit
2657   _igvn.set_delay_transform(false);
2658   _igvn.optimize();
2659   if (C->failing())  return true;
2660   _igvn.set_delay_transform(true);
2661 
2662 
2663   // Because we run IGVN after each expansion, some macro nodes may go
2664   // dead and be removed from the list as we iterate over it. Move
2665   // Allocate nodes (processed in a second pass) at the beginning of
2666   // the list and then iterate from the last element of the list until
2667   // an Allocate node is seen. This is robust to random deletion in
2668   // the list due to nodes going dead.
2669   C->sort_macro_nodes();
2670 
2671   // expand arraycopy "macro" nodes first
2672   // For ReduceBulkZeroing, we must first process all arraycopy nodes
2673   // before the allocate nodes are expanded.
2674   while (C->macro_count() > 0) {
2675     int macro_count = C->macro_count();
2676     Node * n = C->macro_node(macro_count-1);
2677     assert(n->is_macro(), "only macro nodes expected here");
2678     if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) {
2679       // node is unreachable, so don't try to expand it
2680       C->remove_macro_node(n);
2681       continue;
2682     }
2683     if (n->is_Allocate()) {
2684       break;
2685     }
2686     // Make sure expansion will not cause node limit to be exceeded.
2687     // Worst case is a macro node gets expanded into about 200 nodes.
2688     // Allow 50% more for optimization.
2689     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2690       return true;
2691     }
2692 
2693     DEBUG_ONLY(int old_macro_count = C->macro_count();)
2694     switch (n->class_id()) {
2695     case Node::Class_Lock:
2696       expand_lock_node(n->as_Lock());
2697       break;
2698     case Node::Class_Unlock:
2699       expand_unlock_node(n->as_Unlock());
2700       break;
2701     case Node::Class_ArrayCopy:
2702       expand_arraycopy_node(n->as_ArrayCopy());
2703       break;
2704     case Node::Class_SubTypeCheck:
2705       expand_subtypecheck_node(n->as_SubTypeCheck());
2706       break;
2707     default:
2708       assert(false, "unknown node type in macro list");
2709     }
2710     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2711     if (C->failing())  return true;
2712 
2713     // Clean up the graph so we're less likely to hit the maximum node
2714     // limit
2715     _igvn.set_delay_transform(false);
2716     _igvn.optimize();
2717     if (C->failing())  return true;
2718     _igvn.set_delay_transform(true);
2719   }
2720 
2721   // All nodes except Allocate nodes are expanded now. There could be
2722   // new optimization opportunities (such as folding newly created
2723   // load from a just allocated object). Run IGVN.
2724 
2725   // expand "macro" nodes
2726   // nodes are removed from the macro list as they are processed
2727   while (C->macro_count() > 0) {
2728     int macro_count = C->macro_count();
2729     Node * n = C->macro_node(macro_count-1);
2730     assert(n->is_macro(), "only macro nodes expected here");
2731     if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) {
2732       // node is unreachable, so don't try to expand it
2733       C->remove_macro_node(n);
2734       continue;
2735     }
2736     // Make sure expansion will not cause node limit to be exceeded.
2737     // Worst case is a macro node gets expanded into about 200 nodes.
2738     // Allow 50% more for optimization.
2739     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2740       return true;
2741     }
2742     switch (n->class_id()) {
2743     case Node::Class_Allocate:
2744       expand_allocate(n->as_Allocate());
2745       break;
2746     case Node::Class_AllocateArray:
2747       expand_allocate_array(n->as_AllocateArray());
2748       break;
2749     default:
2750       assert(false, "unknown node type in macro list");
2751     }
2752     assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2753     if (C->failing())  return true;
2754 
2755     // Clean up the graph so we're less likely to hit the maximum node
2756     // limit
2757     _igvn.set_delay_transform(false);
2758     _igvn.optimize();
2759     if (C->failing())  return true;
2760     _igvn.set_delay_transform(true);
2761   }
2762 
2763   _igvn.set_delay_transform(false);
2764   return false;
2765 }