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