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