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