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