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