< prev index next >

src/hotspot/share/opto/macro.cpp

Print this page

   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 "compiler/compileLog.hpp"
  26 #include "gc/shared/collectedHeap.inline.hpp"
  27 #include "gc/shared/tlab_globals.hpp"
  28 #include "libadt/vectset.hpp"
  29 #include "memory/universe.hpp"
  30 #include "opto/addnode.hpp"
  31 #include "opto/arraycopynode.hpp"
  32 #include "opto/callnode.hpp"
  33 #include "opto/castnode.hpp"
  34 #include "opto/cfgnode.hpp"
  35 #include "opto/compile.hpp"
  36 #include "opto/convertnode.hpp"
  37 #include "opto/graphKit.hpp"

  38 #include "opto/intrinsicnode.hpp"
  39 #include "opto/locknode.hpp"
  40 #include "opto/loopnode.hpp"
  41 #include "opto/macro.hpp"
  42 #include "opto/memnode.hpp"
  43 #include "opto/narrowptrnode.hpp"
  44 #include "opto/node.hpp"
  45 #include "opto/opaquenode.hpp"

  46 #include "opto/phaseX.hpp"
  47 #include "opto/reachability.hpp"
  48 #include "opto/rootnode.hpp"
  49 #include "opto/runtime.hpp"
  50 #include "opto/subnode.hpp"
  51 #include "opto/subtypenode.hpp"
  52 #include "opto/type.hpp"
  53 #include "prims/jvmtiExport.hpp"
  54 #include "runtime/continuation.hpp"
  55 #include "runtime/sharedRuntime.hpp"

  56 #include "utilities/globalDefinitions.hpp"
  57 #include "utilities/macros.hpp"
  58 #include "utilities/powerOfTwo.hpp"
  59 #if INCLUDE_G1GC
  60 #include "gc/g1/g1ThreadLocalData.hpp"
  61 #endif // INCLUDE_G1GC
  62 
  63 
  64 //
  65 // Replace any references to "oldref" in inputs to "use" with "newref".
  66 // Returns the number of replacements made.
  67 //
  68 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
  69   int nreplacements = 0;
  70   uint req = use->req();
  71   for (uint j = 0; j < use->len(); j++) {
  72     Node *uin = use->in(j);
  73     if (uin == oldref) {
  74       if (j < req)
  75         use->set_req(j, newref);
  76       else
  77         use->set_prec(j, newref);
  78       nreplacements++;
  79     } else if (j >= req && uin == nullptr) {
  80       break;
  81     }
  82   }
  83   return nreplacements;
  84 }
  85 
  86 void PhaseMacroExpand::migrate_outs(Node *old, Node *target) {
  87   assert(old != nullptr, "sanity");
  88   for (DUIterator_Fast imax, i = old->fast_outs(imax); i < imax; i++) {
  89     Node* use = old->fast_out(i);
  90     _igvn.rehash_node_delayed(use);
  91     imax -= replace_input(use, old, target);
  92     // back up iterator
  93     --i;
  94   }
  95   assert(old->outcnt() == 0, "all uses must be deleted");
  96 }
  97 
  98 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word) {
  99   Node* cmp = word;
 100   Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
 101   IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
 102   transform_later(iff);
 103 
 104   // Fast path taken.
 105   Node *fast_taken = transform_later(new IfFalseNode(iff));
 106 
 107   // Fast path not-taken, i.e. slow path
 108   Node *slow_taken = transform_later(new IfTrueNode(iff));
 109 
 110     region->init_req(edge, fast_taken); // Capture fast-control
 111     return slow_taken;
 112 }
 113 
 114 //--------------------copy_predefined_input_for_runtime_call--------------------
 115 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
 116   // Set fixed predefined input arguments

 129   // Slow-path call
 130  CallNode *call = leaf_name
 131    ? (CallNode*)new CallLeafNode      ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
 132    : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), TypeRawPtr::BOTTOM );
 133 
 134   // Slow path call has no side-effects, uses few values
 135   copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
 136   if (parm0 != nullptr)  call->init_req(TypeFunc::Parms+0, parm0);
 137   if (parm1 != nullptr)  call->init_req(TypeFunc::Parms+1, parm1);
 138   if (parm2 != nullptr)  call->init_req(TypeFunc::Parms+2, parm2);
 139   call->copy_call_debug_info(&_igvn, oldcall);
 140   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
 141   _igvn.replace_node(oldcall, call);
 142   transform_later(call);
 143 
 144   return call;
 145 }
 146 
 147 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) {
 148   BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 149   bs->eliminate_gc_barrier(this, p2x);
 150 #ifndef PRODUCT
 151   if (PrintOptoStatistics) {
 152     AtomicAccess::inc(&PhaseMacroExpand::_GC_barriers_removed_counter);
 153   }
 154 #endif
 155 }
 156 
 157 // Search for a memory operation for the specified memory slice.
 158 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
 159   Node *orig_mem = mem;
 160   Node *alloc_mem = alloc->as_Allocate()->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 161   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 162   const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
 163   while (true) {
 164     if (mem == alloc_mem || mem == start_mem ) {
 165       return mem;  // hit one of our sentinels
 166     } else if (mem->is_MergeMem()) {
 167       mem = mem->as_MergeMem()->memory_at(alias_idx);
 168     } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
 169       Node *in = mem->in(0);

 172       if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
 173         return in;
 174       } else if (in->is_Call()) {
 175         CallNode *call = in->as_Call();
 176         if (call->may_modify(tinst, phase)) {
 177           assert(call->is_ArrayCopy(), "ArrayCopy is the only call node that doesn't make allocation escape");
 178           if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
 179             return in;
 180           }
 181         }
 182         mem = in->in(TypeFunc::Memory);
 183       } else if (in->is_MemBar()) {
 184         ArrayCopyNode* ac = nullptr;
 185         if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
 186           if (ac != nullptr) {
 187             assert(ac->is_clonebasic(), "Only basic clone is a non escaping clone");
 188             return ac;
 189           }
 190         }
 191         mem = in->in(TypeFunc::Memory);


 192       } else {
 193 #ifdef ASSERT
 194         in->dump();
 195         mem->dump();
 196         assert(false, "unexpected projection");
 197 #endif
 198       }
 199     } else if (mem->is_Store()) {
 200       const TypePtr* atype = mem->as_Store()->adr_type();
 201       int adr_idx = phase->C->get_alias_index(atype);
 202       if (adr_idx == alias_idx) {
 203         assert(atype->isa_oopptr(), "address type must be oopptr");
 204         int adr_offset = atype->offset();
 205         uint adr_iid = atype->is_oopptr()->instance_id();
 206         // Array elements references have the same alias_idx
 207         // but different offset and different instance_id.
 208         if (adr_offset == offset && adr_iid == alloc->_idx) {
 209           return mem;
 210         }
 211       } else {
 212         assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
 213       }
 214       mem = mem->in(MemNode::Memory);
 215     } else if (mem->is_ClearArray()) {
 216       if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
 217         // Can not bypass initialization of the instance
 218         // we are looking.
 219         DEBUG_ONLY(intptr_t offset;)
 220         assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
 221         InitializeNode* init = alloc->as_Allocate()->initialization();
 222         // We are looking for stored value, return Initialize node
 223         // or memory edge from Allocate node.
 224         if (init != nullptr) {

 229       }
 230       // Otherwise skip it (the call updated 'mem' value).
 231     } else if (mem->Opcode() == Op_SCMemProj) {
 232       mem = mem->in(0);
 233       Node* adr = nullptr;
 234       if (mem->is_LoadStore()) {
 235         adr = mem->in(MemNode::Address);
 236       } else {
 237         assert(mem->Opcode() == Op_EncodeISOArray ||
 238                mem->Opcode() == Op_StrCompressedCopy, "sanity");
 239         adr = mem->in(3); // Destination array
 240       }
 241       const TypePtr* atype = adr->bottom_type()->is_ptr();
 242       int adr_idx = phase->C->get_alias_index(atype);
 243       if (adr_idx == alias_idx) {
 244         DEBUG_ONLY(mem->dump();)
 245         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 246         return nullptr;
 247       }
 248       mem = mem->in(MemNode::Memory);
 249    } else if (mem->Opcode() == Op_StrInflatedCopy) {
 250       Node* adr = mem->in(3); // Destination array
 251       const TypePtr* atype = adr->bottom_type()->is_ptr();
 252       int adr_idx = phase->C->get_alias_index(atype);
 253       if (adr_idx == alias_idx) {
 254         DEBUG_ONLY(mem->dump();)
 255         assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
 256         return nullptr;
 257       }
 258       mem = mem->in(MemNode::Memory);
 259     } else {
 260       return mem;
 261     }
 262     assert(mem != orig_mem, "dead memory loop");
 263   }
 264 }
 265 
 266 // Determine if there is an interfering store between a rematerialization load and an arraycopy that is in the process
 267 // of being elided. Starting from the given rematerialization load this method starts a BFS traversal upwards through
 268 // the memory graph towards the provided ArrayCopyNode. For every node encountered on the traversal, check that it is
 269 // independent from the provided rematerialization. Returns false if every node on the traversal is independent and

 309 // Generate loads from source of the arraycopy for fields of destination needed at a deoptimization point.
 310 // Returns nullptr if the load cannot be created because the arraycopy is not suitable for elimination
 311 // (e.g. copy inside the array with non-constant offsets) or the inputs do not match our assumptions (e.g.
 312 // the arraycopy does not actually write something at the provided offset).
 313 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type* ftype, AllocateNode* alloc) {
 314   assert((ctl == ac->control() && mem == ac->memory()) != (mem != ac->memory() && ctl->is_Proj() && ctl->as_Proj()->is_uncommon_trap_proj()),
 315     "Either the control and memory are the same as for the arraycopy or they are pinned in an uncommon trap.");
 316   BasicType bt = ft;
 317   const Type *type = ftype;
 318   if (ft == T_NARROWOOP) {
 319     bt = T_OBJECT;
 320     type = ftype->make_oopptr();
 321   }
 322   Node* base = ac->in(ArrayCopyNode::Src);
 323   Node* adr = nullptr;
 324   const TypePtr* adr_type = nullptr;
 325 
 326   if (ac->is_clonebasic()) {
 327     assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
 328     adr = _igvn.transform(AddPNode::make_with_base(base, _igvn.MakeConX(offset)));
 329     adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);





 330   } else {
 331     if (!ac->modifies(offset, offset, &_igvn, true)) {
 332       // If the arraycopy does not copy to this offset, we cannot generate a rematerialization load for it.
 333       return nullptr;
 334     }
 335     assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
 336     uint shift = exact_log2(type2aelembytes(bt));
 337     Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
 338     Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
 339     const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
 340     const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
 341 




 342     if (src_pos_t->is_con() && dest_pos_t->is_con()) {
 343       intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
 344       adr = _igvn.transform(AddPNode::make_with_base(base, _igvn.MakeConX(off)));
 345       adr_type = _igvn.type(base)->is_ptr()->add_offset(off);

 346       if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 347         // Don't emit a new load from src if src == dst but try to get the value from memory instead
 348         return value_from_mem(ac, ctl, ft, ftype, adr_type->isa_oopptr(), alloc);
 349       }
 350     } else {





 351       Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 352 #ifdef _LP64
 353       diff = _igvn.transform(new ConvI2LNode(diff));
 354 #endif
 355       diff = _igvn.transform(new LShiftXNode(diff, _igvn.intcon(shift)));
 356 
 357       Node* off = _igvn.transform(new AddXNode(_igvn.MakeConX(offset), diff));
 358       adr = _igvn.transform(AddPNode::make_with_base(base, off));
 359       adr_type = _igvn.type(base)->is_ptr()->add_offset(Type::OffsetBot);
 360       if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 361         // Non constant offset in the array: we can't statically
 362         // determine the value
 363         return nullptr;
 364       }
 365     }
 366   }
 367   assert(adr != nullptr && adr_type != nullptr, "sanity");
 368 
 369   // Create the rematerialization load ...
 370   MergeMemNode* mergemem = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 371   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 372   Node* res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemem, adr, adr_type, type, bt);
 373   assert(res != nullptr, "load should have been created");
 374 
 375   // ... and ensure that pinning the rematerialization load inside the uncommon path is safe.
 376   if (mem != ac->memory() && ctl->is_Proj() && ctl->as_Proj()->is_uncommon_trap_proj() && res->is_Load() &&
 377       has_interfering_store(ac, res->as_Load(), &_igvn)) {
 378     // Not safe: use control and memory from the arraycopy to ensure correct memory state.
 379     _igvn.remove_dead_node(res, PhaseIterGVN::NodeOrigin::Graph); // Clean up the unusable rematerialization load.
 380     return make_arraycopy_load(ac, offset, ac->control(), ac->memory(), ft, ftype, alloc);
 381   }
 382 
 383   if (ftype->isa_narrowoop()) {
 384     // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
 385     res = _igvn.transform(new EncodePNode(res, ftype));
 386   }
 387   return res;
 388 }
 389 
 390 //
 391 // Given a Memory Phi, compute a value Phi containing the values from stores
 392 // on the input paths.
 393 // Note: this function is recursive, its depth is limited by the "level" argument
 394 // Returns the computed Phi, or null if it cannot compute it.
 395 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) {
 396   assert(mem->is_Phi(), "sanity");
 397   int alias_idx = C->get_alias_index(adr_t);
 398   int offset = adr_t->offset();
 399   int instance_id = adr_t->instance_id();
 400 
 401   // Check if an appropriate value phi already exists.
 402   Node* region = mem->in(0);
 403   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
 404     Node* phi = region->fast_out(k);
 405     if (phi->is_Phi() && phi != mem &&
 406         phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
 407       return phi;
 408     }
 409   }
 410   // Check if an appropriate new value phi already exists.
 411   Node* new_phi = value_phis->find(mem->_idx);
 412   if (new_phi != nullptr)
 413     return new_phi;
 414 
 415   if (level <= 0) {
 416     return nullptr; // Give up: phi tree too deep
 417   }
 418   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 419   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 420   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 421 
 422   uint length = mem->req();
 423   GrowableArray <Node *> values(length, length, nullptr);
 424 
 425   // create a new Phi for the value
 426   PhiNode *phi = new PhiNode(mem->in(0), phi_type, nullptr, mem->_idx, instance_id, alias_idx, offset);
 427   transform_later(phi);
 428   value_phis->push(phi, mem->_idx);
 429 
 430   for (uint j = 1; j < length; j++) {
 431     Node *in = mem->in(j);
 432     if (in == nullptr || in->is_top()) {
 433       values.at_put(j, in);
 434     } else  {
 435       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
 436       if (val == start_mem || val == alloc_mem) {
 437         // hit a sentinel, return appropriate 0 value
 438         values.at_put(j, _igvn.zerocon(ft));
 439         continue;





 440       }
 441       if (val->is_Initialize()) {
 442         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 443       }
 444       if (val == nullptr) {
 445         return nullptr;  // can't find a value on this path
 446       }
 447       if (val == mem) {
 448         values.at_put(j, mem);
 449       } else if (val->is_Store()) {
 450         Node* n = val->in(MemNode::ValueIn);
 451         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 452         n = bs->step_over_gc_barrier(n);
 453         if (is_subword_type(ft)) {
 454           n = Compile::narrow_value(ft, n, phi_type, &_igvn, true);
 455         }
 456         values.at_put(j, n);
 457       } else if(val->is_Proj() && val->in(0) == alloc) {
 458         values.at_put(j, _igvn.zerocon(ft));





 459       } else if (val->is_Phi()) {
 460         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 461         if (val == nullptr) {
 462           return nullptr;
 463         }
 464         values.at_put(j, val);
 465       } else if (val->Opcode() == Op_SCMemProj) {
 466         assert(val->in(0)->is_LoadStore() ||
 467                val->in(0)->Opcode() == Op_EncodeISOArray ||
 468                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
 469         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 470         return nullptr;
 471       } else if (val->is_ArrayCopy()) {
 472         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
 473         if (res == nullptr) {
 474           return nullptr;
 475         }
 476         values.at_put(j, res);
 477       } else if (val->is_top()) {
 478         // This indicates that this path into the phi is dead. Top will eventually also propagate into the Region.
 479         // IGVN will clean this up later.
 480         values.at_put(j, val);
 481       } else {
 482         DEBUG_ONLY( val->dump(); )
 483         assert(false, "unknown node on this path");
 484         return nullptr;  // unknown node on this path
 485       }
 486     }
 487   }
 488   // Set Phi's inputs
 489   for (uint j = 1; j < length; j++) {
 490     if (values.at(j) == mem) {
 491       phi->init_req(j, phi);
 492     } else {
 493       phi->init_req(j, values.at(j));
 494     }
 495   }
 496   return phi;
 497 }
 498 
























































 499 // Search the last value stored into the object's field.
 500 Node* PhaseMacroExpand::value_from_mem(Node* origin, Node* ctl, BasicType ft, const Type* ftype, const TypeOopPtr* adr_t, AllocateNode* alloc) {
 501   assert(adr_t->is_known_instance_field(), "instance required");
 502   int instance_id = adr_t->instance_id();
 503   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 504 
 505   int alias_idx = C->get_alias_index(adr_t);
 506   int offset = adr_t->offset();
 507   Node* orig_mem = origin->in(TypeFunc::Memory);
 508   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 509   Node *alloc_ctrl = alloc->in(TypeFunc::Control);
 510   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 511   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 512   VectorSet visited;
 513 
 514   bool done = orig_mem == alloc_mem;
 515   Node *mem = orig_mem;
 516   while (!done) {
 517     if (visited.test_set(mem->_idx)) {
 518       return nullptr;  // found a loop, give up
 519     }
 520     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 521     if (mem == start_mem || mem == alloc_mem) {
 522       done = true;  // hit a sentinel, return appropriate 0 value
 523     } else if (mem->is_Initialize()) {
 524       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 525       if (mem == nullptr) {
 526         done = true; // Something go wrong.
 527       } else if (mem->is_Store()) {
 528         const TypePtr* atype = mem->as_Store()->adr_type();
 529         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 530         done = true;
 531       }
 532     } else if (mem->is_Store()) {
 533       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 534       assert(atype != nullptr, "address type must be oopptr");
 535       assert(C->get_alias_index(atype) == alias_idx &&
 536              atype->is_known_instance_field() && atype->offset() == offset &&
 537              atype->instance_id() == instance_id, "store is correct memory slice");
 538       done = true;
 539     } else if (mem->is_Phi()) {
 540       // try to find a phi's unique input
 541       Node *unique_input = nullptr;
 542       Node *top = C->top();
 543       for (uint i = 1; i < mem->req(); i++) {
 544         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 545         if (n == nullptr || n == top || n == mem) {
 546           continue;
 547         } else if (unique_input == nullptr) {
 548           unique_input = n;
 549         } else if (unique_input != n) {
 550           unique_input = top;
 551           break;
 552         }
 553       }
 554       if (unique_input != nullptr && unique_input != top) {
 555         mem = unique_input;
 556       } else {
 557         done = true;
 558       }
 559     } else if (mem->is_ArrayCopy()) {
 560       done = true;
 561     } else if (mem->is_top()) {
 562       // The slice is on a dead path. Returning nullptr would lead to elimination
 563       // bailout, but we want to prevent that. Just forwarding the top is also legal,
 564       // and IGVN can just clean things up, and remove whatever receives top.
 565       return mem;
 566     } else {
 567       DEBUG_ONLY( mem->dump(); )
 568       assert(false, "unexpected node");
 569     }
 570   }
 571   if (mem != nullptr) {
 572     if (mem == start_mem || mem == alloc_mem) {
 573       // hit a sentinel, return appropriate 0 value
 574       return _igvn.zerocon(ft);
 575     } else if (mem->is_Store()) {
 576       Node* n = mem->in(MemNode::ValueIn);
 577       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 578       n = bs->step_over_gc_barrier(n);
 579       return n;
 580     } else if (mem->is_Phi()) {
 581       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 582       Node_Stack value_phis(8);
 583       Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 584       if (phi != nullptr) {
 585         return phi;
 586       } else {
 587         // Kill all new Phis
 588         while(value_phis.is_nonempty()) {
 589           Node* n = value_phis.node();
 590           _igvn.replace_node(n, C->top());
 591           value_phis.pop();
 592         }
 593       }
 594     } else if (mem->is_ArrayCopy()) {
 595       // Rematerialize the scalar-replaced array. If possible, pin the loads to the uncommon path of the uncommon trap.
 596       // Check for each element of the source array, whether it was modified. If not, pin both memory and control to
 597       // the uncommon path. Otherwise, use the control and memory state of the arraycopy. Control and memory state must
 598       // come from the same source to prevent anti-dependence problems in the backend.
 599       ArrayCopyNode* ac = mem->as_ArrayCopy();
 600       Node* ac_ctl = ac->control();
 601       Node* ac_mem = ac->memory();
 602       if (ctl->is_Proj() && ctl->as_Proj()->is_uncommon_trap_proj()) {
 603         // pin the loads in the uncommon trap path
 604         ac_ctl = ctl;
 605         ac_mem = orig_mem;
 606       }
 607       return make_arraycopy_load(ac, offset, ac_ctl, ac_mem, ft, ftype, alloc);
 608     }
 609   }
 610   // Something went wrong.
 611   return nullptr;
 612 }
 613 


















































































 614 // Check the possibility of scalar replacement.
 615 bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode* alloc, Unique_Node_List* safepoints) {
 616   //  Scan the uses of the allocation to check for anything that would
 617   //  prevent us from eliminating it.
 618   NOT_PRODUCT( const char* fail_eliminate = nullptr; )
 619   DEBUG_ONLY( Node* disq_node = nullptr; )
 620   bool can_eliminate = true;
 621   bool reduce_merge_precheck = (safepoints == nullptr);
 622 

 623   Node* res = alloc->result_cast();
 624   const TypeOopPtr* res_type = nullptr;
 625   if (res == nullptr) {
 626     // All users were eliminated.
 627   } else if (!res->is_CheckCastPP()) {
 628     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 629     can_eliminate = false;
 630   } else {

 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   if (can_eliminate && res != nullptr) {
 648     BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 649     for (DUIterator_Fast jmax, j = res->fast_outs(jmax);
 650                                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_Mem() && n->as_Mem()->is_mismatched_access()) {
 666             DEBUG_ONLY(disq_node = n);
 667             NOT_PRODUCT(fail_eliminate = "Mismatched access");
 668             can_eliminate = false;
 669           }
 670           if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n) && !reduce_merge_precheck) {
 671             DEBUG_ONLY(disq_node = n;)
 672             if (n->is_Load() || n->is_LoadStore()) {
 673               NOT_PRODUCT(fail_eliminate = "Field load";)
 674             } else {
 675               NOT_PRODUCT(fail_eliminate = "Not store field reference";)
 676             }
 677             can_eliminate = false;
 678           }
 679         }
 680       } else if (use->is_ArrayCopy() &&
 681                  (use->as_ArrayCopy()->is_clonebasic() ||
 682                   use->as_ArrayCopy()->is_arraycopy_validated() ||
 683                   use->as_ArrayCopy()->is_copyof_validated() ||
 684                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
 685                  use->in(ArrayCopyNode::Dest) == res) {
 686         // ok to eliminate
 687       } else if (use->is_ReachabilityFence() && OptimizeReachabilityFences) {
 688         // ok to eliminate
 689       } else if (use->is_SafePoint()) {
 690         SafePointNode* sfpt = use->as_SafePoint();
 691         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 692           // Object is passed as argument.
 693           DEBUG_ONLY(disq_node = use;)
 694           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 695           can_eliminate = false;
 696         }
 697         Node* sfptMem = sfpt->memory();
 698         if (sfptMem == nullptr || sfptMem->is_top()) {
 699           DEBUG_ONLY(disq_node = use;)
 700           NOT_PRODUCT(fail_eliminate = "null or TOP memory";)
 701           can_eliminate = false;
 702         } else if (!reduce_merge_precheck) {

 703           safepoints->push(sfpt);
 704         }























 705       } else if (reduce_merge_precheck &&
 706                  (use->is_Phi() || use->is_EncodeP() ||
 707                   use->Opcode() == Op_MemBarRelease ||
 708                   (UseStoreStoreForCtor && use->Opcode() == Op_MemBarStoreStore))) {
 709         // Nothing to do
 710       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 711         if (use->is_Phi()) {
 712           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 713             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 714           } else {
 715             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 716           }
 717           DEBUG_ONLY(disq_node = use;)
 718         } else {
 719           if (use->Opcode() == Op_Return) {
 720             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 721           } else {
 722             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 723           }
 724           DEBUG_ONLY(disq_node = use;)
 725         }
 726         can_eliminate = false;



 727       }
 728     }
 729   }
 730 
 731 #ifndef PRODUCT
 732   if (PrintEliminateAllocations && safepoints != nullptr) {
 733     if (can_eliminate) {
 734       tty->print("Scalar ");
 735       if (res == nullptr)
 736         alloc->dump();
 737       else
 738         res->dump();
 739     } else if (alloc->_is_scalar_replaceable) {
 740       tty->print("NotScalar (%s)", fail_eliminate);
 741       if (res == nullptr)
 742         alloc->dump();
 743       else
 744         res->dump();
 745 #ifdef ASSERT
 746       if (disq_node != nullptr) {
 747           tty->print("  >>>> ");
 748           disq_node->dump();
 749       }
 750 #endif /*ASSERT*/
 751     }
 752   }
 753 
 754   if (TraceReduceAllocationMerges && !can_eliminate && reduce_merge_precheck) {
 755     tty->print_cr("\tCan't eliminate allocation because '%s': ", fail_eliminate != nullptr ? fail_eliminate : "");
 756     DEBUG_ONLY(if (disq_node != nullptr) disq_node->dump();)
 757   }
 758 #endif
 759   return can_eliminate;

 833     // CheckCastPP result was not updated in the stack slot, and so
 834     // we ended up using the CastPP. That means that the field knows
 835     // that it should get an oop from an interface, but the value lost
 836     // that information, and so it is not a subtype.
 837     // There may be other issues, feel free to investigate further!
 838     if (!is_java_primitive(value_bt)) { return; }
 839 
 840     tty->print_cr("value not compatible for field: %s vs %s",
 841                   type2name(value_bt),
 842                   type2name(field_bt));
 843     tty->print("value_type: ");
 844     value_type->dump();
 845     tty->cr();
 846     tty->print("field_type: ");
 847     field_type->dump();
 848     tty->cr();
 849     assert(false, "value_type does not fit field_type");
 850   }
 851 #endif
 852 
 853 SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_description(AllocateNode *alloc, SafePointNode* sfpt) {




































































































































































 854   assert(sfpt->jvms()->endoff() == sfpt->req(), "no extra edges past debug info allowed");
 855 
 856   // Fields of scalar objs are referenced only at the end
 857   // of regular debuginfo at the last (youngest) JVMS.
 858   // Record relative start index.
 859   ciInstanceKlass* iklass    = nullptr;
 860   BasicType basic_elem_type  = T_ILLEGAL;
 861   const Type* field_type     = nullptr;
 862   const TypeOopPtr* res_type = nullptr;
 863   int nfields                = 0;
 864   int array_base             = 0;
 865   int element_size           = 0;
 866   uint first_ind             = (sfpt->req() - sfpt->jvms()->scloff());
 867   Node* res                  = alloc->result_cast();
 868 
 869   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
 870   assert(sfpt->jvms() != nullptr, "missed JVMS");

 871 
 872   if (res != nullptr) { // Could be null when there are no users
 873     res_type = _igvn.type(res)->isa_oopptr();
 874 
 875     if (res_type->isa_instptr()) {
 876       // find the fields of the class which will be needed for safepoint debug information
 877       iklass = res_type->is_instptr()->instance_klass();
 878       nfields = iklass->nof_nonstatic_fields();
 879     } else {
 880       // find the array's elements which will be needed for safepoint debug information
 881       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 882       assert(nfields >= 0, "must be an array klass.");
 883       basic_elem_type = res_type->is_aryptr()->elem()->array_element_basic_type();
 884       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 885       element_size = type2aelembytes(basic_elem_type);
 886       field_type = res_type->is_aryptr()->elem();






 887     }
 888   }
 889 
 890   SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type, alloc, first_ind, sfpt->jvms()->depth(), nfields);
 891   sobj->init_req(0, C->root());
 892   transform_later(sobj);
 893 
 894   // Scan object's fields adding an input to the safepoint for each field.
 895   for (int j = 0; j < nfields; j++) {
 896     intptr_t offset;
 897     ciField* field = nullptr;
 898     if (iklass != nullptr) {
 899       field = iklass->nonstatic_field_at(j);
 900       offset = field->offset_in_bytes();
 901       ciType* elem_type = field->type();
 902       basic_elem_type = field->layout_type();
 903 
 904       // The next code is taken from Parse::do_get_xxx().
 905       if (is_reference_type(basic_elem_type)) {
 906         if (!elem_type->is_loaded()) {
 907           field_type = TypeInstPtr::BOTTOM;
 908         } else if (field != nullptr && field->is_static_constant()) {
 909           ciObject* con = field->constant_value().as_object();
 910           // Do not "join" in the previous type; it doesn't add value,
 911           // and may yield a vacuous result if the field is of interface type.
 912           field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 913           assert(field_type != nullptr, "field singleton type must be consistent");
 914         } else {
 915           field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 916         }
 917         if (UseCompressedOops) {
 918           field_type = field_type->make_narrowoop();
 919           basic_elem_type = T_NARROWOOP;
 920         }
 921       } else {
 922         field_type = Type::get_const_basic_type(basic_elem_type);
 923       }
 924     } else {
 925       offset = array_base + j * (intptr_t)element_size;
 926     }
 927 
 928     const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 929 
 930     Node* field_val = value_from_mem(sfpt, sfpt->control(), basic_elem_type, field_type, field_addr_type, alloc);
 931 
 932     // We weren't able to find a value for this field,
 933     // give up on eliminating this allocation.
 934     bool force_scalarization_failure = StressEliminateAllocations &&
 935                                        (C->random() % StressEliminateAllocationsMean == 0);
 936     if (field_val == nullptr || force_scalarization_failure) {
 937       uint last = sfpt->req() - 1;
 938       for (int k = 0;  k < j; k++) {
 939         sfpt->del_req(last--);
 940       }
 941       _igvn._worklist.push(sfpt);
 942 
 943 #ifndef PRODUCT
 944       if (PrintEliminateAllocations) {
 945         tty->print("=== At SafePoint node %d ", sfpt->_idx);
 946         if (field_val == nullptr) {
 947           tty->print_raw("can't find value of ");
 948 
 949           if (field != nullptr) {
 950             tty->print_raw("field: ");
 951             field->print();
 952             int field_idx = C->get_alias_index(field_addr_type);
 953             tty->print(" (alias_idx=%d)", field_idx);
 954           } else { // Array's element
 955             tty->print("array element [%d]", j);
 956           }
 957         } else {
 958           assert(force_scalarization_failure, "sanity");
 959           tty->print_raw("forcibly abort elimination");
 960         }
 961         tty->print(", which prevents elimination of: ");
 962         if (res == nullptr)
 963           alloc->dump();
 964         else
 965           res->dump();
 966       }
 967 #endif
 968 
 969       return nullptr;
 970     }




 971 
 972     if (UseCompressedOops && field_type->isa_narrowoop()) {
 973       // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 974       // to be able scalar replace the allocation.
 975       if (field_val->is_EncodeP()) {
 976         field_val = field_val->in(1);
 977       } else {
 978         field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 979       }
 980     }
 981     DEBUG_ONLY(verify_type_compatability(field_val->bottom_type(), field_type);)
 982     sfpt->add_req(field_val);
 983   }
 984 
 985   sfpt->jvms()->set_endoff(sfpt->req());
 986 
 987   return sobj;
 988 }
 989 
 990 // Do scalar replacement.
 991 bool PhaseMacroExpand::scalar_replacement(AllocateNode* alloc, Unique_Node_List& safepoints) {
 992   Unique_Node_List safepoints_done;
 993   Node* res = alloc->result_cast();
 994   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");




 995 
 996   // Process the safepoint uses

 997   while (safepoints.size() > 0) {
 998     SafePointNode* sfpt = safepoints.pop()->as_SafePoint();
 999 
1000     SafePointNode::NodeEdgeTempStorage non_debug_edges_worklist(igvn());
1001 
1002     // All sfpt inputs are implicitly included into debug info during the scalarization process below.
1003     // Keep non-debug inputs separately, so they stay non-debug.
1004     sfpt->remove_non_debug_edges(non_debug_edges_worklist);
1005 
1006     SafePointScalarObjectNode* sobj = create_scalarized_object_description(alloc, sfpt);
1007 
1008     if (sobj == nullptr) {
1009       sfpt->restore_non_debug_edges(non_debug_edges_worklist);
1010       undo_previous_scalarizations(safepoints_done, alloc);
1011       return false;
1012     }
1013 
1014     // Now make a pass over the debug information replacing any references
1015     // to the allocated object with "sobj"
1016     JVMState *jvms = sfpt->jvms();
1017     sfpt->replace_edges_in_range(res, sobj, jvms->debug_start(), jvms->debug_end(), &_igvn);
1018     non_debug_edges_worklist.remove_edge_if_present(res); // drop scalarized input from non-debug info
1019     sfpt->restore_non_debug_edges(non_debug_edges_worklist);
1020     _igvn._worklist.push(sfpt);
1021 
1022     // keep it for rollback
1023     safepoints_done.push(sfpt);
1024   }
1025 







1026   return true;
1027 }
1028 
1029 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
1030   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
1031   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
1032   if (ctl_proj != nullptr) {
1033     igvn.replace_node(ctl_proj, n->in(0));
1034   }
1035   if (mem_proj != nullptr) {
1036     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
1037   }
1038 }
1039 
1040 // Process users of eliminated allocation.
1041 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc) {

1042   Node* res = alloc->result_cast();
1043   if (res != nullptr) {




1044     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
1045       Node *use = res->last_out(j);
1046       uint oc1 = res->outcnt();
1047 
1048       if (use->is_AddP()) {
1049         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
1050           Node *n = use->last_out(k);
1051           uint oc2 = use->outcnt();
1052           if (n->is_Store()) {
1053 #ifdef ASSERT
1054             // Verify that there is no dependent MemBarVolatile nodes,
1055             // they should be removed during IGVN, see MemBarNode::Ideal().
1056             for (DUIterator_Fast pmax, p = n->fast_outs(pmax);
1057                                        p < pmax; p++) {
1058               Node* mb = n->fast_out(p);
1059               assert(mb->is_Initialize() || !mb->is_MemBar() ||
1060                      mb->req() <= MemBarNode::Precedent ||
1061                      mb->in(MemBarNode::Precedent) != n,
1062                      "MemBarVolatile should be eliminated for non-escaping object");
1063             }
1064 #endif
1065             _igvn.replace_node(n, n->in(MemNode::Memory));
1066           } else {
1067             eliminate_gc_barrier(n);
1068           }
1069           k -= (oc2 - use->outcnt());
1070         }
1071         _igvn.remove_dead_node(use, PhaseIterGVN::NodeOrigin::Graph);
1072       } else if (use->is_ArrayCopy()) {
1073         // Disconnect ArrayCopy node
1074         ArrayCopyNode* ac = use->as_ArrayCopy();
1075         if (ac->is_clonebasic()) {
1076           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
1077           disconnect_projections(ac, _igvn);
1078           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
1079           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
1080           disconnect_projections(membar_before->as_MemBar(), _igvn);
1081           if (membar_after->is_MemBar()) {
1082             disconnect_projections(membar_after->as_MemBar(), _igvn);
1083           }
1084         } else {
1085           assert(ac->is_arraycopy_validated() ||
1086                  ac->is_copyof_validated() ||
1087                  ac->is_copyofrange_validated(), "unsupported");
1088           CallProjections callprojs;
1089           ac->extract_projections(&callprojs, true);
1090 
1091           _igvn.replace_node(callprojs.fallthrough_ioproj, ac->in(TypeFunc::I_O));
1092           _igvn.replace_node(callprojs.fallthrough_memproj, ac->in(TypeFunc::Memory));
1093           _igvn.replace_node(callprojs.fallthrough_catchproj, ac->in(TypeFunc::Control));
1094 
1095           // Set control to top. IGVN will remove the remaining projections
1096           ac->set_req(0, top());
1097           ac->replace_edge(res, top(), &_igvn);
1098 
1099           // Disconnect src right away: it can help find new
1100           // opportunities for allocation elimination
1101           Node* src = ac->in(ArrayCopyNode::Src);
1102           ac->replace_edge(src, top(), &_igvn);
1103           // src can be top at this point if src and dest of the
1104           // arraycopy were the same
1105           if (src->outcnt() == 0 && !src->is_top()) {
1106             _igvn.remove_dead_node(src, PhaseIterGVN::NodeOrigin::Graph);
1107           }
1108         }
1109         _igvn._worklist.push(ac);
























1110       } else if (use->is_ReachabilityFence() && OptimizeReachabilityFences) {
1111         use->as_ReachabilityFence()->clear_referent(_igvn); // redundant fence; will be removed during IGVN
1112       } else {
1113         eliminate_gc_barrier(use);
1114       }
1115       j -= (oc1 - res->outcnt());
1116     }
1117     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1118     _igvn.remove_dead_node(res, PhaseIterGVN::NodeOrigin::Graph);
1119   }
1120 
1121   //
1122   // Process other users of allocation's projections
1123   //
1124   if (_callprojs.resproj != nullptr && _callprojs.resproj->outcnt() != 0) {
1125     // First disconnect stores captured by Initialize node.
1126     // If Initialize node is eliminated first in the following code,
1127     // it will kill such stores and DUIterator_Last will assert.
1128     for (DUIterator_Fast jmax, j = _callprojs.resproj->fast_outs(jmax);  j < jmax; j++) {
1129       Node* use = _callprojs.resproj->fast_out(j);
1130       if (use->is_AddP()) {
1131         // raw memory addresses used only by the initialization
1132         _igvn.replace_node(use, C->top());
1133         --j; --jmax;
1134       }
1135     }
1136     for (DUIterator_Last jmin, j = _callprojs.resproj->last_outs(jmin); j >= jmin; ) {
1137       Node* use = _callprojs.resproj->last_out(j);
1138       uint oc1 = _callprojs.resproj->outcnt();
1139       if (use->is_Initialize()) {
1140         // Eliminate Initialize node.
1141         InitializeNode *init = use->as_Initialize();
1142         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1143         if (ctrl_proj != nullptr) {
1144           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1145 #ifdef ASSERT
1146           // If the InitializeNode has no memory out, it will die, and tmp will become null
1147           Node* tmp = init->in(TypeFunc::Control);
1148           assert(tmp == nullptr || tmp == _callprojs.fallthrough_catchproj, "allocation control projection");
1149 #endif
1150         }
1151         Node* mem = init->in(TypeFunc::Memory);
1152 #ifdef ASSERT
1153         if (init->number_of_projs(TypeFunc::Memory) > 0) {
1154           if (mem->is_MergeMem()) {
1155             assert(mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw) == _callprojs.fallthrough_memproj, "allocation memory projection");
1156           } else {
1157             assert(mem == _callprojs.fallthrough_memproj, "allocation memory projection");
1158           }
1159         }
1160 #endif
1161         init->replace_mem_projs_by(mem, &_igvn);
1162         assert(init->outcnt() == 0, "should only have had a control and some memory projections, and we removed them");




1163       } else  {
1164         assert(false, "only Initialize or AddP expected");
1165       }
1166       j -= (oc1 - _callprojs.resproj->outcnt());
1167     }
1168   }
1169   if (_callprojs.fallthrough_catchproj != nullptr) {
1170     _igvn.replace_node(_callprojs.fallthrough_catchproj, alloc->in(TypeFunc::Control));
1171   }
1172   if (_callprojs.fallthrough_memproj != nullptr) {
1173     _igvn.replace_node(_callprojs.fallthrough_memproj, alloc->in(TypeFunc::Memory));
1174   }
1175   if (_callprojs.catchall_memproj != nullptr) {
1176     _igvn.replace_node(_callprojs.catchall_memproj, C->top());
1177   }
1178   if (_callprojs.fallthrough_ioproj != nullptr) {
1179     _igvn.replace_node(_callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
1180   }
1181   if (_callprojs.catchall_ioproj != nullptr) {
1182     _igvn.replace_node(_callprojs.catchall_ioproj, C->top());
1183   }
1184   if (_callprojs.catchall_catchproj != nullptr) {
1185     _igvn.replace_node(_callprojs.catchall_catchproj, C->top());
1186   }
1187 }
1188 
1189 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1190   // If reallocation fails during deoptimization we'll pop all
1191   // interpreter frames for this compiled frame and that won't play
1192   // nice with JVMTI popframe.
1193   // We avoid this issue by eager reallocation when the popframe request
1194   // is received.
1195   if (!EliminateAllocations || !alloc->_is_non_escaping) {
1196     return false;
1197   }
1198   Node* klass = alloc->in(AllocateNode::KlassNode);
1199   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1200   Node* res = alloc->result_cast();







1201   // Eliminate boxing allocations which are not used
1202   // regardless scalar replaceable status.
1203   bool boxing_alloc = C->eliminate_boxing() &&

1204                       tklass->isa_instklassptr() &&
1205                       tklass->is_instklassptr()->instance_klass()->is_box_klass();
1206   if (!alloc->_is_scalar_replaceable && (!boxing_alloc || (res != nullptr))) {
1207     return false;
1208   }
1209 
1210   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1211 
1212   Unique_Node_List safepoints;
1213   if (!can_eliminate_allocation(&_igvn, alloc, &safepoints)) {
1214     return false;
1215   }
1216 
1217   if (!alloc->_is_scalar_replaceable) {
1218     assert(res == nullptr, "sanity");
1219     // We can only eliminate allocation if all debug info references
1220     // are already replaced with SafePointScalarObject because
1221     // we can't search for a fields value without instance_id.
1222     if (safepoints.size() > 0) {
1223       return false;
1224     }
1225   }
1226 
1227   if (!scalar_replacement(alloc, safepoints)) {
1228     return false;
1229   }
1230 
1231   CompileLog* log = C->log();
1232   if (log != nullptr) {
1233     log->head("eliminate_allocation type='%d'",
1234               log->identify(tklass->exact_klass()));
1235     JVMState* p = alloc->jvms();
1236     while (p != nullptr) {
1237       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1238       p = p->caller();
1239     }
1240     log->tail("eliminate_allocation");
1241   }
1242 
1243   process_users_of_allocation(alloc);
1244 
1245 #ifndef PRODUCT
1246   if (PrintEliminateAllocations) {
1247     if (alloc->is_AllocateArray())
1248       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1249     else
1250       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1251   }
1252 #endif
1253 
1254   return true;
1255 }
1256 
1257 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1258   // EA should remove all uses of non-escaping boxing node.
1259   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != nullptr) {
1260     return false;
1261   }





1262 
1263   assert(boxing->result_cast() == nullptr, "unexpected boxing node result");
1264 
1265   boxing->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1266 
1267   const TypeTuple* r = boxing->tf()->range();
1268   assert(r->cnt() > TypeFunc::Parms, "sanity");
1269   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1270   assert(t != nullptr, "sanity");
1271 
1272   CompileLog* log = C->log();
1273   if (log != nullptr) {










1274     log->head("eliminate_boxing type='%d'",
1275               log->identify(t->instance_klass()));
1276     JVMState* p = boxing->jvms();
1277     while (p != nullptr) {
1278       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1279       p = p->caller();
1280     }
1281     log->tail("eliminate_boxing");
1282   }
1283 
1284   process_users_of_allocation(boxing);
1285 
1286 #ifndef PRODUCT
1287   if (PrintEliminateAllocations) {
1288     tty->print("++++ Eliminated: %d ", boxing->_idx);
1289     boxing->method()->print_short_name(tty);
1290     tty->cr();
1291   }
1292 #endif
1293 
1294   return true;
1295 }
1296 
1297 
1298 Node* PhaseMacroExpand::make_load_raw(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) {
1299   Node* adr = off_heap_plus_addr(base, offset);
1300   const TypePtr* adr_type = adr->bottom_type()->is_ptr();
1301   Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt, MemNode::unordered);
1302   transform_later(value);
1303   return value;
1304 }
1305 
1306 
1307 Node* PhaseMacroExpand::make_store_raw(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) {
1308   Node* adr = off_heap_plus_addr(base, offset);
1309   mem = StoreNode::make(_igvn, ctl, mem, adr, nullptr, value, bt, MemNode::unordered);
1310   transform_later(mem);
1311   return mem;
1312 }
1313 
1314 //=============================================================================
1315 //
1316 //                              A L L O C A T I O N
1317 //

1351 // oop flavor.
1352 //
1353 //=============================================================================
1354 // FastAllocateSizeLimit value is in DOUBLEWORDS.
1355 // Allocations bigger than this always go the slow route.
1356 // This value must be small enough that allocation attempts that need to
1357 // trigger exceptions go the slow route.  Also, it must be small enough so
1358 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
1359 //=============================================================================j//
1360 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
1361 // The allocator will coalesce int->oop copies away.  See comment in
1362 // coalesce.cpp about how this works.  It depends critically on the exact
1363 // code shape produced here, so if you are changing this code shape
1364 // make sure the GC info for the heap-top is correct in and around the
1365 // slow-path call.
1366 //
1367 
1368 void PhaseMacroExpand::expand_allocate_common(
1369             AllocateNode* alloc, // allocation node to be expanded
1370             Node* length,  // array length for an array allocation

1371             const TypeFunc* slow_call_type, // Type of slow call
1372             address slow_call_address,  // Address of slow call
1373             Node* valid_length_test // whether length is valid or not
1374     )
1375 {
1376   Node* ctrl = alloc->in(TypeFunc::Control);
1377   Node* mem  = alloc->in(TypeFunc::Memory);
1378   Node* i_o  = alloc->in(TypeFunc::I_O);
1379   Node* size_in_bytes     = alloc->in(AllocateNode::AllocSize);
1380   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
1381   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1382   assert(ctrl != nullptr, "must have control");
1383 
1384   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1385   // they will not be used if "always_slow" is set
1386   enum { slow_result_path = 1, fast_result_path = 2 };
1387   Node *result_region = nullptr;
1388   Node *result_phi_rawmem = nullptr;
1389   Node *result_phi_rawoop = nullptr;
1390   Node *result_phi_i_o = nullptr;

1435 #endif
1436       yank_alloc_node(alloc);
1437       return;
1438     }
1439   }
1440 
1441   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1442   Node *slow_region = nullptr;
1443   Node *toobig_false = ctrl;
1444 
1445   // generate the initial test if necessary
1446   if (initial_slow_test != nullptr ) {
1447     assert (expand_fast_path, "Only need test if there is a fast path");
1448     slow_region = new RegionNode(3);
1449 
1450     // Now make the initial failure test.  Usually a too-big test but
1451     // might be a TRUE for finalizers.
1452     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1453     transform_later(toobig_iff);
1454     // Plug the failing-too-big test into the slow-path region
1455     Node *toobig_true = new IfTrueNode( toobig_iff );
1456     transform_later(toobig_true);
1457     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1458     toobig_false = new IfFalseNode( toobig_iff );
1459     transform_later(toobig_false);
1460   } else {
1461     // No initial test, just fall into next case
1462     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1463     toobig_false = ctrl;
1464     DEBUG_ONLY(slow_region = NodeSentinel);
1465   }
1466 
1467   // If we are here there are several possibilities
1468   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1469   // no_initial_check means a constant allocation.
1470   // - If check always evaluates to false -> expand_fast_path is false (see above)
1471   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1472   // if !allocation_has_use the fast path is empty
1473   // if !allocation_has_use && no_initial_check
1474   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1475   //   removed by yank_alloc_node above.
1476 
1477   Node *slow_mem = mem;  // save the current memory state for slow path
1478   // generate the fast allocation code unless we know that the initial test will always go slow
1479   if (expand_fast_path) {
1480     // Fast path modifies only raw memory.
1481     if (mem->is_MergeMem()) {
1482       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1483     }
1484 
1485     // allocate the Region and Phi nodes for the result
1486     result_region = new RegionNode(3);
1487     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1488     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1489 
1490     // Grab regular I/O before optional prefetch may change it.
1491     // Slow-path does no I/O so just set it to the original I/O.
1492     result_phi_i_o->init_req(slow_result_path, i_o);
1493 
1494     // Name successful fast-path variables
1495     Node* fast_oop_ctrl;
1496     Node* fast_oop_rawmem;

1497     if (allocation_has_use) {
1498       Node* needgc_ctrl = nullptr;
1499       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1500 
1501       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1502       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1503       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1504                                         fast_oop_ctrl, fast_oop_rawmem,
1505                                         prefetch_lines);
1506 
1507       if (initial_slow_test != nullptr) {
1508         // This completes all paths into the slow merge point
1509         slow_region->init_req(need_gc_path, needgc_ctrl);
1510         transform_later(slow_region);
1511       } else {
1512         // No initial slow path needed!
1513         // Just fall from the need-GC path straight into the VM call.
1514         slow_region = needgc_ctrl;
1515       }
1516 

1534     result_phi_i_o   ->init_req(fast_result_path, i_o);
1535     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1536   } else {
1537     slow_region = ctrl;
1538     result_phi_i_o = i_o; // Rename it to use in the following code.
1539   }
1540 
1541   // Generate slow-path call
1542   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1543                                OptoRuntime::stub_name(slow_call_address),
1544                                TypePtr::BOTTOM);
1545   call->init_req(TypeFunc::Control,   slow_region);
1546   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1547   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1548   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1549   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1550 
1551   call->init_req(TypeFunc::Parms+0, klass_node);
1552   if (length != nullptr) {
1553     call->init_req(TypeFunc::Parms+1, length);



1554   }
1555 
1556   // Copy debug information and adjust JVMState information, then replace
1557   // allocate node with the call
1558   call->copy_call_debug_info(&_igvn, alloc);
1559   // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify
1560   // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough
1561   // path dies).
1562   if (valid_length_test != nullptr) {
1563     call->add_req(valid_length_test);
1564   }
1565   if (expand_fast_path) {
1566     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1567   } else {
1568     // Hook i_o projection to avoid its elimination during allocation
1569     // replacement (when only a slow call is generated).
1570     call->set_req(TypeFunc::I_O, result_phi_i_o);
1571   }
1572   _igvn.replace_node(alloc, call);
1573   transform_later(call);
1574 
1575   // Identify the output projections from the allocate node and
1576   // adjust any references to them.
1577   // The control and io projections look like:
1578   //
1579   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1580   //  Allocate                   Catch
1581   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1582   //
1583   //  We are interested in the CatchProj nodes.
1584   //
1585   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1586 
1587   // An allocate node has separate memory projections for the uses on
1588   // the control and i_o paths. Replace the control memory projection with
1589   // result_phi_rawmem (unless we are only generating a slow call when
1590   // both memory projections are combined)
1591   if (expand_fast_path && _callprojs.fallthrough_memproj != nullptr) {
1592     migrate_outs(_callprojs.fallthrough_memproj, result_phi_rawmem);
1593   }
1594   // Now change uses of catchall_memproj to use fallthrough_memproj and delete
1595   // catchall_memproj so we end up with a call that has only 1 memory projection.
1596   if (_callprojs.catchall_memproj != nullptr ) {
1597     if (_callprojs.fallthrough_memproj == nullptr) {
1598       _callprojs.fallthrough_memproj = new ProjNode(call, TypeFunc::Memory);
1599       transform_later(_callprojs.fallthrough_memproj);
1600     }
1601     migrate_outs(_callprojs.catchall_memproj, _callprojs.fallthrough_memproj);
1602     _igvn.remove_dead_node(_callprojs.catchall_memproj, PhaseIterGVN::NodeOrigin::Graph);
1603   }
1604 
1605   // An allocate node has separate i_o projections for the uses on the control
1606   // and i_o paths. Always replace the control i_o projection with result i_o
1607   // otherwise incoming i_o become dead when only a slow call is generated
1608   // (it is different from memory projections where both projections are
1609   // combined in such case).
1610   if (_callprojs.fallthrough_ioproj != nullptr) {
1611     migrate_outs(_callprojs.fallthrough_ioproj, result_phi_i_o);
1612   }
1613   // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete
1614   // catchall_ioproj so we end up with a call that has only 1 i_o projection.
1615   if (_callprojs.catchall_ioproj != nullptr ) {
1616     if (_callprojs.fallthrough_ioproj == nullptr) {
1617       _callprojs.fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O);
1618       transform_later(_callprojs.fallthrough_ioproj);
1619     }
1620     migrate_outs(_callprojs.catchall_ioproj, _callprojs.fallthrough_ioproj);
1621     _igvn.remove_dead_node(_callprojs.catchall_ioproj, PhaseIterGVN::NodeOrigin::Graph);
1622   }
1623 
1624   // if we generated only a slow call, we are done
1625   if (!expand_fast_path) {
1626     // Now we can unhook i_o.
1627     if (result_phi_i_o->outcnt() > 1) {
1628       call->set_req(TypeFunc::I_O, top());
1629     } else {
1630       assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1631       // Case of new array with negative size known during compilation.
1632       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1633       // following code since call to runtime will throw exception.
1634       // As result there will be no users of i_o after the call.
1635       // Leave i_o attached to this call to avoid problems in preceding graph.
1636     }
1637     return;
1638   }
1639 
1640   if (_callprojs.fallthrough_catchproj != nullptr) {
1641     ctrl = _callprojs.fallthrough_catchproj->clone();
1642     transform_later(ctrl);
1643     _igvn.replace_node(_callprojs.fallthrough_catchproj, result_region);
1644   } else {
1645     ctrl = top();
1646   }
1647   Node *slow_result;
1648   if (_callprojs.resproj == nullptr) {
1649     // no uses of the allocation result
1650     slow_result = top();
1651   } else {
1652     slow_result = _callprojs.resproj->clone();
1653     transform_later(slow_result);
1654     _igvn.replace_node(_callprojs.resproj, result_phi_rawoop);
1655   }
1656 
1657   // Plug slow-path into result merge point
1658   result_region->init_req( slow_result_path, ctrl);
1659   transform_later(result_region);
1660   if (allocation_has_use) {
1661     result_phi_rawoop->init_req(slow_result_path, slow_result);
1662     transform_later(result_phi_rawoop);
1663   }
1664   result_phi_rawmem->init_req(slow_result_path, _callprojs.fallthrough_memproj);
1665   transform_later(result_phi_rawmem);
1666   transform_later(result_phi_i_o);
1667   // This completes all paths into the result merge point
1668 }
1669 
1670 // Remove alloc node that has no uses.
1671 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1672   Node* ctrl = alloc->in(TypeFunc::Control);
1673   Node* mem  = alloc->in(TypeFunc::Memory);
1674   Node* i_o  = alloc->in(TypeFunc::I_O);
1675 
1676   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1677   if (_callprojs.resproj != nullptr) {
1678     for (DUIterator_Fast imax, i = _callprojs.resproj->fast_outs(imax); i < imax; i++) {
1679       Node* use = _callprojs.resproj->fast_out(i);
1680       use->isa_MemBar()->remove(&_igvn);
1681       --imax;
1682       --i; // back up iterator
1683     }
1684     assert(_callprojs.resproj->outcnt() == 0, "all uses must be deleted");
1685     _igvn.remove_dead_node(_callprojs.resproj, PhaseIterGVN::NodeOrigin::Graph);
1686   }
1687   if (_callprojs.fallthrough_catchproj != nullptr) {
1688     migrate_outs(_callprojs.fallthrough_catchproj, ctrl);
1689     _igvn.remove_dead_node(_callprojs.fallthrough_catchproj, PhaseIterGVN::NodeOrigin::Graph);
1690   }
1691   if (_callprojs.catchall_catchproj != nullptr) {
1692     _igvn.rehash_node_delayed(_callprojs.catchall_catchproj);
1693     _callprojs.catchall_catchproj->set_req(0, top());
1694   }
1695   if (_callprojs.fallthrough_proj != nullptr) {
1696     Node* catchnode = _callprojs.fallthrough_proj->unique_ctrl_out();
1697     _igvn.remove_dead_node(catchnode, PhaseIterGVN::NodeOrigin::Graph);
1698     _igvn.remove_dead_node(_callprojs.fallthrough_proj, PhaseIterGVN::NodeOrigin::Graph);
1699   }
1700   if (_callprojs.fallthrough_memproj != nullptr) {
1701     migrate_outs(_callprojs.fallthrough_memproj, mem);
1702     _igvn.remove_dead_node(_callprojs.fallthrough_memproj, PhaseIterGVN::NodeOrigin::Graph);
1703   }
1704   if (_callprojs.fallthrough_ioproj != nullptr) {
1705     migrate_outs(_callprojs.fallthrough_ioproj, i_o);
1706     _igvn.remove_dead_node(_callprojs.fallthrough_ioproj, PhaseIterGVN::NodeOrigin::Graph);
1707   }
1708   if (_callprojs.catchall_memproj != nullptr) {
1709     _igvn.rehash_node_delayed(_callprojs.catchall_memproj);
1710     _callprojs.catchall_memproj->set_req(0, top());
1711   }
1712   if (_callprojs.catchall_ioproj != nullptr) {
1713     _igvn.rehash_node_delayed(_callprojs.catchall_ioproj);
1714     _callprojs.catchall_ioproj->set_req(0, top());
1715   }
1716 #ifndef PRODUCT
1717   if (PrintEliminateAllocations) {
1718     if (alloc->is_AllocateArray()) {
1719       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1720     } else {
1721       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1722     }
1723   }
1724 #endif
1725   _igvn.remove_dead_node(alloc, PhaseIterGVN::NodeOrigin::Graph);
1726 }
1727 
1728 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1729                                                 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1730   // If initialization is performed by an array copy, any required
1731   // MemBarStoreStore was already added. If the object does not
1732   // escape no need for a MemBarStoreStore. If the object does not
1733   // escape in its initializer and memory barrier (MemBarStoreStore or
1734   // stronger) is already added at exit of initializer, also no need

1828     Node* thread = new ThreadLocalNode();
1829     transform_later(thread);
1830 
1831     call->init_req(TypeFunc::Parms + 0, thread);
1832     call->init_req(TypeFunc::Parms + 1, oop);
1833     call->init_req(TypeFunc::Control, ctrl);
1834     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1835     call->init_req(TypeFunc::Memory , rawmem);
1836     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1837     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1838     transform_later(call);
1839     ctrl = new ProjNode(call, TypeFunc::Control);
1840     transform_later(ctrl);
1841     rawmem = new ProjNode(call, TypeFunc::Memory);
1842     transform_later(rawmem);
1843   }
1844 }
1845 
1846 // Helper for PhaseMacroExpand::expand_allocate_common.
1847 // Initializes the newly-allocated storage.
1848 Node*
1849 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1850                                     Node* control, Node* rawmem, Node* object,
1851                                     Node* klass_node, Node* length,
1852                                     Node* size_in_bytes) {
1853   InitializeNode* init = alloc->initialization();
1854   // Store the klass & mark bits
1855   Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem);
1856   if (!mark_node->is_Con()) {
1857     transform_later(mark_node);
1858   }
1859   rawmem = make_store_raw(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1860 
1861   if (!UseCompactObjectHeaders) {
1862     rawmem = make_store_raw(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1863   }
1864   int header_size = alloc->minimum_header_size();  // conservatively small
1865 
1866   // Array length
1867   if (length != nullptr) {         // Arrays need length field
1868     rawmem = make_store_raw(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1869     // conservatively small header size:
1870     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1871     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
1872       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
1873       if (is_reference_type(elem, true)) {
1874         elem = T_OBJECT;
1875       }
1876       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
1877     }
1878   }
1879 
1880   // Clear the object body, if necessary.
1881   if (init == nullptr) {
1882     // The init has somehow disappeared; be cautious and clear everything.
1883     //
1884     // This can happen if a node is allocated but an uncommon trap occurs
1885     // immediately.  In this case, the Initialize gets associated with the
1886     // trap, and may be placed in a different (outer) loop, if the Allocate
1887     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1888     // there can be two Allocates to one Initialize.  The answer in all these
1889     // edge cases is safety first.  It is always safe to clear immediately
1890     // within an Allocate, and then (maybe or maybe not) clear some more later.
1891     if (!(UseTLAB && ZeroTLAB)) {
1892       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,


1893                                             header_size, size_in_bytes,
1894                                             true,
1895                                             &_igvn);
1896     }
1897   } else {
1898     if (!init->is_complete()) {
1899       // Try to win by zeroing only what the init does not store.
1900       // We can also try to do some peephole optimizations,
1901       // such as combining some adjacent subword stores.
1902       rawmem = init->complete_stores(control, rawmem, object,
1903                                      header_size, size_in_bytes, &_igvn);
1904     }
1905     // We have no more use for this link, since the AllocateNode goes away:
1906     init->set_req(InitializeNode::RawAddress, top());
1907     // (If we keep the link, it just confuses the register allocator,
1908     // who thinks he sees a real use of the address by the membar.)
1909   }
1910 
1911   return rawmem;
1912 }

2047       for (intx i = 0; i < lines; i++) {
2048         prefetch_adr = AddPNode::make_off_heap(new_eden_top,
2049                                                _igvn.MakeConX(distance));
2050         transform_later(prefetch_adr);
2051         prefetch = new PrefetchAllocationNode(i_o, prefetch_adr);
2052         // Do not let it float too high, since if eden_top == eden_end,
2053         // both might be null.
2054         if (i == 0) { // Set control for first prefetch, next follows it
2055           prefetch->init_req(0, needgc_false);
2056         }
2057         transform_later(prefetch);
2058         distance += step_size;
2059         i_o = prefetch;
2060       }
2061    }
2062    return i_o;
2063 }
2064 
2065 
2066 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
2067   expand_allocate_common(alloc, nullptr,
2068                          OptoRuntime::new_instance_Type(),
2069                          OptoRuntime::new_instance_Java(), nullptr);
2070 }
2071 
2072 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
2073   Node* length = alloc->in(AllocateNode::ALength);
2074   Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest);
2075   InitializeNode* init = alloc->initialization();
2076   Node* klass_node = alloc->in(AllocateNode::KlassNode);

2077   const TypeAryKlassPtr* ary_klass_t = _igvn.type(klass_node)->isa_aryklassptr();



2078   address slow_call_address;  // Address of slow call
2079   if (init != nullptr && init->is_complete_with_arraycopy() &&
2080       ary_klass_t && ary_klass_t->elem()->isa_klassptr() == nullptr) {
2081     // Don't zero type array during slow allocation in VM since
2082     // it will be initialized later by arraycopy in compiled code.
2083     slow_call_address = OptoRuntime::new_array_nozero_Java();

2084   } else {
2085     slow_call_address = OptoRuntime::new_array_Java();







2086   }
2087   expand_allocate_common(alloc, length,
2088                          OptoRuntime::new_array_Type(),
2089                          slow_call_address, valid_length_test);
2090 }
2091 
2092 //-------------------mark_eliminated_box----------------------------------
2093 //
2094 // During EA obj may point to several objects but after few ideal graph
2095 // transformations (CCP) it may point to only one non escaping object
2096 // (but still using phi), corresponding locks and unlocks will be marked
2097 // for elimination. Later obj could be replaced with a new node (new phi)
2098 // and which does not have escape information. And later after some graph
2099 // reshape other locks and unlocks (which were not marked for elimination
2100 // before) are connected to this new obj (phi) but they still will not be
2101 // marked for elimination since new obj has no escape information.
2102 // Mark all associated (same box and obj) lock and unlock nodes for
2103 // elimination if some of them marked already.
2104 void PhaseMacroExpand::mark_eliminated_box(Node* box, Node* obj) {
2105   BoxLockNode* oldbox = box->as_BoxLock();
2106   if (oldbox->is_eliminated()) {
2107     return; // This BoxLock node was processed already.
2108   }

2280 #ifdef ASSERT
2281   if (!alock->is_coarsened()) {
2282     // Check that new "eliminated" BoxLock node is created.
2283     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2284     assert(oldbox->is_eliminated(), "should be done already");
2285   }
2286 #endif
2287 
2288   alock->log_lock_optimization(C, "eliminate_lock");
2289 
2290 #ifndef PRODUCT
2291   if (PrintEliminateLocks) {
2292     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2293   }
2294 #endif
2295 
2296   Node* mem  = alock->in(TypeFunc::Memory);
2297   Node* ctrl = alock->in(TypeFunc::Control);
2298   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2299 
2300   alock->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2301   // There are 2 projections from the lock.  The lock node will
2302   // be deleted when its last use is subsumed below.
2303   assert(alock->outcnt() == 2 &&
2304          _callprojs.fallthrough_proj != nullptr &&
2305          _callprojs.fallthrough_memproj != nullptr,
2306          "Unexpected projections from Lock/Unlock");
2307 
2308   Node* fallthroughproj = _callprojs.fallthrough_proj;
2309   Node* memproj_fallthrough = _callprojs.fallthrough_memproj;
2310 
2311   // The memory projection from a lock/unlock is RawMem
2312   // The input to a Lock is merged memory, so extract its RawMem input
2313   // (unless the MergeMem has been optimized away.)
2314   if (alock->is_Lock()) {
2315     // Search for MemBarAcquireLock node and delete it also.
2316     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2317     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2318     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2319     Node* memproj = membar->proj_out(TypeFunc::Memory);
2320     _igvn.replace_node(ctrlproj, fallthroughproj);
2321     _igvn.replace_node(memproj, memproj_fallthrough);
2322 
2323     // Delete FastLock node also if this Lock node is unique user
2324     // (a loop peeling may clone a Lock node).
2325     Node* flock = alock->as_Lock()->fastlock_node();
2326     if (flock->outcnt() == 1) {
2327       assert(flock->unique_out() == alock, "sanity");
2328       _igvn.replace_node(flock, top());
2329     }

2360   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2361 
2362   // Make the merge point
2363   Node *region;
2364   Node *mem_phi;
2365   Node *slow_path;
2366 
2367   region  = new RegionNode(3);
2368   // create a Phi for the memory state
2369   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2370 
2371   // Optimize test; set region slot 2
2372   slow_path = opt_bits_test(ctrl, region, 2, flock);
2373   mem_phi->init_req(2, mem);
2374 
2375   // Make slow path call
2376   CallNode* call = make_slow_call(lock, OptoRuntime::complete_monitor_enter_Type(),
2377                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2378                                   obj, box, nullptr);
2379 
2380   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2381 
2382   // Slow path can only throw asynchronous exceptions, which are always
2383   // de-opted.  So the compiler thinks the slow-call can never throw an
2384   // exception.  If it DOES throw an exception we would need the debug
2385   // info removed first (since if it throws there is no monitor).
2386   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2387          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2388 
2389   // Capture slow path
2390   // disconnect fall-through projection from call and create a new one
2391   // hook up users of fall-through projection to region
2392   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2393   transform_later(slow_ctrl);
2394   _igvn.hash_delete(_callprojs.fallthrough_proj);
2395   _callprojs.fallthrough_proj->disconnect_inputs(C);
2396   region->init_req(1, slow_ctrl);
2397   // region inputs are now complete
2398   transform_later(region);
2399   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2400 
2401   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2402 
2403   mem_phi->init_req(1, memproj);
2404 
2405   transform_later(mem_phi);
2406 
2407   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2408 }
2409 
2410 //------------------------------expand_unlock_node----------------------
2411 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2412 
2413   Node* ctrl = unlock->in(TypeFunc::Control);
2414   Node* mem = unlock->in(TypeFunc::Memory);
2415   Node* obj = unlock->obj_node();
2416   Node* box = unlock->box_node();
2417 
2418   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2419 
2420   // No need for a null check on unlock
2421 
2422   // Make the merge point
2423   Node* region = new RegionNode(3);
2424 
2425   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2426   funlock = transform_later( funlock )->as_FastUnlock();
2427   // Optimize test; set region slot 2
2428   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock);
2429   Node *thread = transform_later(new ThreadLocalNode());
2430 
2431   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2432                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2433                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2434 
2435   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2436   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2437          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2438 
2439   // No exceptions for unlocking
2440   // Capture slow path
2441   // disconnect fall-through projection from call and create a new one
2442   // hook up users of fall-through projection to region
2443   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2444   transform_later(slow_ctrl);
2445   _igvn.hash_delete(_callprojs.fallthrough_proj);
2446   _callprojs.fallthrough_proj->disconnect_inputs(C);
2447   region->init_req(1, slow_ctrl);
2448   // region inputs are now complete
2449   transform_later(region);
2450   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2451 
2452   if (_callprojs.fallthrough_memproj != nullptr) {
2453     // create a Phi for the memory state
2454     Node* mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2455     Node* memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2456     mem_phi->init_req(1, memproj);
2457     mem_phi->init_req(2, mem);
2458     transform_later(mem_phi);
2459     _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2460   }
2461 }
2462 




























































































































































































































2463 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2464   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2465   Node* bol = check->unique_out();
2466   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2467   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2468   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2469 
2470   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2471     Node* iff = bol->last_out(i);
2472     assert(iff->is_If(), "where's the if?");
2473 
2474     if (iff->in(0)->is_top()) {
2475       _igvn.replace_input_of(iff, 1, C->top());
2476       continue;
2477     }
2478 
2479     IfTrueNode* iftrue = iff->as_If()->true_proj();
2480     IfFalseNode* iffalse = iff->as_If()->false_proj();
2481     Node* ctrl = iff->in(0);
2482 
2483     Node* subklass = nullptr;
2484     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2485       subklass = obj_or_subklass;
2486     } else {
2487       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2488       subklass = _igvn.transform(LoadKlassNode::make(_igvn, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2489     }
2490 
2491     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci());
2492 
2493     _igvn.replace_input_of(iff, 0, C->top());
2494     _igvn.replace_node(iftrue, not_subtype_ctrl);
2495     _igvn.replace_node(iffalse, ctrl);
2496   }
2497   _igvn.replace_node(check, C->top());
2498 }
2499 

















































































































2500 // Perform refining of strip mined loop nodes in the macro nodes list.
2501 void PhaseMacroExpand::refine_strip_mined_loop_macro_nodes() {
2502    for (int i = C->macro_count(); i > 0; i--) {
2503     Node* n = C->macro_node(i - 1);
2504     if (n->is_OuterStripMinedLoop()) {
2505       n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
2506     }
2507   }
2508 }
2509 
2510 //---------------------------eliminate_macro_nodes----------------------
2511 // Eliminate scalar replaced allocations and associated locks.
2512 void PhaseMacroExpand::eliminate_macro_nodes() {
2513   if (C->macro_count() == 0)
2514     return;

2515 
2516   if (StressMacroElimination) {
2517     C->shuffle_macro_nodes();
2518   }
2519   NOT_PRODUCT(int membar_before = count_MemBar(C);)
2520 
2521   // Before elimination may re-mark (change to Nested or NonEscObj)
2522   // all associated (same box and obj) lock and unlock nodes.
2523   int cnt = C->macro_count();
2524   for (int i=0; i < cnt; i++) {
2525     Node *n = C->macro_node(i);
2526     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2527       mark_eliminated_locking_nodes(n->as_AbstractLock());
2528     }
2529   }
2530   // Re-marking may break consistency of Coarsened locks.
2531   if (!C->coarsened_locks_consistent()) {
2532     return; // recompile without Coarsened locks if broken
2533   } else {
2534     // After coarsened locks are eliminated locking regions
2535     // become unbalanced. We should not execute any more
2536     // locks elimination optimizations on them.
2537     C->mark_unbalanced_boxes();
2538   }
2539 
2540   // First, attempt to eliminate locks
2541   bool progress = true;
2542   while (progress) {
2543     progress = false;
2544     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2545       Node* n = C->macro_node(i - 1);
2546       bool success = false;
2547       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2548       if (n->is_AbstractLock()) {
2549         success = eliminate_locking_node(n->as_AbstractLock());
2550 #ifndef PRODUCT
2551         if (success && PrintOptoStatistics) {
2552           AtomicAccess::inc(&PhaseMacroExpand::_monitor_objects_removed_counter);
2553         }
2554 #endif
2555       }
2556       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2557       progress = progress || success;
2558       if (success) {
2559         C->print_method(PHASE_AFTER_MACRO_ELIMINATION_STEP, 5, n);




2560       }
2561     }
2562   }
2563   // Next, attempt to eliminate allocations
2564   progress = true;
2565   while (progress) {
2566     progress = false;
2567     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2568       Node* n = C->macro_node(i - 1);
2569       bool success = false;
2570       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2571       switch (n->class_id()) {
2572       case Node::Class_Allocate:
2573       case Node::Class_AllocateArray:
2574         success = eliminate_allocate_node(n->as_Allocate());
2575 #ifndef PRODUCT
2576         if (success && PrintOptoStatistics) {
2577           AtomicAccess::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
2578         }
2579 #endif
2580         break;
2581       case Node::Class_CallStaticJava:
2582         success = eliminate_boxing_node(n->as_CallStaticJava());



2583         break;

2584       case Node::Class_Lock:
2585       case Node::Class_Unlock:
2586         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");







2587         break;
2588       case Node::Class_ArrayCopy:
2589         break;
2590       case Node::Class_OuterStripMinedLoop:
2591         break;
2592       case Node::Class_SubTypeCheck:
2593         break;
2594       case Node::Class_Opaque1:
2595         break;


2596       default:
2597         assert(n->Opcode() == Op_LoopLimit ||
2598                n->Opcode() == Op_ModD ||
2599                n->Opcode() == Op_ModF ||
2600                n->Opcode() == Op_PowD ||
2601                n->is_OpaqueConstantBool()    ||
2602                n->is_OpaqueInitializedAssertionPredicate() ||
2603                n->Opcode() == Op_MaxL      ||
2604                n->Opcode() == Op_MinL      ||
2605                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2606                "unknown node type in macro list");
2607       }
2608       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2609       progress = progress || success;
2610       if (success) {
2611         C->print_method(PHASE_AFTER_MACRO_ELIMINATION_STEP, 5, n);
2612       }
2613     }
















2614   }
2615 #ifndef PRODUCT
2616   if (PrintOptoStatistics) {
2617     int membar_after = count_MemBar(C);
2618     AtomicAccess::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
2619   }
2620 #endif
2621 }
2622 
2623 void PhaseMacroExpand::eliminate_opaque_looplimit_macro_nodes() {
2624   if (C->macro_count() == 0) {
2625     return;
2626   }
2627   refine_strip_mined_loop_macro_nodes();
2628   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2629   bool progress = true;
2630   while (progress) {
2631     progress = false;
2632     for (int i = C->macro_count(); i > 0; i--) {
2633       Node* n = C->macro_node(i-1);
2634       bool success = false;
2635       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2636       if (n->Opcode() == Op_LoopLimit) {
2637         // Remove it from macro list and put on IGVN worklist to optimize.
2638         C->remove_macro_node(n);
2639         _igvn._worklist.push(n);
2640         success = true;
2641       } else if (n->Opcode() == Op_CallStaticJava) {
2642         // Remove it from macro list and put on IGVN worklist to optimize.
2643         C->remove_macro_node(n);
2644         _igvn._worklist.push(n);
2645         success = true;



2646       } else if (n->is_Opaque1()) {
2647         _igvn.replace_node(n, n->in(1));
2648         success = true;
2649       } else if (n->is_OpaqueConstantBool()) {
2650         // Tests with OpaqueConstantBool nodes are implicitly known. Replace the node with true/false. In debug builds,
2651         // we leave the test in the graph to have an additional sanity check at runtime. If the test fails (i.e. a bug),
2652         // we will execute a Halt node.
2653 #ifdef ASSERT
2654         _igvn.replace_node(n, n->in(1));
2655 #else
2656         _igvn.replace_node(n, _igvn.intcon(n->as_OpaqueConstantBool()->constant()));
2657 #endif
2658         success = true;
2659       } else if (n->is_OpaqueInitializedAssertionPredicate()) {
2660           // Initialized Assertion Predicates must always evaluate to true. Therefore, we get rid of them in product
2661           // builds as they are useless. In debug builds we keep them as additional verification code. Even though
2662           // loop opts are already over, we want to keep Initialized Assertion Predicates alive as long as possible to
2663           // enable folding of dead control paths within which cast nodes become top after due to impossible types -
2664           // even after loop opts are over. Therefore, we delay the removal of these opaque nodes until now.
2665 #ifdef ASSERT

2734     // Worst case is a macro node gets expanded into about 200 nodes.
2735     // Allow 50% more for optimization.
2736     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2737       return true;
2738     }
2739 
2740     DEBUG_ONLY(int old_macro_count = C->macro_count();)
2741     switch (n->class_id()) {
2742     case Node::Class_Lock:
2743       expand_lock_node(n->as_Lock());
2744       break;
2745     case Node::Class_Unlock:
2746       expand_unlock_node(n->as_Unlock());
2747       break;
2748     case Node::Class_ArrayCopy:
2749       expand_arraycopy_node(n->as_ArrayCopy());
2750       break;
2751     case Node::Class_SubTypeCheck:
2752       expand_subtypecheck_node(n->as_SubTypeCheck());
2753       break;







2754     default:
2755       switch (n->Opcode()) {
2756       case Op_ModD:
2757       case Op_ModF:
2758       case Op_PowD: {
2759         CallLeafPureNode* call_macro = n->as_CallLeafPure();
2760         CallLeafPureNode* call = call_macro->inline_call_leaf_pure_node();
2761         _igvn.replace_node(call_macro, call);
2762         transform_later(call);
2763         break;
2764       }
2765       default:
2766         assert(false, "unknown node type in macro list");
2767       }
2768     }
2769     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2770     if (C->failing())  return true;
2771     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
2772 
2773     // Clean up the graph so we're less likely to hit the maximum node

   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "ci/ciFlatArrayKlass.hpp"
  26 #include "ci/ciInlineKlass.hpp"
  27 #include "ci/ciInstanceKlass.hpp"
  28 #include "compiler/compileLog.hpp"
  29 #include "gc/shared/collectedHeap.inline.hpp"
  30 #include "gc/shared/tlab_globals.hpp"
  31 #include "libadt/vectset.hpp"
  32 #include "memory/universe.hpp"
  33 #include "opto/addnode.hpp"
  34 #include "opto/arraycopynode.hpp"
  35 #include "opto/callnode.hpp"
  36 #include "opto/castnode.hpp"
  37 #include "opto/cfgnode.hpp"
  38 #include "opto/compile.hpp"
  39 #include "opto/convertnode.hpp"
  40 #include "opto/graphKit.hpp"
  41 #include "opto/inlinetypenode.hpp"
  42 #include "opto/intrinsicnode.hpp"
  43 #include "opto/locknode.hpp"
  44 #include "opto/loopnode.hpp"
  45 #include "opto/macro.hpp"
  46 #include "opto/memnode.hpp"
  47 #include "opto/narrowptrnode.hpp"
  48 #include "opto/node.hpp"
  49 #include "opto/opaquenode.hpp"
  50 #include "opto/opcodes.hpp"
  51 #include "opto/phaseX.hpp"
  52 #include "opto/reachability.hpp"
  53 #include "opto/rootnode.hpp"
  54 #include "opto/runtime.hpp"
  55 #include "opto/subnode.hpp"
  56 #include "opto/subtypenode.hpp"
  57 #include "opto/type.hpp"
  58 #include "prims/jvmtiExport.hpp"
  59 #include "runtime/continuation.hpp"
  60 #include "runtime/sharedRuntime.hpp"
  61 #include "runtime/stubRoutines.hpp"
  62 #include "utilities/globalDefinitions.hpp"
  63 #include "utilities/macros.hpp"
  64 #include "utilities/powerOfTwo.hpp"
  65 #if INCLUDE_G1GC
  66 #include "gc/g1/g1ThreadLocalData.hpp"
  67 #endif // INCLUDE_G1GC
  68 
  69 
  70 //
  71 // Replace any references to "oldref" in inputs to "use" with "newref".
  72 // Returns the number of replacements made.
  73 //
  74 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
  75   int nreplacements = 0;
  76   uint req = use->req();
  77   for (uint j = 0; j < use->len(); j++) {
  78     Node *uin = use->in(j);
  79     if (uin == oldref) {
  80       if (j < req)
  81         use->set_req(j, newref);
  82       else
  83         use->set_prec(j, newref);
  84       nreplacements++;
  85     } else if (j >= req && uin == nullptr) {
  86       break;
  87     }
  88   }
  89   return nreplacements;
  90 }
  91 











  92 
  93 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word) {
  94   Node* cmp = word;
  95   Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
  96   IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
  97   transform_later(iff);
  98 
  99   // Fast path taken.
 100   Node *fast_taken = transform_later(new IfFalseNode(iff));
 101 
 102   // Fast path not-taken, i.e. slow path
 103   Node *slow_taken = transform_later(new IfTrueNode(iff));
 104 
 105     region->init_req(edge, fast_taken); // Capture fast-control
 106     return slow_taken;
 107 }
 108 
 109 //--------------------copy_predefined_input_for_runtime_call--------------------
 110 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
 111   // Set fixed predefined input arguments

 124   // Slow-path call
 125  CallNode *call = leaf_name
 126    ? (CallNode*)new CallLeafNode      ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
 127    : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), TypeRawPtr::BOTTOM );
 128 
 129   // Slow path call has no side-effects, uses few values
 130   copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
 131   if (parm0 != nullptr)  call->init_req(TypeFunc::Parms+0, parm0);
 132   if (parm1 != nullptr)  call->init_req(TypeFunc::Parms+1, parm1);
 133   if (parm2 != nullptr)  call->init_req(TypeFunc::Parms+2, parm2);
 134   call->copy_call_debug_info(&_igvn, oldcall);
 135   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
 136   _igvn.replace_node(oldcall, call);
 137   transform_later(call);
 138 
 139   return call;
 140 }
 141 
 142 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) {
 143   BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 144   bs->eliminate_gc_barrier(&_igvn, p2x);
 145 #ifndef PRODUCT
 146   if (PrintOptoStatistics) {
 147     AtomicAccess::inc(&PhaseMacroExpand::_GC_barriers_removed_counter);
 148   }
 149 #endif
 150 }
 151 
 152 // Search for a memory operation for the specified memory slice.
 153 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
 154   Node *orig_mem = mem;
 155   Node *alloc_mem = alloc->as_Allocate()->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 156   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 157   const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
 158   while (true) {
 159     if (mem == alloc_mem || mem == start_mem ) {
 160       return mem;  // hit one of our sentinels
 161     } else if (mem->is_MergeMem()) {
 162       mem = mem->as_MergeMem()->memory_at(alias_idx);
 163     } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
 164       Node *in = mem->in(0);

 167       if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
 168         return in;
 169       } else if (in->is_Call()) {
 170         CallNode *call = in->as_Call();
 171         if (call->may_modify(tinst, phase)) {
 172           assert(call->is_ArrayCopy(), "ArrayCopy is the only call node that doesn't make allocation escape");
 173           if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
 174             return in;
 175           }
 176         }
 177         mem = in->in(TypeFunc::Memory);
 178       } else if (in->is_MemBar()) {
 179         ArrayCopyNode* ac = nullptr;
 180         if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
 181           if (ac != nullptr) {
 182             assert(ac->is_clonebasic(), "Only basic clone is a non escaping clone");
 183             return ac;
 184           }
 185         }
 186         mem = in->in(TypeFunc::Memory);
 187       } else if (in->is_LoadFlat() || in->is_StoreFlat()) {
 188         mem = in->in(TypeFunc::Memory);
 189       } else {
 190 #ifdef ASSERT
 191         in->dump();
 192         mem->dump();
 193         assert(false, "unexpected projection");
 194 #endif
 195       }
 196     } else if (mem->is_Store()) {
 197       const TypePtr* atype = mem->as_Store()->adr_type();
 198       int adr_idx = phase->C->get_alias_index(atype);
 199       if (adr_idx == alias_idx) {
 200         assert(atype->isa_oopptr(), "address type must be oopptr");
 201         int adr_offset = atype->flat_offset();
 202         uint adr_iid = atype->is_oopptr()->instance_id();
 203         // Array elements references have the same alias_idx
 204         // but different offset and different instance_id.
 205         if (adr_offset == offset && adr_iid == alloc->_idx) {
 206           return mem;
 207         }
 208       } else {
 209         assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
 210       }
 211       mem = mem->in(MemNode::Memory);
 212     } else if (mem->is_ClearArray()) {
 213       if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
 214         // Can not bypass initialization of the instance
 215         // we are looking.
 216         DEBUG_ONLY(intptr_t offset;)
 217         assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
 218         InitializeNode* init = alloc->as_Allocate()->initialization();
 219         // We are looking for stored value, return Initialize node
 220         // or memory edge from Allocate node.
 221         if (init != nullptr) {

 226       }
 227       // Otherwise skip it (the call updated 'mem' value).
 228     } else if (mem->Opcode() == Op_SCMemProj) {
 229       mem = mem->in(0);
 230       Node* adr = nullptr;
 231       if (mem->is_LoadStore()) {
 232         adr = mem->in(MemNode::Address);
 233       } else {
 234         assert(mem->Opcode() == Op_EncodeISOArray ||
 235                mem->Opcode() == Op_StrCompressedCopy, "sanity");
 236         adr = mem->in(3); // Destination array
 237       }
 238       const TypePtr* atype = adr->bottom_type()->is_ptr();
 239       int adr_idx = phase->C->get_alias_index(atype);
 240       if (adr_idx == alias_idx) {
 241         DEBUG_ONLY(mem->dump();)
 242         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 243         return nullptr;
 244       }
 245       mem = mem->in(MemNode::Memory);
 246     } else if (mem->Opcode() == Op_StrInflatedCopy) {
 247       Node* adr = mem->in(3); // Destination array
 248       const TypePtr* atype = adr->bottom_type()->is_ptr();
 249       int adr_idx = phase->C->get_alias_index(atype);
 250       if (adr_idx == alias_idx) {
 251         DEBUG_ONLY(mem->dump();)
 252         assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
 253         return nullptr;
 254       }
 255       mem = mem->in(MemNode::Memory);
 256     } else {
 257       return mem;
 258     }
 259     assert(mem != orig_mem, "dead memory loop");
 260   }
 261 }
 262 
 263 // Determine if there is an interfering store between a rematerialization load and an arraycopy that is in the process
 264 // of being elided. Starting from the given rematerialization load this method starts a BFS traversal upwards through
 265 // the memory graph towards the provided ArrayCopyNode. For every node encountered on the traversal, check that it is
 266 // independent from the provided rematerialization. Returns false if every node on the traversal is independent and

 306 // Generate loads from source of the arraycopy for fields of destination needed at a deoptimization point.
 307 // Returns nullptr if the load cannot be created because the arraycopy is not suitable for elimination
 308 // (e.g. copy inside the array with non-constant offsets) or the inputs do not match our assumptions (e.g.
 309 // the arraycopy does not actually write something at the provided offset).
 310 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type* ftype, AllocateNode* alloc) {
 311   assert((ctl == ac->control() && mem == ac->memory()) != (mem != ac->memory() && ctl->is_Proj() && ctl->as_Proj()->is_uncommon_trap_proj()),
 312     "Either the control and memory are the same as for the arraycopy or they are pinned in an uncommon trap.");
 313   BasicType bt = ft;
 314   const Type *type = ftype;
 315   if (ft == T_NARROWOOP) {
 316     bt = T_OBJECT;
 317     type = ftype->make_oopptr();
 318   }
 319   Node* base = ac->in(ArrayCopyNode::Src);
 320   Node* adr = nullptr;
 321   const TypePtr* adr_type = nullptr;
 322 
 323   if (ac->is_clonebasic()) {
 324     assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
 325     adr = _igvn.transform(AddPNode::make_with_base(base, _igvn.MakeConX(offset)));
 326     adr_type = _igvn.type(base)->is_ptr();
 327     if (adr_type->isa_aryptr()) {
 328       adr_type = adr_type->is_aryptr()->add_field_offset_and_offset(offset);
 329     } else {
 330       adr_type = adr_type->add_offset(offset);
 331     }
 332   } else {
 333     if (!ac->modifies(offset, offset, &_igvn, true)) {
 334       // If the arraycopy does not copy to this offset, we cannot generate a rematerialization load for it.
 335       return nullptr;
 336     }
 337     assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
 338     uint shift = exact_log2(type2aelembytes(bt));
 339     Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
 340     Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
 341     const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
 342     const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
 343 
 344     adr_type = _igvn.type(base)->is_aryptr();
 345     if (((const TypeAryPtr*)adr_type)->is_flat()) {
 346       shift = ((const TypeAryPtr*)adr_type)->flat_log_elem_size();
 347     }
 348     if (src_pos_t->is_con() && dest_pos_t->is_con()) {
 349       intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
 350       adr = _igvn.transform(AddPNode::make_with_base(base, base, _igvn.MakeConX(off)));
 351       adr_type = _igvn.type(adr)->is_aryptr();
 352       assert(adr_type == _igvn.type(base)->is_aryptr()->add_field_offset_and_offset(off), "incorrect address type");
 353       if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 354         // Don't emit a new load from src if src == dst but try to get the value from memory instead
 355         return value_from_mem(ac, ctl, ft, ftype, (const TypeAryPtr*)adr_type, alloc);
 356       }
 357     } else {
 358       if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 359         // Non constant offset in the array: we can't statically
 360         // determine the value
 361         return nullptr;
 362       }
 363       Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 364 #ifdef _LP64
 365       diff = _igvn.transform(new ConvI2LNode(diff));
 366 #endif
 367       diff = _igvn.transform(new LShiftXNode(diff, _igvn.intcon(shift)));
 368 
 369       Node* off = _igvn.transform(new AddXNode(_igvn.MakeConX(offset), diff));
 370       adr = _igvn.transform(AddPNode::make_with_base(base, base, off));
 371       // In the case of a flat inline type array, each field has its
 372       // own slice so we need to extract the field being accessed from
 373       // the address computation
 374       adr_type = ((TypeAryPtr*)adr_type)->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot)->is_aryptr();
 375       adr = _igvn.transform(new CastPPNode(ctl, adr, adr_type));

 376     }
 377   }
 378   assert(adr != nullptr && adr_type != nullptr, "sanity");
 379 
 380   // Create the rematerialization load ...
 381   MergeMemNode* mergemem = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 382   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 383   Node* res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemem, adr, adr_type, type, bt);
 384   assert(res != nullptr, "load should have been created");
 385 
 386   // ... and ensure that pinning the rematerialization load inside the uncommon path is safe.
 387   if (mem != ac->memory() && ctl->is_Proj() && ctl->as_Proj()->is_uncommon_trap_proj() && res->is_Load() &&
 388       has_interfering_store(ac, res->as_Load(), &_igvn)) {
 389     // Not safe: use control and memory from the arraycopy to ensure correct memory state.
 390     _igvn.remove_dead_node(res, PhaseIterGVN::NodeOrigin::Graph); // Clean up the unusable rematerialization load.
 391     return make_arraycopy_load(ac, offset, ac->control(), ac->memory(), ft, ftype, alloc);
 392   }
 393 
 394   if (ftype->isa_narrowoop()) {
 395     // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
 396     res = _igvn.transform(new EncodePNode(res, ftype));
 397   }
 398   return res;
 399 }
 400 
 401 //
 402 // Given a Memory Phi, compute a value Phi containing the values from stores
 403 // on the input paths.
 404 // Note: this function is recursive, its depth is limited by the "level" argument
 405 // Returns the computed Phi, or null if it cannot compute it.
 406 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) {
 407   assert(mem->is_Phi(), "sanity");
 408   int alias_idx = C->get_alias_index(adr_t);
 409   int offset = adr_t->flat_offset();
 410   int instance_id = adr_t->instance_id();
 411 
 412   // Check if an appropriate value phi already exists.
 413   Node* region = mem->in(0);
 414   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
 415     Node* phi = region->fast_out(k);
 416     if (phi->is_Phi() && phi != mem &&
 417         phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
 418       return phi;
 419     }
 420   }
 421   // Check if an appropriate new value phi already exists.
 422   Node* new_phi = value_phis->find(mem->_idx);
 423   if (new_phi != nullptr)
 424     return new_phi;
 425 
 426   if (level <= 0) {
 427     return nullptr; // Give up: phi tree too deep
 428   }
 429   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 430   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 431   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 432 
 433   uint length = mem->req();
 434   GrowableArray <Node *> values(length, length, nullptr);
 435 
 436   // create a new Phi for the value
 437   PhiNode *phi = new PhiNode(mem->in(0), phi_type, nullptr, mem->_idx, instance_id, alias_idx, offset);
 438   transform_later(phi);
 439   value_phis->push(phi, mem->_idx);
 440 
 441   for (uint j = 1; j < length; j++) {
 442     Node *in = mem->in(j);
 443     if (in == nullptr || in->is_top()) {
 444       values.at_put(j, in);
 445     } else {
 446       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
 447       if (val == start_mem || val == alloc_mem) {
 448         // hit a sentinel, return appropriate value
 449         Node* init_value = value_from_alloc(ft, adr_t, alloc);
 450         if (init_value == nullptr) {
 451           return nullptr;
 452         } else {
 453           values.at_put(j, init_value);
 454           continue;
 455         }
 456       }
 457       if (val->is_Initialize()) {
 458         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 459       }
 460       if (val == nullptr) {
 461         return nullptr;  // can't find a value on this path
 462       }
 463       if (val == mem) {
 464         values.at_put(j, mem);
 465       } else if (val->is_Store()) {
 466         Node* n = val->in(MemNode::ValueIn);
 467         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 468         n = bs->step_over_gc_barrier(n);
 469         if (is_subword_type(ft)) {
 470           n = Compile::narrow_value(ft, n, phi_type, &_igvn, true);
 471         }
 472         values.at_put(j, n);
 473       } else if (val->is_Proj() && val->in(0) == alloc) {
 474         Node* init_value = value_from_alloc(ft, adr_t, alloc);
 475         if (init_value == nullptr) {
 476           return nullptr;
 477         } else {
 478           values.at_put(j, init_value);
 479         }
 480       } else if (val->is_Phi()) {
 481         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 482         if (val == nullptr) {
 483           return nullptr;
 484         }
 485         values.at_put(j, val);
 486       } else if (val->Opcode() == Op_SCMemProj) {
 487         assert(val->in(0)->is_LoadStore() ||
 488                val->in(0)->Opcode() == Op_EncodeISOArray ||
 489                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
 490         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 491         return nullptr;
 492       } else if (val->is_ArrayCopy()) {
 493         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
 494         if (res == nullptr) {
 495           return nullptr;
 496         }
 497         values.at_put(j, res);
 498       } else if (val->is_top()) {
 499         // This indicates that this path into the phi is dead. Top will eventually also propagate into the Region.
 500         // IGVN will clean this up later.
 501         values.at_put(j, val);
 502       } else {
 503         DEBUG_ONLY( val->dump(); )
 504         assert(false, "unknown node on this path");
 505         return nullptr;  // unknown node on this path
 506       }
 507     }
 508   }
 509   // Set Phi's inputs
 510   for (uint j = 1; j < length; j++) {
 511     if (values.at(j) == mem) {
 512       phi->init_req(j, phi);
 513     } else {
 514       phi->init_req(j, values.at(j));
 515     }
 516   }
 517   return phi;
 518 }
 519 
 520 // Extract the initial value of a field in an allocation
 521 Node* PhaseMacroExpand::value_from_alloc(BasicType ft, const TypeOopPtr* adr_t, AllocateNode* alloc) {
 522   Node* init_value = alloc->in(AllocateNode::InitValue);
 523   if (init_value == nullptr) {
 524     assert(alloc->in(AllocateNode::RawInitValue) == nullptr, "conflicting InitValue and RawInitValue");
 525     return _igvn.zerocon(ft);
 526   }
 527 
 528   const TypeAryPtr* ary_t = adr_t->isa_aryptr();
 529   assert(ary_t != nullptr, "must be a pointer into an array");
 530 
 531   // If this is not a flat array, then it must be an oop array with elements being init_value
 532   if (ary_t->is_not_flat()) {
 533 #ifdef ASSERT
 534     BasicType init_bt = init_value->bottom_type()->basic_type();
 535     assert(ft == init_bt ||
 536            (!is_java_primitive(ft) && !is_java_primitive(init_bt) && type2aelembytes(ft, true) == type2aelembytes(init_bt, true)) ||
 537            (is_subword_type(ft) && init_bt == T_INT),
 538            "invalid init_value of type %s for field of type %s", type2name(init_bt), type2name(ft));
 539 #endif // ASSERT
 540     return init_value;
 541   }
 542 
 543   assert(ary_t->klass_is_exact() && ary_t->is_flat(), "must be an exact flat array");
 544   assert(ary_t->field_offset().get() != Type::OffsetBot, "unknown offset");
 545   if (init_value->is_EncodeP()) {
 546     init_value = init_value->in(1);
 547   }
 548   // Cannot look through init_value if it is an oop
 549   if (!init_value->is_InlineType()) {
 550     return nullptr;
 551   }
 552 
 553   ciInlineKlass* vk = init_value->bottom_type()->inline_klass();
 554   if (ary_t->field_offset().get() == vk->null_marker_offset_in_payload()) {
 555     init_value = init_value->as_InlineType()->get_null_marker();
 556   } else {
 557     init_value = init_value->as_InlineType()->field_value_by_offset(ary_t->field_offset().get() + vk->payload_offset(), true);
 558   }
 559 
 560   if (ft == T_NARROWOOP) {
 561     assert(init_value->bottom_type()->isa_ptr(), "must be a pointer");
 562     init_value = transform_later(new EncodePNode(init_value, init_value->bottom_type()->make_narrowoop()));
 563   }
 564 
 565 #ifdef ASSERT
 566   BasicType init_bt = init_value->bottom_type()->basic_type();
 567   assert(ft == init_bt ||
 568          (!is_java_primitive(ft) && !is_java_primitive(init_bt) && type2aelembytes(ft, true) == type2aelembytes(init_bt, true)) ||
 569          (is_subword_type(ft) && init_bt == T_INT),
 570          "invalid init_value of type %s for field of type %s", type2name(init_bt), type2name(ft));
 571 #endif // ASSERT
 572 
 573   return init_value;
 574 }
 575 
 576 // Search the last value stored into the object's field.
 577 Node* PhaseMacroExpand::value_from_mem(Node* origin, Node* ctl, BasicType ft, const Type* ftype, const TypeOopPtr* adr_t, AllocateNode* alloc) {
 578   assert(adr_t->is_known_instance_field(), "instance required");
 579   int instance_id = adr_t->instance_id();
 580   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 581 
 582   int alias_idx = C->get_alias_index(adr_t);
 583   int offset = adr_t->flat_offset();
 584   Node* orig_mem = origin->in(TypeFunc::Memory);
 585   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);

 586   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 587   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 588   VectorSet visited;
 589 
 590   bool done = orig_mem == alloc_mem;
 591   Node *mem = orig_mem;
 592   while (!done) {
 593     if (visited.test_set(mem->_idx)) {
 594       return nullptr;  // found a loop, give up
 595     }
 596     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 597     if (mem == start_mem || mem == alloc_mem) {
 598       done = true;  // hit a sentinel, return appropriate 0 value
 599     } else if (mem->is_Initialize()) {
 600       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 601       if (mem == nullptr) {
 602         done = true; // Something went wrong.
 603       } else if (mem->is_Store()) {
 604         const TypePtr* atype = mem->as_Store()->adr_type();
 605         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 606         done = true;
 607       }
 608     } else if (mem->is_Store()) {
 609       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 610       assert(atype != nullptr, "address type must be oopptr");
 611       assert(C->get_alias_index(atype) == alias_idx &&
 612              atype->is_known_instance_field() && atype->flat_offset() == offset &&
 613              atype->instance_id() == instance_id, "store is correct memory slice");
 614       done = true;
 615     } else if (mem->is_Phi()) {
 616       // try to find a phi's unique input
 617       Node *unique_input = nullptr;
 618       Node *top = C->top();
 619       for (uint i = 1; i < mem->req(); i++) {
 620         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 621         if (n == nullptr || n == top || n == mem) {
 622           continue;
 623         } else if (unique_input == nullptr) {
 624           unique_input = n;
 625         } else if (unique_input != n) {
 626           unique_input = top;
 627           break;
 628         }
 629       }
 630       if (unique_input != nullptr && unique_input != top) {
 631         mem = unique_input;
 632       } else {
 633         done = true;
 634       }
 635     } else if (mem->is_ArrayCopy()) {
 636       done = true;
 637     } else if (mem->is_top()) {
 638       // The slice is on a dead path. Returning nullptr would lead to elimination
 639       // bailout, but we want to prevent that. Just forwarding the top is also legal,
 640       // and IGVN can just clean things up, and remove whatever receives top.
 641       return mem;
 642     } else {
 643       DEBUG_ONLY( mem->dump(); )
 644       assert(false, "unexpected node");
 645     }
 646   }
 647   if (mem != nullptr) {
 648     if (mem == start_mem || mem == alloc_mem) {
 649       // hit a sentinel, return appropriate value
 650       return value_from_alloc(ft, adr_t, alloc);
 651     } else if (mem->is_Store()) {
 652       Node* n = mem->in(MemNode::ValueIn);
 653       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 654       n = bs->step_over_gc_barrier(n);
 655       return n;
 656     } else if (mem->is_Phi()) {
 657       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 658       Node_Stack value_phis(8);
 659       Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 660       if (phi != nullptr) {
 661         return phi;
 662       } else {
 663         // Kill all new Phis
 664         while(value_phis.is_nonempty()) {
 665           Node* n = value_phis.node();
 666           _igvn.replace_node(n, C->top());
 667           value_phis.pop();
 668         }
 669       }
 670     } else if (mem->is_ArrayCopy()) {
 671       // Rematerialize the scalar-replaced array. If possible, pin the loads to the uncommon path of the uncommon trap.
 672       // Check for each element of the source array, whether it was modified. If not, pin both memory and control to
 673       // the uncommon path. Otherwise, use the control and memory state of the arraycopy. Control and memory state must
 674       // come from the same source to prevent anti-dependence problems in the backend.
 675       ArrayCopyNode* ac = mem->as_ArrayCopy();
 676       Node* ac_ctl = ac->control();
 677       Node* ac_mem = ac->memory();
 678       if (ctl->is_Proj() && ctl->as_Proj()->is_uncommon_trap_proj()) {
 679         // pin the loads in the uncommon trap path
 680         ac_ctl = ctl;
 681         ac_mem = orig_mem;
 682       }
 683       return make_arraycopy_load(ac, offset, ac_ctl, ac_mem, ft, ftype, alloc);
 684     }
 685   }
 686   // Something went wrong.
 687   return nullptr;
 688 }
 689 
 690 // Search the last value stored into the inline type's fields (for flat arrays).
 691 Node* PhaseMacroExpand::inline_type_from_mem(ciInlineKlass* vk, const TypeAryPtr* elem_adr_type, int elem_idx, int offset_in_element, bool null_free, AllocateNode* alloc, SafePointNode* sfpt) {
 692   auto report_failure = [&](int field_offset_in_element, bool is_forced_failure) {
 693 #ifndef PRODUCT
 694     if (PrintEliminateAllocations) {
 695       ciInlineKlass* elem_klass = elem_adr_type->elem()->inline_klass();
 696       int offset = field_offset_in_element + elem_klass->payload_offset();
 697       ciField* flattened_field = elem_klass->get_field_by_offset(offset, false);
 698       assert(flattened_field != nullptr, "must have a field of type %s at offset %d", elem_klass->name()->as_utf8(), offset);
 699 
 700       tty->print("=== At SafePoint node %d ", sfpt->_idx);
 701       if (is_forced_failure) {
 702         tty->print_raw("forcibly abort elimination");
 703       } else {
 704         tty->print("can't find value of field [%s] of array element [%d]", flattened_field->name()->as_utf8(), elem_idx);
 705       }
 706       tty->print(", which prevents elimination of: ");
 707       alloc->dump();
 708     }
 709 #endif // PRODUCT
 710   };
 711 
 712   // Create a new InlineTypeNode and retrieve the field values from memory
 713   InlineTypeNode* vt = InlineTypeNode::make_uninitialized(_igvn, vk, null_free);
 714   transform_later(vt);
 715   if (null_free) {
 716     vt->set_null_marker(_igvn);
 717   } else {
 718     int nm_offset_in_element = offset_in_element + vk->null_marker_offset_in_payload();
 719     const TypeAryPtr* nm_adr_type = elem_adr_type->with_field_offset(nm_offset_in_element);
 720     Node* nm_value = value_from_mem(sfpt, sfpt->control(), T_BOOLEAN, TypeInt::BOOL, nm_adr_type, alloc);
 721     bool force_scalarization_failure = StressEliminateAllocations &&
 722                                        (C->random() % StressEliminateAllocationsMean == 0);
 723     if (nm_value != nullptr && !force_scalarization_failure) {
 724       vt->set_null_marker(_igvn, nm_value);
 725     } else {
 726       report_failure(nm_offset_in_element, nm_value != nullptr);
 727       return nullptr;
 728     }
 729   }
 730 
 731   for (int i = 0; i < vk->nof_declared_nonstatic_fields(); ++i) {
 732     ciField* field = vt->field(i);
 733     ciType* field_type = field->type();
 734     int field_offset_in_element = offset_in_element + field->offset_in_bytes() - vk->payload_offset();
 735     Node* field_value = nullptr;
 736     assert(!field->is_flat() || field->type()->is_inlinetype(), "must be an inline type");
 737     if (field->is_flat()) {
 738       field_value = inline_type_from_mem(field_type->as_inline_klass(), elem_adr_type, elem_idx, field_offset_in_element, field->is_null_free(), alloc, sfpt);
 739     } else {
 740       const Type* ft = Type::get_const_type(field_type);
 741       BasicType bt = type2field[field_type->basic_type()];
 742       if (UseCompressedOops && !is_java_primitive(bt)) {
 743         ft = ft->make_narrowoop();
 744         bt = T_NARROWOOP;
 745       }
 746       // Each inline type field has its own memory slice
 747       const TypeAryPtr* field_adr_type = elem_adr_type->with_field_offset(field_offset_in_element);
 748       field_value = value_from_mem(sfpt, sfpt->control(), bt, ft, field_adr_type, alloc);
 749       bool force_scalarization_failure = StressEliminateAllocations &&
 750                                          (C->random() % StressEliminateAllocationsMean == 0);
 751       if (field_value == nullptr || force_scalarization_failure) {
 752         report_failure(field_offset_in_element, field_value != nullptr);
 753         return nullptr;
 754       } else if (ft->isa_narrowoop()) {
 755         assert(UseCompressedOops, "unexpected narrow oop");
 756         if (field_value->is_EncodeP()) {
 757           field_value = field_value->in(1);
 758         } else if (!field_value->is_InlineType()) {
 759           field_value = transform_later(new DecodeNNode(field_value, field_value->get_ptr_type()));
 760         }
 761       }
 762     }
 763     if (field_value != nullptr) {
 764       vt->set_field_value(i, field_value);
 765     } else {
 766       return nullptr;
 767     }
 768   }
 769   return vt;
 770 }
 771 
 772 // Check the possibility of scalar replacement.
 773 bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode* alloc, Unique_Node_List* safepoints) {
 774   //  Scan the uses of the allocation to check for anything that would
 775   //  prevent us from eliminating it.
 776   NOT_PRODUCT( const char* fail_eliminate = nullptr; )
 777   DEBUG_ONLY( Node* disq_node = nullptr; )
 778   bool can_eliminate = true;
 779   bool reduce_merge_precheck = (safepoints == nullptr);
 780 
 781   Unique_Node_List worklist;
 782   Node* res = alloc->result_cast();
 783   const TypeOopPtr* res_type = nullptr;
 784   if (res == nullptr) {
 785     // All users were eliminated.
 786   } else if (!res->is_CheckCastPP()) {
 787     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 788     can_eliminate = false;
 789   } else {
 790     worklist.push(res);
 791     res_type = igvn->type(res)->isa_oopptr();
 792     if (res_type == nullptr) {
 793       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
 794       can_eliminate = false;
 795     } else if (!res_type->klass_is_exact()) {
 796       NOT_PRODUCT(fail_eliminate = "Not an exact type.";)
 797       can_eliminate = false;
 798     } else if (res_type->isa_aryptr()) {
 799       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 800       if (length < 0) {
 801         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 802         can_eliminate = false;
 803       }
 804     }
 805   }
 806 
 807   while (can_eliminate && worklist.size() > 0) {
 808     BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 809     res = worklist.pop();
 810     for (DUIterator_Fast jmax, j = res->fast_outs(jmax); j < jmax && can_eliminate; j++) {
 811       Node* use = res->fast_out(j);
 812 
 813       if (use->is_AddP()) {
 814         const TypePtr* addp_type = igvn->type(use)->is_ptr();
 815         int offset = addp_type->offset();
 816 
 817         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 818           NOT_PRODUCT(fail_eliminate = "Undefined field reference";)
 819           can_eliminate = false;
 820           break;
 821         }
 822         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 823                                    k < kmax && can_eliminate; k++) {
 824           Node* n = use->fast_out(k);
 825           if ((n->is_Mem() && n->as_Mem()->is_mismatched_access()) || n->is_LoadFlat() || n->is_StoreFlat()) {
 826             DEBUG_ONLY(disq_node = n);
 827             NOT_PRODUCT(fail_eliminate = "Mismatched access");
 828             can_eliminate = false;
 829           }
 830           if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n) && !reduce_merge_precheck) {
 831             DEBUG_ONLY(disq_node = n;)
 832             if (n->is_Load() || n->is_LoadStore()) {
 833               NOT_PRODUCT(fail_eliminate = "Field load";)
 834             } else {
 835               NOT_PRODUCT(fail_eliminate = "Not store field reference";)
 836             }
 837             can_eliminate = false;
 838           }
 839         }
 840       } else if (use->is_ArrayCopy() &&
 841                  (use->as_ArrayCopy()->is_clonebasic() ||
 842                   use->as_ArrayCopy()->is_arraycopy_validated() ||
 843                   use->as_ArrayCopy()->is_copyof_validated() ||
 844                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
 845                  use->in(ArrayCopyNode::Dest) == res) {
 846         // ok to eliminate
 847       } else if (use->is_ReachabilityFence() && OptimizeReachabilityFences) {
 848         // ok to eliminate
 849       } else if (use->is_SafePoint()) {
 850         SafePointNode* sfpt = use->as_SafePoint();
 851         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 852           // Object is passed as argument.
 853           DEBUG_ONLY(disq_node = use;)
 854           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 855           can_eliminate = false;
 856         }
 857         Node* sfptMem = sfpt->memory();
 858         if (sfptMem == nullptr || sfptMem->is_top()) {
 859           DEBUG_ONLY(disq_node = use;)
 860           NOT_PRODUCT(fail_eliminate = "null or TOP memory";)
 861           can_eliminate = false;
 862         } else if (!reduce_merge_precheck) {
 863           assert(!res->is_Phi() || !res->as_Phi()->can_be_inline_type(), "Inline type allocations should not have safepoint uses");
 864           safepoints->push(sfpt);
 865         }
 866       } else if (use->is_InlineType() && use->as_InlineType()->get_oop() == res) {
 867         // Look at uses
 868         for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) {
 869           Node* u = use->fast_out(k);
 870           if (u->is_InlineType()) {
 871             // Use in flat field can be eliminated
 872             InlineTypeNode* vt = u->as_InlineType();
 873             for (uint i = 0; i < vt->field_count(); ++i) {
 874               if (vt->field_value(i) == use && !vt->field(i)->is_flat()) {
 875                 can_eliminate = false; // Use in non-flat field
 876                 break;
 877               }
 878             }
 879           } else {
 880             // Add other uses to the worklist to process individually
 881             worklist.push(use);
 882           }
 883         }
 884       } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
 885         // Store to mark word of inline type larval buffer
 886         assert(res_type->is_inlinetypeptr(), "Unexpected store to mark word");
 887       } else if (res_type->is_inlinetypeptr() && (use->Opcode() == Op_MemBarRelease || use->Opcode() == Op_MemBarStoreStore)) {
 888         // Inline type buffer allocations are followed by a membar
 889       } else if (reduce_merge_precheck &&
 890                  (use->is_Phi() || use->is_EncodeP() ||
 891                   use->Opcode() == Op_MemBarRelease ||
 892                   (UseStoreStoreForCtor && use->Opcode() == Op_MemBarStoreStore))) {
 893         // Nothing to do
 894       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 895         if (use->is_Phi()) {
 896           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 897             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 898           } else {
 899             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 900           }
 901           DEBUG_ONLY(disq_node = use;)
 902         } else {
 903           if (use->Opcode() == Op_Return) {
 904             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 905           } else {
 906             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 907           }
 908           DEBUG_ONLY(disq_node = use;)
 909         }
 910         can_eliminate = false;
 911       } else {
 912         assert(use->Opcode() == Op_CastP2X, "should be");
 913         assert(!use->has_out_with(Op_OrL), "should have been removed because oop is never null");
 914       }
 915     }
 916   }
 917 
 918 #ifndef PRODUCT
 919   if (PrintEliminateAllocations && safepoints != nullptr) {
 920     if (can_eliminate) {
 921       tty->print("Scalar ");
 922       if (res == nullptr)
 923         alloc->dump();
 924       else
 925         res->dump();
 926     } else {
 927       tty->print("NotScalar (%s)", fail_eliminate);
 928       if (res == nullptr)
 929         alloc->dump();
 930       else
 931         res->dump();
 932 #ifdef ASSERT
 933       if (disq_node != nullptr) {
 934           tty->print("  >>>> ");
 935           disq_node->dump();
 936       }
 937 #endif /*ASSERT*/
 938     }
 939   }
 940 
 941   if (TraceReduceAllocationMerges && !can_eliminate && reduce_merge_precheck) {
 942     tty->print_cr("\tCan't eliminate allocation because '%s': ", fail_eliminate != nullptr ? fail_eliminate : "");
 943     DEBUG_ONLY(if (disq_node != nullptr) disq_node->dump();)
 944   }
 945 #endif
 946   return can_eliminate;

1020     // CheckCastPP result was not updated in the stack slot, and so
1021     // we ended up using the CastPP. That means that the field knows
1022     // that it should get an oop from an interface, but the value lost
1023     // that information, and so it is not a subtype.
1024     // There may be other issues, feel free to investigate further!
1025     if (!is_java_primitive(value_bt)) { return; }
1026 
1027     tty->print_cr("value not compatible for field: %s vs %s",
1028                   type2name(value_bt),
1029                   type2name(field_bt));
1030     tty->print("value_type: ");
1031     value_type->dump();
1032     tty->cr();
1033     tty->print("field_type: ");
1034     field_type->dump();
1035     tty->cr();
1036     assert(false, "value_type does not fit field_type");
1037   }
1038 #endif
1039 
1040 void PhaseMacroExpand::process_field_value_at_safepoint(const Type* field_type, Node* field_val, SafePointNode* sfpt, Unique_Node_List* value_worklist) {
1041   if (UseCompressedOops && field_type->isa_narrowoop()) {
1042     // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
1043     // to be able scalar replace the allocation.
1044     if (field_val->is_EncodeP()) {
1045       field_val = field_val->in(1);
1046     } else if (!field_val->is_InlineType()) {
1047       field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
1048     }
1049   }
1050 
1051   // Keep track of inline types to scalarize them later
1052   if (field_val->is_InlineType()) {
1053     value_worklist->push(field_val);
1054   } else if (field_val->is_Phi()) {
1055     PhiNode* phi = field_val->as_Phi();
1056     // Eagerly replace inline type phis now since we could be removing an inline type allocation where we must
1057     // scalarize all its fields in safepoints.
1058     field_val = phi->try_push_inline_types_down(&_igvn, true);
1059     if (field_val->is_InlineType()) {
1060       value_worklist->push(field_val);
1061     }
1062   }
1063   DEBUG_ONLY(verify_type_compatability(field_val->bottom_type(), field_type);)
1064   sfpt->add_req(field_val);
1065 }
1066 
1067 bool PhaseMacroExpand::add_array_elems_to_safepoint(AllocateNode* alloc, const TypeAryPtr* array_type, SafePointNode* sfpt, Unique_Node_List* value_worklist) {
1068   const Type* elem_type = array_type->elem();
1069   BasicType basic_elem_type = elem_type->array_element_basic_type();
1070 
1071   intptr_t elem_size;
1072   uint header_size;
1073   if (array_type->is_flat()) {
1074     elem_size = array_type->flat_elem_size();
1075     header_size = arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT);
1076   } else {
1077     elem_size = type2aelembytes(basic_elem_type);
1078     header_size = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
1079   }
1080 
1081   int n_elems = alloc->in(AllocateNode::ALength)->get_int();
1082   for (int elem_idx = 0; elem_idx < n_elems; elem_idx++) {
1083     intptr_t elem_offset = header_size + elem_idx * elem_size;
1084     const TypeAryPtr* elem_adr_type = array_type->with_offset(elem_offset);
1085     Node* elem_val;
1086     if (array_type->is_flat()) {
1087       ciInlineKlass* elem_klass = elem_type->inline_klass();
1088       assert(elem_klass->maybe_flat_in_array(), "must be flat in array");
1089       elem_val = inline_type_from_mem(elem_klass, elem_adr_type, elem_idx, 0, array_type->is_null_free(), alloc, sfpt);
1090     } else {
1091       elem_val = value_from_mem(sfpt, sfpt->control(), basic_elem_type, elem_type, elem_adr_type, alloc);
1092     }
1093     bool force_scalarization_failure = StressEliminateAllocations &&
1094                                        (C->random() % StressEliminateAllocationsMean == 0);
1095     if (elem_val == nullptr || force_scalarization_failure) {
1096 #ifndef PRODUCT
1097       if (PrintEliminateAllocations) {
1098         tty->print("=== At SafePoint node %d ", sfpt->_idx);
1099         if (elem_val == nullptr) {
1100           tty->print("can't find value of array element [%d]", elem_idx);
1101         } else {
1102           assert(force_scalarization_failure, "sanity");
1103           tty->print_raw("forcibly abort elimination");
1104         }
1105         tty->print(", which prevents elimination of: ");
1106         alloc->dump();
1107       }
1108 #endif // PRODUCT
1109       return false;
1110     }
1111 
1112     process_field_value_at_safepoint(elem_type, elem_val, sfpt, value_worklist);
1113   }
1114 
1115   return true;
1116 }
1117 
1118 // Recursively adds all flattened fields of a type 'iklass' inside 'base' to 'sfpt'.
1119 // 'offset_minus_header' refers to the offset of the payload of 'iklass' inside 'base' minus the
1120 // payload offset of 'iklass'. If 'base' is of type 'iklass' then 'offset_minus_header' == 0.
1121 bool PhaseMacroExpand::add_inst_fields_to_safepoint(ciInstanceKlass* iklass, AllocateNode* alloc, Node* base, int offset_minus_header, SafePointNode* sfpt, Unique_Node_List* value_worklist) {
1122   const TypeInstPtr* base_type = _igvn.type(base)->is_instptr();
1123   auto report_failure = [&](int offset, bool is_forced_failure) {
1124 #ifndef PRODUCT
1125     if (PrintEliminateAllocations) {
1126       ciInstanceKlass* base_klass = base_type->instance_klass();
1127       ciField* flattened_field = base_klass->get_field_by_offset(offset, false);
1128       assert(flattened_field != nullptr, "must have a field of type %s at offset %d", base_klass->name()->as_utf8(), offset);
1129       tty->print("=== At SafePoint node %d ", sfpt->_idx);
1130       if (is_forced_failure) {
1131         tty->print_raw("forcibly abort elimination");
1132       } else {
1133         tty->print_raw("can't find value of field: ");
1134         flattened_field->print();
1135         int field_idx = C->alias_type(flattened_field)->index();
1136         tty->print(" (alias_idx=%d)", field_idx);
1137       }
1138       tty->print(", which prevents elimination of: ");
1139       base->dump();
1140     }
1141 #endif // PRODUCT
1142   };
1143 
1144   for (int i = 0; i < iklass->nof_declared_nonstatic_fields(); i++) {
1145     ciField* field = iklass->declared_nonstatic_field_at(i);
1146     if (field->is_flat()) {
1147       ciInlineKlass* fvk = field->type()->as_inline_klass();
1148       int field_offset_minus_header = offset_minus_header + field->offset_in_bytes() - fvk->payload_offset();
1149       bool success = add_inst_fields_to_safepoint(fvk, alloc, base, field_offset_minus_header, sfpt, value_worklist);
1150       if (!success) {
1151         return false;
1152       }
1153 
1154       // The null marker of a field is added right after we scalarize that field
1155       if (!field->is_null_free()) {
1156         int nm_offset = offset_minus_header + field->null_marker_offset();
1157         Node* null_marker = value_from_mem(sfpt, sfpt->control(), T_BOOLEAN, TypeInt::BOOL, base_type->with_offset(nm_offset), alloc);
1158         bool force_scalarization_failure = StressEliminateAllocations &&
1159                                            (C->random() % StressEliminateAllocationsMean == 0);
1160         if (null_marker == nullptr || force_scalarization_failure) {
1161           report_failure(nm_offset, null_marker != nullptr);
1162           return false;
1163         }
1164         process_field_value_at_safepoint(TypeInt::BOOL, null_marker, sfpt, value_worklist);
1165       }
1166 
1167       continue;
1168     }
1169 
1170     int offset = offset_minus_header + field->offset_in_bytes();
1171     ciType* elem_type = field->type();
1172     BasicType basic_elem_type = field->layout_type();
1173 
1174     const Type* field_type;
1175     if (is_reference_type(basic_elem_type)) {
1176       if (!elem_type->is_loaded()) {
1177         field_type = TypeInstPtr::BOTTOM;
1178       } else {
1179         field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
1180       }
1181       if (UseCompressedOops) {
1182         field_type = field_type->make_narrowoop();
1183         basic_elem_type = T_NARROWOOP;
1184       }
1185     } else {
1186       field_type = Type::get_const_basic_type(basic_elem_type);
1187     }
1188 
1189     const TypeInstPtr* field_addr_type = base_type->add_offset(offset)->isa_instptr();
1190     Node* field_val = value_from_mem(sfpt, sfpt->control(), basic_elem_type, field_type, field_addr_type, alloc);
1191     bool force_scalarization_failure = StressEliminateAllocations &&
1192                                        (C->random() % StressEliminateAllocationsMean == 0);
1193     if (field_val == nullptr || force_scalarization_failure) {
1194       report_failure(offset, field_val != nullptr);
1195       return false;
1196     }
1197     process_field_value_at_safepoint(field_type, field_val, sfpt, value_worklist);
1198   }
1199 
1200   return true;
1201 }
1202 
1203 SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_description(AllocateNode* alloc, SafePointNode* sfpt,
1204                                                                                   Unique_Node_List* value_worklist) {
1205   assert(sfpt->jvms()->endoff() == sfpt->req(), "no extra edges past debug info allowed");
1206 
1207   // Fields of scalar objs are referenced only at the end
1208   // of regular debuginfo at the last (youngest) JVMS.
1209   // Record relative start index.
1210   ciInstanceKlass* iklass    = nullptr;


1211   const TypeOopPtr* res_type = nullptr;
1212   int nfields                = 0;


1213   uint first_ind             = (sfpt->req() - sfpt->jvms()->scloff());
1214   Node* res                  = alloc->result_cast();
1215 
1216   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
1217   assert(sfpt->jvms() != nullptr, "missed JVMS");
1218   uint before_sfpt_req = sfpt->req();
1219 
1220   if (res != nullptr) { // Could be null when there are no users
1221     res_type = _igvn.type(res)->isa_oopptr();
1222 
1223     if (res_type->isa_instptr()) {
1224       // find the fields of the class which will be needed for safepoint debug information
1225       iklass = res_type->is_instptr()->instance_klass();
1226       nfields = iklass->nof_nonstatic_fields();
1227     } else {
1228       // find the array's elements which will be needed for safepoint debug information
1229       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
1230       assert(nfields >= 0, "must be an array klass.");
1231     }
1232 
1233     if (res->bottom_type()->is_inlinetypeptr()) {
1234       // Nullable inline types have a null marker field which is added to the safepoint when scalarizing them (see
1235       // InlineTypeNode::make_scalar_in_safepoint()). When having circular inline types, we stop scalarizing at depth 1
1236       // to avoid an endless recursion. Therefore, we do not have a SafePointScalarObjectNode node here, yet.
1237       // We are about to create a SafePointScalarObjectNode as if this is a normal object. Add an additional int input
1238       // with value 1 which sets the null marker to true to indicate that the object is always non-null. This input is checked
1239       // later in PhaseOutput::filLocArray() for inline types.
1240       sfpt->add_req(_igvn.intcon(1));
1241     }
1242   }
1243 
1244   SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type, alloc, first_ind, sfpt->jvms()->depth(), nfields);
1245   sobj->init_req(0, C->root());
1246   transform_later(sobj);
1247 
1248   if (res == nullptr) {
1249     sfpt->jvms()->set_endoff(sfpt->req());
1250     return sobj;
1251   }






































































1252 
1253   bool success;
1254   if (iklass == nullptr) {
1255     success = add_array_elems_to_safepoint(alloc, res_type->is_aryptr(), sfpt, value_worklist);
1256   } else {
1257     success = add_inst_fields_to_safepoint(iklass, alloc, res, 0, sfpt, value_worklist);
1258   }
1259 
1260   // We weren't able to find a value for this field, remove all the fields added to the safepoint
1261   if (!success) {
1262     for (uint i = sfpt->req() - 1; i >= before_sfpt_req; i--) {
1263       sfpt->del_req(i);




1264     }
1265     _igvn._worklist.push(sfpt);
1266     return nullptr;
1267   }
1268 
1269   sfpt->jvms()->set_endoff(sfpt->req());

1270   return sobj;
1271 }
1272 
1273 // Do scalar replacement.
1274 bool PhaseMacroExpand::scalar_replacement(AllocateNode* alloc, Unique_Node_List& safepoints) {
1275   Unique_Node_List safepoints_done;
1276   Node* res = alloc->result_cast();
1277   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
1278   const TypeOopPtr* res_type = nullptr;
1279   if (res != nullptr) { // Could be null when there are no users
1280     res_type = _igvn.type(res)->isa_oopptr();
1281   }
1282 
1283   // Process the safepoint uses
1284   Unique_Node_List value_worklist;
1285   while (safepoints.size() > 0) {
1286     SafePointNode* sfpt = safepoints.pop()->as_SafePoint();
1287 
1288     SafePointNode::NodeEdgeTempStorage non_debug_edges_worklist(igvn());
1289 
1290     // All sfpt inputs are implicitly included into debug info during the scalarization process below.
1291     // Keep non-debug inputs separately, so they stay non-debug.
1292     sfpt->remove_non_debug_edges(non_debug_edges_worklist);
1293 
1294     SafePointScalarObjectNode* sobj = create_scalarized_object_description(alloc, sfpt, &value_worklist);
1295 
1296     if (sobj == nullptr) {
1297       sfpt->restore_non_debug_edges(non_debug_edges_worklist);
1298       undo_previous_scalarizations(safepoints_done, alloc);
1299       return false;
1300     }
1301 
1302     // Now make a pass over the debug information replacing any references
1303     // to the allocated object with "sobj"
1304     JVMState *jvms = sfpt->jvms();
1305     sfpt->replace_edges_in_range(res, sobj, jvms->debug_start(), jvms->debug_end(), &_igvn);
1306     non_debug_edges_worklist.remove_edge_if_present(res); // drop scalarized input from non-debug info
1307     sfpt->restore_non_debug_edges(non_debug_edges_worklist);
1308     _igvn._worklist.push(sfpt);
1309 
1310     // keep it for rollback
1311     safepoints_done.push(sfpt);
1312   }
1313   // Scalarize inline types that were added to the safepoint.
1314   // Don't allow linking a constant oop (if available) for flat array elements
1315   // because Deoptimization::reassign_flat_array_elements needs field values.
1316   bool allow_oop = (res_type != nullptr) && !res_type->is_flat();
1317   for (uint i = 0; i < value_worklist.size(); ++i) {
1318     InlineTypeNode* vt = value_worklist.at(i)->as_InlineType();
1319     vt->make_scalar_in_safepoints(&_igvn, allow_oop);
1320   }
1321   return true;
1322 }
1323 
1324 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
1325   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
1326   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
1327   if (ctl_proj != nullptr) {
1328     igvn.replace_node(ctl_proj, n->in(0));
1329   }
1330   if (mem_proj != nullptr) {
1331     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
1332   }
1333 }
1334 
1335 // Process users of eliminated allocation.
1336 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc, bool inline_alloc) {
1337   Unique_Node_List worklist;
1338   Node* res = alloc->result_cast();
1339   if (res != nullptr) {
1340     worklist.push(res);
1341   }
1342   while (worklist.size() > 0) {
1343     res = worklist.pop();
1344     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
1345       Node *use = res->last_out(j);
1346       uint oc1 = res->outcnt();
1347 
1348       if (use->is_AddP()) {
1349         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
1350           Node *n = use->last_out(k);
1351           uint oc2 = use->outcnt();
1352           if (n->is_Store()) {
1353             for (DUIterator_Fast pmax, p = n->fast_outs(pmax); p < pmax; p++) {
1354               MemBarNode* mb = n->fast_out(p)->isa_MemBar();
1355               if (mb != nullptr && mb->req() <= MemBarNode::Precedent && mb->in(MemBarNode::Precedent) == n) {
1356                 // MemBarVolatiles should have been removed by MemBarNode::Ideal() for non-inline allocations
1357                 assert(inline_alloc, "MemBarVolatile should be eliminated for non-escaping object");
1358                 mb->remove(&_igvn);
1359               }



1360             }

1361             _igvn.replace_node(n, n->in(MemNode::Memory));
1362           } else {
1363             eliminate_gc_barrier(n);
1364           }
1365           k -= (oc2 - use->outcnt());
1366         }
1367         _igvn.remove_dead_node(use, PhaseIterGVN::NodeOrigin::Graph);
1368       } else if (use->is_ArrayCopy()) {
1369         // Disconnect ArrayCopy node
1370         ArrayCopyNode* ac = use->as_ArrayCopy();
1371         if (ac->is_clonebasic()) {
1372           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
1373           disconnect_projections(ac, _igvn);
1374           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
1375           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
1376           disconnect_projections(membar_before->as_MemBar(), _igvn);
1377           if (membar_after->is_MemBar()) {
1378             disconnect_projections(membar_after->as_MemBar(), _igvn);
1379           }
1380         } else {
1381           assert(ac->is_arraycopy_validated() ||
1382                  ac->is_copyof_validated() ||
1383                  ac->is_copyofrange_validated(), "unsupported");
1384           CallProjections* callprojs = ac->extract_projections(true);

1385 
1386           _igvn.replace_node(callprojs->fallthrough_ioproj, ac->in(TypeFunc::I_O));
1387           _igvn.replace_node(callprojs->fallthrough_memproj, ac->in(TypeFunc::Memory));
1388           _igvn.replace_node(callprojs->fallthrough_catchproj, ac->in(TypeFunc::Control));
1389 
1390           // Set control to top. IGVN will remove the remaining projections
1391           ac->set_req(0, top());
1392           ac->replace_edge(res, top(), &_igvn);
1393 
1394           // Disconnect src right away: it can help find new
1395           // opportunities for allocation elimination
1396           Node* src = ac->in(ArrayCopyNode::Src);
1397           ac->replace_edge(src, top(), &_igvn);
1398           // src can be top at this point if src and dest of the
1399           // arraycopy were the same
1400           if (src->outcnt() == 0 && !src->is_top()) {
1401             _igvn.remove_dead_node(src, PhaseIterGVN::NodeOrigin::Graph);
1402           }
1403         }
1404         _igvn._worklist.push(ac);
1405       } else if (use->is_InlineType()) {
1406         assert(use->as_InlineType()->get_oop() == res, "unexpected inline type ptr use");
1407         // Cut off oop input and remove known instance id from type
1408         _igvn.rehash_node_delayed(use);
1409         use->as_InlineType()->set_oop(_igvn, _igvn.zerocon(T_OBJECT));
1410         use->as_InlineType()->set_is_buffered(_igvn, false);
1411         const TypeOopPtr* toop = _igvn.type(use)->is_oopptr()->cast_to_instance_id(TypeOopPtr::InstanceBot);
1412         _igvn.set_type(use, toop);
1413         use->as_InlineType()->set_type(toop);
1414         // Process users
1415         for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) {
1416           Node* u = use->fast_out(k);
1417           if (!u->is_InlineType() && !u->is_StoreFlat()) {
1418             worklist.push(u);
1419           }
1420         }
1421       } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
1422         // Store to mark word of inline type larval buffer
1423         assert(inline_alloc, "Unexpected store to mark word");
1424         _igvn.replace_node(use, use->in(MemNode::Memory));
1425       } else if (use->Opcode() == Op_MemBarRelease || use->Opcode() == Op_MemBarStoreStore) {
1426         // Inline type buffer allocations are followed by a membar
1427         assert(inline_alloc, "Unexpected MemBarRelease");
1428         use->as_MemBar()->remove(&_igvn);
1429       } else if (use->is_ReachabilityFence() && OptimizeReachabilityFences) {
1430         use->as_ReachabilityFence()->clear_referent(_igvn); // redundant fence; will be removed during IGVN
1431       } else {
1432         eliminate_gc_barrier(use);
1433       }
1434       j -= (oc1 - res->outcnt());
1435     }
1436     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1437     _igvn.remove_dead_node(res, PhaseIterGVN::NodeOrigin::Graph);
1438   }
1439 
1440   //
1441   // Process other users of allocation's projections
1442   //
1443   if (_callprojs->resproj[0] != nullptr && _callprojs->resproj[0]->outcnt() != 0) {
1444     // First disconnect stores captured by Initialize node.
1445     // If Initialize node is eliminated first in the following code,
1446     // it will kill such stores and DUIterator_Last will assert.
1447     for (DUIterator_Fast jmax, j = _callprojs->resproj[0]->fast_outs(jmax);  j < jmax; j++) {
1448       Node* use = _callprojs->resproj[0]->fast_out(j);
1449       if (use->is_AddP()) {
1450         // raw memory addresses used only by the initialization
1451         _igvn.replace_node(use, C->top());
1452         --j; --jmax;
1453       }
1454     }
1455     for (DUIterator_Last jmin, j = _callprojs->resproj[0]->last_outs(jmin); j >= jmin; ) {
1456       Node* use = _callprojs->resproj[0]->last_out(j);
1457       uint oc1 = _callprojs->resproj[0]->outcnt();
1458       if (use->is_Initialize()) {
1459         // Eliminate Initialize node.
1460         InitializeNode *init = use->as_Initialize();
1461         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1462         if (ctrl_proj != nullptr) {
1463           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1464 #ifdef ASSERT
1465           // If the InitializeNode has no memory out, it will die, and tmp will become null
1466           Node* tmp = init->in(TypeFunc::Control);
1467           assert(tmp == nullptr || tmp == _callprojs->fallthrough_catchproj, "allocation control projection");
1468 #endif
1469         }
1470         Node* mem = init->in(TypeFunc::Memory);
1471 #ifdef ASSERT
1472         if (init->number_of_projs(TypeFunc::Memory) > 0) {
1473           if (mem->is_MergeMem()) {
1474             assert(mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw) == _callprojs->fallthrough_memproj, "allocation memory projection");
1475           } else {
1476             assert(mem == _callprojs->fallthrough_memproj, "allocation memory projection");
1477           }
1478         }
1479 #endif
1480         init->replace_mem_projs_by(mem, &_igvn);
1481         assert(init->outcnt() == 0, "should only have had a control and some memory projections, and we removed them");
1482       } else if (use->Opcode() == Op_MemBarStoreStore) {
1483         // Inline type buffer allocations are followed by a membar
1484         assert(inline_alloc, "Unexpected MemBarStoreStore");
1485         use->as_MemBar()->remove(&_igvn);
1486       } else  {
1487         assert(false, "only Initialize or AddP expected");
1488       }
1489       j -= (oc1 - _callprojs->resproj[0]->outcnt());
1490     }
1491   }
1492   if (_callprojs->fallthrough_catchproj != nullptr) {
1493     _igvn.replace_node(_callprojs->fallthrough_catchproj, alloc->in(TypeFunc::Control));
1494   }
1495   if (_callprojs->fallthrough_memproj != nullptr) {
1496     _igvn.replace_node(_callprojs->fallthrough_memproj, alloc->in(TypeFunc::Memory));
1497   }
1498   if (_callprojs->catchall_memproj != nullptr) {
1499     _igvn.replace_node(_callprojs->catchall_memproj, C->top());
1500   }
1501   if (_callprojs->fallthrough_ioproj != nullptr) {
1502     _igvn.replace_node(_callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
1503   }
1504   if (_callprojs->catchall_ioproj != nullptr) {
1505     _igvn.replace_node(_callprojs->catchall_ioproj, C->top());
1506   }
1507   if (_callprojs->catchall_catchproj != nullptr) {
1508     _igvn.replace_node(_callprojs->catchall_catchproj, C->top());
1509   }
1510 }
1511 
1512 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1513   // If reallocation fails during deoptimization we'll pop all
1514   // interpreter frames for this compiled frame and that won't play
1515   // nice with JVMTI popframe.
1516   // We avoid this issue by eager reallocation when the popframe request
1517   // is received.
1518   if (!EliminateAllocations) {
1519     return false;
1520   }
1521   Node* klass = alloc->in(AllocateNode::KlassNode);
1522   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1523 
1524   // Attempt to eliminate inline type buffer allocations
1525   // regardless of usage and escape/replaceable status.
1526   bool inline_alloc = tklass->isa_instklassptr() &&
1527                       tklass->is_instklassptr()->instance_klass()->is_inlinetype();
1528   if (!alloc->_is_non_escaping && !inline_alloc) {
1529     return false;
1530   }
1531   // Eliminate boxing allocations which are not used
1532   // regardless scalar replaceable status.
1533   Node* res = alloc->result_cast();
1534   bool boxing_alloc = (res == nullptr) && C->eliminate_boxing() &&
1535                       tklass->isa_instklassptr() &&
1536                       tklass->is_instklassptr()->instance_klass()->is_box_klass();
1537   if (!alloc->_is_scalar_replaceable && !boxing_alloc && !inline_alloc) {
1538     return false;
1539   }
1540 
1541   _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1542 
1543   Unique_Node_List safepoints;
1544   if (!can_eliminate_allocation(&_igvn, alloc, &safepoints)) {
1545     return false;
1546   }
1547 
1548   if (!alloc->_is_scalar_replaceable) {
1549     assert(res == nullptr || inline_alloc, "sanity");
1550     // We can only eliminate allocation if all debug info references
1551     // are already replaced with SafePointScalarObject because
1552     // we can't search for a fields value without instance_id.
1553     if (safepoints.size() > 0) {
1554       return false;
1555     }
1556   }
1557 
1558   if (!scalar_replacement(alloc, safepoints)) {
1559     return false;
1560   }
1561 
1562   CompileLog* log = C->log();
1563   if (log != nullptr) {
1564     log->head("eliminate_allocation type='%d'",
1565               log->identify(tklass->exact_klass()));
1566     JVMState* p = alloc->jvms();
1567     while (p != nullptr) {
1568       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1569       p = p->caller();
1570     }
1571     log->tail("eliminate_allocation");
1572   }
1573 
1574   process_users_of_allocation(alloc, inline_alloc);
1575 
1576 #ifndef PRODUCT
1577   if (PrintEliminateAllocations) {
1578     if (alloc->is_AllocateArray())
1579       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1580     else
1581       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1582   }
1583 #endif
1584 
1585   return true;
1586 }
1587 
1588 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode* call) {
1589   // EA should remove all uses of non-escaping boxing node.
1590   if (!C->eliminate_boxing()) {
1591     return false;
1592   }
1593   for (uint i = TypeFunc::Parms; i < call->tf()->range_cc()->cnt(); ++i) {
1594     if (call->proj_out_or_null(i) != nullptr) {
1595       return false;
1596     }
1597   }
1598 
1599   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);


1600 
1601   process_users_of_allocation(call);



1602 
1603   CompileLog* log = C->log();
1604   if (log != nullptr) {
1605     const TypeInstPtr* t = nullptr;
1606     if (call->is_boxing_method()) {
1607       const TypeTuple* range = call->tf()->range_sig();
1608       t = range->field_at(TypeFunc::Parms)->isa_instptr();
1609     } else {
1610       assert(call->is_unboxing_method(), "Unexpected call");
1611       const TypeTuple* domain = call->tf()->domain_sig();
1612       t = domain->field_at(TypeFunc::Parms)->isa_instptr();
1613       assert(!t->maybe_null(), "missing receiver null check?");
1614     }
1615     log->head("eliminate_boxing type='%d'",
1616               log->identify(t->instance_klass()));
1617     JVMState* p = call->jvms();
1618     while (p != nullptr) {
1619       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1620       p = p->caller();
1621     }
1622     log->tail("eliminate_boxing");
1623   }
1624 


1625 #ifndef PRODUCT
1626   if (PrintEliminateAllocations) {
1627     tty->print("++++ Eliminated: %d ", call->_idx);
1628     call->method()->print_short_name(tty);
1629     tty->cr();
1630   }
1631 #endif
1632 
1633   return true;
1634 }
1635 

1636 Node* PhaseMacroExpand::make_load_raw(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) {
1637   Node* adr = off_heap_plus_addr(base, offset);
1638   const TypePtr* adr_type = adr->bottom_type()->is_ptr();
1639   Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt, MemNode::unordered);
1640   transform_later(value);
1641   return value;
1642 }
1643 
1644 
1645 Node* PhaseMacroExpand::make_store_raw(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) {
1646   Node* adr = off_heap_plus_addr(base, offset);
1647   mem = StoreNode::make(_igvn, ctl, mem, adr, nullptr, value, bt, MemNode::unordered);
1648   transform_later(mem);
1649   return mem;
1650 }
1651 
1652 //=============================================================================
1653 //
1654 //                              A L L O C A T I O N
1655 //

1689 // oop flavor.
1690 //
1691 //=============================================================================
1692 // FastAllocateSizeLimit value is in DOUBLEWORDS.
1693 // Allocations bigger than this always go the slow route.
1694 // This value must be small enough that allocation attempts that need to
1695 // trigger exceptions go the slow route.  Also, it must be small enough so
1696 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
1697 //=============================================================================j//
1698 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
1699 // The allocator will coalesce int->oop copies away.  See comment in
1700 // coalesce.cpp about how this works.  It depends critically on the exact
1701 // code shape produced here, so if you are changing this code shape
1702 // make sure the GC info for the heap-top is correct in and around the
1703 // slow-path call.
1704 //
1705 
1706 void PhaseMacroExpand::expand_allocate_common(
1707             AllocateNode* alloc, // allocation node to be expanded
1708             Node* length,  // array length for an array allocation
1709             Node* init_val, // value to initialize the array with
1710             const TypeFunc* slow_call_type, // Type of slow call
1711             address slow_call_address,  // Address of slow call
1712             Node* valid_length_test // whether length is valid or not
1713     )
1714 {
1715   Node* ctrl = alloc->in(TypeFunc::Control);
1716   Node* mem  = alloc->in(TypeFunc::Memory);
1717   Node* i_o  = alloc->in(TypeFunc::I_O);
1718   Node* size_in_bytes     = alloc->in(AllocateNode::AllocSize);
1719   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
1720   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1721   assert(ctrl != nullptr, "must have control");
1722 
1723   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1724   // they will not be used if "always_slow" is set
1725   enum { slow_result_path = 1, fast_result_path = 2 };
1726   Node *result_region = nullptr;
1727   Node *result_phi_rawmem = nullptr;
1728   Node *result_phi_rawoop = nullptr;
1729   Node *result_phi_i_o = nullptr;

1774 #endif
1775       yank_alloc_node(alloc);
1776       return;
1777     }
1778   }
1779 
1780   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1781   Node *slow_region = nullptr;
1782   Node *toobig_false = ctrl;
1783 
1784   // generate the initial test if necessary
1785   if (initial_slow_test != nullptr ) {
1786     assert (expand_fast_path, "Only need test if there is a fast path");
1787     slow_region = new RegionNode(3);
1788 
1789     // Now make the initial failure test.  Usually a too-big test but
1790     // might be a TRUE for finalizers.
1791     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1792     transform_later(toobig_iff);
1793     // Plug the failing-too-big test into the slow-path region
1794     Node* toobig_true = new IfTrueNode(toobig_iff);
1795     transform_later(toobig_true);
1796     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1797     toobig_false = new IfFalseNode(toobig_iff);
1798     transform_later(toobig_false);
1799   } else {
1800     // No initial test, just fall into next case
1801     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1802     toobig_false = ctrl;
1803     DEBUG_ONLY(slow_region = NodeSentinel);
1804   }
1805 
1806   // If we are here there are several possibilities
1807   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1808   // no_initial_check means a constant allocation.
1809   // - If check always evaluates to false -> expand_fast_path is false (see above)
1810   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1811   // if !allocation_has_use the fast path is empty
1812   // if !allocation_has_use && no_initial_check
1813   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1814   //   removed by yank_alloc_node above.
1815 
1816   Node *slow_mem = mem;  // save the current memory state for slow path
1817   // generate the fast allocation code unless we know that the initial test will always go slow
1818   if (expand_fast_path) {
1819     // Fast path modifies only raw memory.
1820     if (mem->is_MergeMem()) {
1821       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1822     }
1823 
1824     // allocate the Region and Phi nodes for the result
1825     result_region = new RegionNode(3);
1826     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1827     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1828 
1829     // Grab regular I/O before optional prefetch may change it.
1830     // Slow-path does no I/O so just set it to the original I/O.
1831     result_phi_i_o->init_req(slow_result_path, i_o);
1832 
1833     // Name successful fast-path variables
1834     Node* fast_oop_ctrl;
1835     Node* fast_oop_rawmem;
1836 
1837     if (allocation_has_use) {
1838       Node* needgc_ctrl = nullptr;
1839       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1840 
1841       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1842       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1843       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1844                                         fast_oop_ctrl, fast_oop_rawmem,
1845                                         prefetch_lines);
1846 
1847       if (initial_slow_test != nullptr) {
1848         // This completes all paths into the slow merge point
1849         slow_region->init_req(need_gc_path, needgc_ctrl);
1850         transform_later(slow_region);
1851       } else {
1852         // No initial slow path needed!
1853         // Just fall from the need-GC path straight into the VM call.
1854         slow_region = needgc_ctrl;
1855       }
1856 

1874     result_phi_i_o   ->init_req(fast_result_path, i_o);
1875     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1876   } else {
1877     slow_region = ctrl;
1878     result_phi_i_o = i_o; // Rename it to use in the following code.
1879   }
1880 
1881   // Generate slow-path call
1882   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1883                                OptoRuntime::stub_name(slow_call_address),
1884                                TypePtr::BOTTOM);
1885   call->init_req(TypeFunc::Control,   slow_region);
1886   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1887   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1888   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1889   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1890 
1891   call->init_req(TypeFunc::Parms+0, klass_node);
1892   if (length != nullptr) {
1893     call->init_req(TypeFunc::Parms+1, length);
1894     if (init_val != nullptr) {
1895       call->init_req(TypeFunc::Parms+2, init_val);
1896     }
1897   }
1898 
1899   // Copy debug information and adjust JVMState information, then replace
1900   // allocate node with the call
1901   call->copy_call_debug_info(&_igvn, alloc);
1902   // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify
1903   // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough
1904   // path dies).
1905   if (valid_length_test != nullptr) {
1906     call->add_req(valid_length_test);
1907   }
1908   if (expand_fast_path) {
1909     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1910   } else {
1911     // Hook i_o projection to avoid its elimination during allocation
1912     // replacement (when only a slow call is generated).
1913     call->set_req(TypeFunc::I_O, result_phi_i_o);
1914   }
1915   _igvn.replace_node(alloc, call);
1916   transform_later(call);
1917 
1918   // Identify the output projections from the allocate node and
1919   // adjust any references to them.
1920   // The control and io projections look like:
1921   //
1922   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1923   //  Allocate                   Catch
1924   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1925   //
1926   //  We are interested in the CatchProj nodes.
1927   //
1928   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1929 
1930   // An allocate node has separate memory projections for the uses on
1931   // the control and i_o paths. Replace the control memory projection with
1932   // result_phi_rawmem (unless we are only generating a slow call when
1933   // both memory projections are combined)
1934   if (expand_fast_path && _callprojs->fallthrough_memproj != nullptr) {
1935     _igvn.replace_in_uses(_callprojs->fallthrough_memproj, result_phi_rawmem);
1936   }
1937   // Now change uses of catchall_memproj to use fallthrough_memproj and delete
1938   // catchall_memproj so we end up with a call that has only 1 memory projection.
1939   if (_callprojs->catchall_memproj != nullptr) {
1940     if (_callprojs->fallthrough_memproj == nullptr) {
1941       _callprojs->fallthrough_memproj = new ProjNode(call, TypeFunc::Memory);
1942       transform_later(_callprojs->fallthrough_memproj);
1943     }
1944     _igvn.replace_in_uses(_callprojs->catchall_memproj, _callprojs->fallthrough_memproj);
1945     _igvn.remove_dead_node(_callprojs->catchall_memproj, PhaseIterGVN::NodeOrigin::Graph);
1946   }
1947 
1948   // An allocate node has separate i_o projections for the uses on the control
1949   // and i_o paths. Always replace the control i_o projection with result i_o
1950   // otherwise incoming i_o become dead when only a slow call is generated
1951   // (it is different from memory projections where both projections are
1952   // combined in such case).
1953   if (_callprojs->fallthrough_ioproj != nullptr) {
1954     _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, result_phi_i_o);
1955   }
1956   // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete
1957   // catchall_ioproj so we end up with a call that has only 1 i_o projection.
1958   if (_callprojs->catchall_ioproj != nullptr) {
1959     if (_callprojs->fallthrough_ioproj == nullptr) {
1960       _callprojs->fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O);
1961       transform_later(_callprojs->fallthrough_ioproj);
1962     }
1963     _igvn.replace_in_uses(_callprojs->catchall_ioproj, _callprojs->fallthrough_ioproj);
1964     _igvn.remove_dead_node(_callprojs->catchall_ioproj, PhaseIterGVN::NodeOrigin::Graph);
1965   }
1966 
1967   // if we generated only a slow call, we are done
1968   if (!expand_fast_path) {
1969     // Now we can unhook i_o.
1970     if (result_phi_i_o->outcnt() > 1) {
1971       call->set_req(TypeFunc::I_O, top());
1972     } else {
1973       assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1974       // Case of new array with negative size known during compilation.
1975       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1976       // following code since call to runtime will throw exception.
1977       // As result there will be no users of i_o after the call.
1978       // Leave i_o attached to this call to avoid problems in preceding graph.
1979     }
1980     return;
1981   }
1982 
1983   if (_callprojs->fallthrough_catchproj != nullptr) {
1984     ctrl = _callprojs->fallthrough_catchproj->clone();
1985     transform_later(ctrl);
1986     _igvn.replace_node(_callprojs->fallthrough_catchproj, result_region);
1987   } else {
1988     ctrl = top();
1989   }
1990   Node *slow_result;
1991   if (_callprojs->resproj[0] == nullptr) {
1992     // no uses of the allocation result
1993     slow_result = top();
1994   } else {
1995     slow_result = _callprojs->resproj[0]->clone();
1996     transform_later(slow_result);
1997     _igvn.replace_node(_callprojs->resproj[0], result_phi_rawoop);
1998   }
1999 
2000   // Plug slow-path into result merge point
2001   result_region->init_req( slow_result_path, ctrl);
2002   transform_later(result_region);
2003   if (allocation_has_use) {
2004     result_phi_rawoop->init_req(slow_result_path, slow_result);
2005     transform_later(result_phi_rawoop);
2006   }
2007   result_phi_rawmem->init_req(slow_result_path, _callprojs->fallthrough_memproj);
2008   transform_later(result_phi_rawmem);
2009   transform_later(result_phi_i_o);
2010   // This completes all paths into the result merge point
2011 }
2012 
2013 // Remove alloc node that has no uses.
2014 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
2015   Node* ctrl = alloc->in(TypeFunc::Control);
2016   Node* mem  = alloc->in(TypeFunc::Memory);
2017   Node* i_o  = alloc->in(TypeFunc::I_O);
2018 
2019   _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2020   if (_callprojs->resproj[0] != nullptr) {
2021     for (DUIterator_Fast imax, i = _callprojs->resproj[0]->fast_outs(imax); i < imax; i++) {
2022       Node* use = _callprojs->resproj[0]->fast_out(i);
2023       use->isa_MemBar()->remove(&_igvn);
2024       --imax;
2025       --i; // back up iterator
2026     }
2027     assert(_callprojs->resproj[0]->outcnt() == 0, "all uses must be deleted");
2028     _igvn.remove_dead_node(_callprojs->resproj[0], PhaseIterGVN::NodeOrigin::Graph);
2029   }
2030   if (_callprojs->fallthrough_catchproj != nullptr) {
2031     _igvn.replace_in_uses(_callprojs->fallthrough_catchproj, ctrl);
2032     _igvn.remove_dead_node(_callprojs->fallthrough_catchproj, PhaseIterGVN::NodeOrigin::Graph);
2033   }
2034   if (_callprojs->catchall_catchproj != nullptr) {
2035     _igvn.rehash_node_delayed(_callprojs->catchall_catchproj);
2036     _callprojs->catchall_catchproj->set_req(0, top());
2037   }
2038   if (_callprojs->fallthrough_proj != nullptr) {
2039     Node* catchnode = _callprojs->fallthrough_proj->unique_ctrl_out();
2040     _igvn.remove_dead_node(catchnode, PhaseIterGVN::NodeOrigin::Graph);
2041     _igvn.remove_dead_node(_callprojs->fallthrough_proj, PhaseIterGVN::NodeOrigin::Graph);
2042   }
2043   if (_callprojs->fallthrough_memproj != nullptr) {
2044     _igvn.replace_in_uses(_callprojs->fallthrough_memproj, mem);
2045     _igvn.remove_dead_node(_callprojs->fallthrough_memproj, PhaseIterGVN::NodeOrigin::Graph);
2046   }
2047   if (_callprojs->fallthrough_ioproj != nullptr) {
2048     _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, i_o);
2049     _igvn.remove_dead_node(_callprojs->fallthrough_ioproj, PhaseIterGVN::NodeOrigin::Graph);
2050   }
2051   if (_callprojs->catchall_memproj != nullptr) {
2052     _igvn.rehash_node_delayed(_callprojs->catchall_memproj);
2053     _callprojs->catchall_memproj->set_req(0, top());
2054   }
2055   if (_callprojs->catchall_ioproj != nullptr) {
2056     _igvn.rehash_node_delayed(_callprojs->catchall_ioproj);
2057     _callprojs->catchall_ioproj->set_req(0, top());
2058   }
2059 #ifndef PRODUCT
2060   if (PrintEliminateAllocations) {
2061     if (alloc->is_AllocateArray()) {
2062       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
2063     } else {
2064       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
2065     }
2066   }
2067 #endif
2068   _igvn.remove_dead_node(alloc, PhaseIterGVN::NodeOrigin::Graph);
2069 }
2070 
2071 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
2072                                                 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
2073   // If initialization is performed by an array copy, any required
2074   // MemBarStoreStore was already added. If the object does not
2075   // escape no need for a MemBarStoreStore. If the object does not
2076   // escape in its initializer and memory barrier (MemBarStoreStore or
2077   // stronger) is already added at exit of initializer, also no need

2171     Node* thread = new ThreadLocalNode();
2172     transform_later(thread);
2173 
2174     call->init_req(TypeFunc::Parms + 0, thread);
2175     call->init_req(TypeFunc::Parms + 1, oop);
2176     call->init_req(TypeFunc::Control, ctrl);
2177     call->init_req(TypeFunc::I_O    , top()); // does no i/o
2178     call->init_req(TypeFunc::Memory , rawmem);
2179     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
2180     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
2181     transform_later(call);
2182     ctrl = new ProjNode(call, TypeFunc::Control);
2183     transform_later(ctrl);
2184     rawmem = new ProjNode(call, TypeFunc::Memory);
2185     transform_later(rawmem);
2186   }
2187 }
2188 
2189 // Helper for PhaseMacroExpand::expand_allocate_common.
2190 // Initializes the newly-allocated storage.
2191 Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc,
2192                                           Node* control, Node* rawmem, Node* object,
2193                                           Node* klass_node, Node* length,
2194                                           Node* size_in_bytes) {

2195   InitializeNode* init = alloc->initialization();
2196   // Store the klass & mark bits
2197   Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem);
2198   if (!mark_node->is_Con()) {
2199     transform_later(mark_node);
2200   }
2201   rawmem = make_store_raw(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
2202 
2203   if (!UseCompactObjectHeaders) {
2204     rawmem = make_store_raw(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2205   }
2206   int header_size = alloc->minimum_header_size();  // conservatively small
2207 
2208   // Array length
2209   if (length != nullptr) {         // Arrays need length field
2210     rawmem = make_store_raw(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
2211     // conservatively small header size:
2212     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
2213     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
2214       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_exact_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
2215       if (is_reference_type(elem, true)) {
2216         elem = T_OBJECT;
2217       }
2218       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
2219     }
2220   }
2221 
2222   // Clear the object body, if necessary.
2223   if (init == nullptr) {
2224     // The init has somehow disappeared; be cautious and clear everything.
2225     //
2226     // This can happen if a node is allocated but an uncommon trap occurs
2227     // immediately.  In this case, the Initialize gets associated with the
2228     // trap, and may be placed in a different (outer) loop, if the Allocate
2229     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
2230     // there can be two Allocates to one Initialize.  The answer in all these
2231     // edge cases is safety first.  It is always safe to clear immediately
2232     // within an Allocate, and then (maybe or maybe not) clear some more later.
2233     if (!(UseTLAB && ZeroTLAB)) {
2234       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
2235                                             alloc->in(AllocateNode::InitValue),
2236                                             alloc->in(AllocateNode::RawInitValue),
2237                                             header_size, size_in_bytes,
2238                                             true,
2239                                             &_igvn);
2240     }
2241   } else {
2242     if (!init->is_complete()) {
2243       // Try to win by zeroing only what the init does not store.
2244       // We can also try to do some peephole optimizations,
2245       // such as combining some adjacent subword stores.
2246       rawmem = init->complete_stores(control, rawmem, object,
2247                                      header_size, size_in_bytes, &_igvn);
2248     }
2249     // We have no more use for this link, since the AllocateNode goes away:
2250     init->set_req(InitializeNode::RawAddress, top());
2251     // (If we keep the link, it just confuses the register allocator,
2252     // who thinks he sees a real use of the address by the membar.)
2253   }
2254 
2255   return rawmem;
2256 }

2391       for (intx i = 0; i < lines; i++) {
2392         prefetch_adr = AddPNode::make_off_heap(new_eden_top,
2393                                                _igvn.MakeConX(distance));
2394         transform_later(prefetch_adr);
2395         prefetch = new PrefetchAllocationNode(i_o, prefetch_adr);
2396         // Do not let it float too high, since if eden_top == eden_end,
2397         // both might be null.
2398         if (i == 0) { // Set control for first prefetch, next follows it
2399           prefetch->init_req(0, needgc_false);
2400         }
2401         transform_later(prefetch);
2402         distance += step_size;
2403         i_o = prefetch;
2404       }
2405    }
2406    return i_o;
2407 }
2408 
2409 
2410 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
2411   expand_allocate_common(alloc, nullptr, nullptr,
2412                          OptoRuntime::new_instance_Type(),
2413                          OptoRuntime::new_instance_Java(), nullptr);
2414 }
2415 
2416 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
2417   Node* length = alloc->in(AllocateNode::ALength);
2418   Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest);
2419   InitializeNode* init = alloc->initialization();
2420   Node* klass_node = alloc->in(AllocateNode::KlassNode);
2421   Node* init_value = alloc->in(AllocateNode::InitValue);
2422   const TypeAryKlassPtr* ary_klass_t = _igvn.type(klass_node)->isa_aryklassptr();
2423   assert(!ary_klass_t || !ary_klass_t->klass_is_exact() || !ary_klass_t->exact_klass()->is_obj_array_klass() ||
2424          ary_klass_t->is_refined_type(), "Must be a refined array klass");
2425   const TypeFunc* slow_call_type;
2426   address slow_call_address;  // Address of slow call
2427   if (init != nullptr && init->is_complete_with_arraycopy() &&
2428       ary_klass_t && ary_klass_t->elem()->isa_klassptr() == nullptr) {
2429     // Don't zero type array during slow allocation in VM since
2430     // it will be initialized later by arraycopy in compiled code.
2431     slow_call_address = OptoRuntime::new_array_nozero_Java();
2432     slow_call_type = OptoRuntime::new_array_nozero_Type();
2433   } else {
2434     slow_call_address = OptoRuntime::new_array_Java();
2435     slow_call_type = OptoRuntime::new_array_Type();
2436 
2437     if (init_value == nullptr) {
2438       init_value = _igvn.zerocon(T_OBJECT);
2439     } else if (UseCompressedOops) {
2440       init_value = transform_later(new DecodeNNode(init_value, init_value->bottom_type()->make_ptr()));
2441     }
2442   }
2443   expand_allocate_common(alloc, length, init_value,
2444                          slow_call_type,
2445                          slow_call_address, valid_length_test);
2446 }
2447 
2448 //-------------------mark_eliminated_box----------------------------------
2449 //
2450 // During EA obj may point to several objects but after few ideal graph
2451 // transformations (CCP) it may point to only one non escaping object
2452 // (but still using phi), corresponding locks and unlocks will be marked
2453 // for elimination. Later obj could be replaced with a new node (new phi)
2454 // and which does not have escape information. And later after some graph
2455 // reshape other locks and unlocks (which were not marked for elimination
2456 // before) are connected to this new obj (phi) but they still will not be
2457 // marked for elimination since new obj has no escape information.
2458 // Mark all associated (same box and obj) lock and unlock nodes for
2459 // elimination if some of them marked already.
2460 void PhaseMacroExpand::mark_eliminated_box(Node* box, Node* obj) {
2461   BoxLockNode* oldbox = box->as_BoxLock();
2462   if (oldbox->is_eliminated()) {
2463     return; // This BoxLock node was processed already.
2464   }

2636 #ifdef ASSERT
2637   if (!alock->is_coarsened()) {
2638     // Check that new "eliminated" BoxLock node is created.
2639     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2640     assert(oldbox->is_eliminated(), "should be done already");
2641   }
2642 #endif
2643 
2644   alock->log_lock_optimization(C, "eliminate_lock");
2645 
2646 #ifndef PRODUCT
2647   if (PrintEliminateLocks) {
2648     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2649   }
2650 #endif
2651 
2652   Node* mem  = alock->in(TypeFunc::Memory);
2653   Node* ctrl = alock->in(TypeFunc::Control);
2654   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2655 
2656   _callprojs = alock->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2657   // There are 2 projections from the lock.  The lock node will
2658   // be deleted when its last use is subsumed below.
2659   assert(alock->outcnt() == 2 &&
2660          _callprojs->fallthrough_proj != nullptr &&
2661          _callprojs->fallthrough_memproj != nullptr,
2662          "Unexpected projections from Lock/Unlock");
2663 
2664   Node* fallthroughproj = _callprojs->fallthrough_proj;
2665   Node* memproj_fallthrough = _callprojs->fallthrough_memproj;
2666 
2667   // The memory projection from a lock/unlock is RawMem
2668   // The input to a Lock is merged memory, so extract its RawMem input
2669   // (unless the MergeMem has been optimized away.)
2670   if (alock->is_Lock()) {
2671     // Search for MemBarAcquireLock node and delete it also.
2672     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2673     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2674     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2675     Node* memproj = membar->proj_out(TypeFunc::Memory);
2676     _igvn.replace_node(ctrlproj, fallthroughproj);
2677     _igvn.replace_node(memproj, memproj_fallthrough);
2678 
2679     // Delete FastLock node also if this Lock node is unique user
2680     // (a loop peeling may clone a Lock node).
2681     Node* flock = alock->as_Lock()->fastlock_node();
2682     if (flock->outcnt() == 1) {
2683       assert(flock->unique_out() == alock, "sanity");
2684       _igvn.replace_node(flock, top());
2685     }

2716   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2717 
2718   // Make the merge point
2719   Node *region;
2720   Node *mem_phi;
2721   Node *slow_path;
2722 
2723   region  = new RegionNode(3);
2724   // create a Phi for the memory state
2725   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2726 
2727   // Optimize test; set region slot 2
2728   slow_path = opt_bits_test(ctrl, region, 2, flock);
2729   mem_phi->init_req(2, mem);
2730 
2731   // Make slow path call
2732   CallNode* call = make_slow_call(lock, OptoRuntime::complete_monitor_enter_Type(),
2733                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2734                                   obj, box, nullptr);
2735 
2736   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2737 
2738   // Slow path can only throw asynchronous exceptions, which are always
2739   // de-opted.  So the compiler thinks the slow-call can never throw an
2740   // exception.  If it DOES throw an exception we would need the debug
2741   // info removed first (since if it throws there is no monitor).
2742   assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr &&
2743          _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock");
2744 
2745   // Capture slow path
2746   // disconnect fall-through projection from call and create a new one
2747   // hook up users of fall-through projection to region
2748   Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2749   transform_later(slow_ctrl);
2750   _igvn.hash_delete(_callprojs->fallthrough_proj);
2751   _callprojs->fallthrough_proj->disconnect_inputs(C);
2752   region->init_req(1, slow_ctrl);
2753   // region inputs are now complete
2754   transform_later(region);
2755   _igvn.replace_node(_callprojs->fallthrough_proj, region);
2756 
2757   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2758 
2759   mem_phi->init_req(1, memproj);
2760 
2761   transform_later(mem_phi);
2762 
2763   _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2764 }
2765 
2766 //------------------------------expand_unlock_node----------------------
2767 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2768 
2769   Node* ctrl = unlock->in(TypeFunc::Control);
2770   Node* mem = unlock->in(TypeFunc::Memory);
2771   Node* obj = unlock->obj_node();
2772   Node* box = unlock->box_node();
2773 
2774   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2775 
2776   // No need for a null check on unlock
2777 
2778   // Make the merge point
2779   Node* region = new RegionNode(3);
2780 
2781   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2782   funlock = transform_later( funlock )->as_FastUnlock();
2783   // Optimize test; set region slot 2
2784   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock);
2785   Node *thread = transform_later(new ThreadLocalNode());
2786 
2787   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2788                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2789                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2790 
2791   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2792   assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr &&
2793          _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock");
2794 
2795   // No exceptions for unlocking
2796   // Capture slow path
2797   // disconnect fall-through projection from call and create a new one
2798   // hook up users of fall-through projection to region
2799   Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2800   transform_later(slow_ctrl);
2801   _igvn.hash_delete(_callprojs->fallthrough_proj);
2802   _callprojs->fallthrough_proj->disconnect_inputs(C);
2803   region->init_req(1, slow_ctrl);
2804   // region inputs are now complete
2805   transform_later(region);
2806   _igvn.replace_node(_callprojs->fallthrough_proj, region);
2807 
2808   if (_callprojs->fallthrough_memproj != nullptr) {
2809     // create a Phi for the memory state
2810     Node* mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2811     Node* memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2812     mem_phi->init_req(1, memproj);
2813     mem_phi->init_req(2, mem);
2814     transform_later(mem_phi);
2815     _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2816   }
2817 }
2818 
2819 // An inline type might be returned from the call but we don't know its
2820 // type. Either we get a buffered inline type (and nothing needs to be done)
2821 // or one of the values being returned is the klass of the inline type
2822 // and we need to allocate an inline type instance of that type and
2823 // initialize it with other values being returned. In that case, we
2824 // first try a fast path allocation and initialize the value with the
2825 // inline klass's pack handler or we fall back to a runtime call.
2826 void PhaseMacroExpand::expand_mh_intrinsic_return(CallStaticJavaNode* call) {
2827   assert(call->method()->is_method_handle_intrinsic(), "must be a method handle intrinsic call");
2828   Node* ret = call->proj_out_or_null(TypeFunc::Parms);
2829   if (ret == nullptr) {
2830     return;
2831   }
2832   const TypeFunc* tf = call->_tf;
2833   const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc();
2834   const TypeFunc* new_tf = TypeFunc::make(tf->domain_sig(), tf->domain_cc(), tf->range_sig(), domain, true);
2835   call->_tf = new_tf;
2836   // Make sure the change of type is applied before projections are processed by igvn
2837   _igvn.set_type(call, call->Value(&_igvn));
2838   _igvn.set_type(ret, ret->Value(&_igvn));
2839 
2840   // Before any new projection is added:
2841   CallProjections* projs = call->extract_projections(true, true);
2842 
2843   // Create temporary hook nodes that will be replaced below.
2844   // Add an input to prevent hook nodes from being dead.
2845   Node* ctl = new Node(call);
2846   Node* mem = new Node(ctl);
2847   Node* io = new Node(ctl);
2848   Node* ex_ctl = new Node(ctl);
2849   Node* ex_mem = new Node(ctl);
2850   Node* ex_io = new Node(ctl);
2851   Node* res = new Node(ctl);
2852 
2853   // Allocate a new buffered inline type only if a new one is not returned
2854   Node* cast = transform_later(new CastP2XNode(ctl, res));
2855   Node* mask = MakeConX(0x1);
2856   Node* masked = transform_later(new AndXNode(cast, mask));
2857   Node* cmp = transform_later(new CmpXNode(masked, mask));
2858   Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
2859   IfNode* allocation_iff = new IfNode(ctl, bol, PROB_MAX, COUNT_UNKNOWN);
2860   transform_later(allocation_iff);
2861   Node* allocation_ctl = transform_later(new IfTrueNode(allocation_iff));
2862   Node* no_allocation_ctl = transform_later(new IfFalseNode(allocation_iff));
2863   Node* no_allocation_res = transform_later(new CheckCastPPNode(no_allocation_ctl, res, TypeInstPtr::BOTTOM));
2864 
2865   // Try to allocate a new buffered inline instance either from TLAB or eden space
2866   Node* needgc_ctrl = nullptr; // needgc means slowcase, i.e. allocation failed
2867   CallLeafNoFPNode* handler_call;
2868   const bool alloc_in_place = UseTLAB;
2869   if (alloc_in_place) {
2870     Node* fast_oop_ctrl = nullptr;
2871     Node* fast_oop_rawmem = nullptr;
2872     Node* mask2 = MakeConX(-2);
2873     Node* masked2 = transform_later(new AndXNode(cast, mask2));
2874     Node* rawklassptr = transform_later(new CastX2PNode(masked2));
2875     Node* klass_node = transform_later(new CheckCastPPNode(allocation_ctl, rawklassptr, TypeInstKlassPtr::OBJECT_OR_NULL));
2876     Node* layout_val = make_load_raw(nullptr, mem, klass_node, in_bytes(Klass::layout_helper_offset()), TypeInt::INT, T_INT);
2877     Node* size_in_bytes = ConvI2X(layout_val);
2878     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2879     Node* fast_oop = bs->obj_allocate(this, mem, allocation_ctl, size_in_bytes, io, needgc_ctrl,
2880                                       fast_oop_ctrl, fast_oop_rawmem,
2881                                       AllocateInstancePrefetchLines);
2882     // Allocation succeed, initialize buffered inline instance header firstly,
2883     // and then initialize its fields with an inline class specific handler
2884     Node* mark_word_node;
2885     if (UseCompactObjectHeaders) {
2886       // COH: We need to load the prototype from the klass at runtime since it encodes the klass pointer already.
2887       mark_word_node = make_load_raw(fast_oop_ctrl, fast_oop_rawmem, klass_node, in_bytes(Klass::prototype_header_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2888     } else {
2889       // Otherwise, use the static prototype.
2890       mark_word_node = makecon(TypeRawPtr::make((address)markWord::inline_type_prototype().value()));
2891     }
2892 
2893     fast_oop_rawmem = make_store_raw(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::mark_offset_in_bytes(), mark_word_node, T_ADDRESS);
2894     if (!UseCompactObjectHeaders) {
2895       // COH: Everything is encoded in the mark word, so nothing left to do.
2896       fast_oop_rawmem = make_store_raw(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2897       fast_oop_rawmem = make_store_raw(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_gap_offset_in_bytes(), intcon(0), T_INT);
2898     }
2899     Node* members  = make_load_raw(fast_oop_ctrl, fast_oop_rawmem, klass_node, in_bytes(InlineKlass::adr_members_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2900     Node* pack_handler = make_load_raw(fast_oop_ctrl, fast_oop_rawmem, members, in_bytes(InlineKlass::pack_handler_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2901     handler_call = new CallLeafNoFPNode(OptoRuntime::pack_inline_type_Type(),
2902                                         nullptr,
2903                                         "pack handler",
2904                                         TypeRawPtr::BOTTOM);
2905     handler_call->init_req(TypeFunc::Control, fast_oop_ctrl);
2906     handler_call->init_req(TypeFunc::Memory, fast_oop_rawmem);
2907     handler_call->init_req(TypeFunc::I_O, top());
2908     handler_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2909     handler_call->init_req(TypeFunc::ReturnAdr, top());
2910     handler_call->init_req(TypeFunc::Parms, pack_handler);
2911     handler_call->init_req(TypeFunc::Parms+1, fast_oop);
2912   } else {
2913     needgc_ctrl = allocation_ctl;
2914   }
2915 
2916   // Allocation failed, fall back to a runtime call
2917   CallStaticJavaNode* slow_call = new CallStaticJavaNode(OptoRuntime::store_inline_type_fields_Type(),
2918                                                          SharedRuntime::store_inline_type_fields_to_buf_entry(),
2919                                                          "store_inline_type_fields",
2920                                                          TypePtr::BOTTOM);
2921   slow_call->init_req(TypeFunc::Control, needgc_ctrl);
2922   slow_call->init_req(TypeFunc::Memory, mem);
2923   slow_call->init_req(TypeFunc::I_O, io);
2924   slow_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2925   slow_call->init_req(TypeFunc::ReturnAdr, call->in(TypeFunc::ReturnAdr));
2926   slow_call->init_req(TypeFunc::Parms, res);
2927 
2928   Node* slow_ctl = transform_later(new ProjNode(slow_call, TypeFunc::Control));
2929   Node* slow_mem = transform_later(new ProjNode(slow_call, TypeFunc::Memory));
2930   Node* slow_io = transform_later(new ProjNode(slow_call, TypeFunc::I_O));
2931   Node* slow_res = transform_later(new ProjNode(slow_call, TypeFunc::Parms));
2932   Node* slow_catc = transform_later(new CatchNode(slow_ctl, slow_io, 2));
2933   Node* slow_norm = transform_later(new CatchProjNode(slow_catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci));
2934   Node* slow_excp = transform_later(new CatchProjNode(slow_catc, CatchProjNode::catch_all_index,    CatchProjNode::no_handler_bci));
2935 
2936   Node* ex_r = new RegionNode(3);
2937   Node* ex_mem_phi = new PhiNode(ex_r, Type::MEMORY, TypePtr::BOTTOM);
2938   Node* ex_io_phi = new PhiNode(ex_r, Type::ABIO);
2939   ex_r->init_req(1, slow_excp);
2940   ex_mem_phi->init_req(1, slow_mem);
2941   ex_io_phi->init_req(1, slow_io);
2942   ex_r->init_req(2, ex_ctl);
2943   ex_mem_phi->init_req(2, ex_mem);
2944   ex_io_phi->init_req(2, ex_io);
2945   transform_later(ex_r);
2946   transform_later(ex_mem_phi);
2947   transform_later(ex_io_phi);
2948 
2949   // We don't know how many values are returned. This assumes the
2950   // worst case, that all available registers are used.
2951   for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2952     if (domain->field_at(i) == Type::HALF) {
2953       slow_call->init_req(i, top());
2954       if (alloc_in_place) {
2955         handler_call->init_req(i+1, top());
2956       }
2957       continue;
2958     }
2959     Node* proj = transform_later(new ProjNode(call, i));
2960     slow_call->init_req(i, proj);
2961     if (alloc_in_place) {
2962       handler_call->init_req(i+1, proj);
2963     }
2964   }
2965   // We can safepoint at that new call
2966   slow_call->copy_call_debug_info(&_igvn, call);
2967   transform_later(slow_call);
2968   if (alloc_in_place) {
2969     transform_later(handler_call);
2970   }
2971 
2972   Node* fast_ctl = nullptr;
2973   Node* fast_res = nullptr;
2974   MergeMemNode* fast_mem = nullptr;
2975   if (alloc_in_place) {
2976     fast_ctl = transform_later(new ProjNode(handler_call, TypeFunc::Control));
2977     Node* rawmem = transform_later(new ProjNode(handler_call, TypeFunc::Memory));
2978     fast_res = transform_later(new ProjNode(handler_call, TypeFunc::Parms));
2979     fast_mem = MergeMemNode::make(mem);
2980     fast_mem->set_memory_at(Compile::AliasIdxRaw, rawmem);
2981     transform_later(fast_mem);
2982   }
2983 
2984   Node* r = new RegionNode(alloc_in_place ? 4 : 3);
2985   Node* mem_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM);
2986   Node* io_phi = new PhiNode(r, Type::ABIO);
2987   Node* res_phi = new PhiNode(r, TypeInstPtr::BOTTOM);
2988   r->init_req(1, no_allocation_ctl);
2989   mem_phi->init_req(1, mem);
2990   io_phi->init_req(1, io);
2991   res_phi->init_req(1, no_allocation_res);
2992   r->init_req(2, slow_norm);
2993   mem_phi->init_req(2, slow_mem);
2994   io_phi->init_req(2, slow_io);
2995   res_phi->init_req(2, slow_res);
2996   if (alloc_in_place) {
2997     r->init_req(3, fast_ctl);
2998     mem_phi->init_req(3, fast_mem);
2999     io_phi->init_req(3, io);
3000     res_phi->init_req(3, fast_res);
3001   }
3002   transform_later(r);
3003   transform_later(mem_phi);
3004   transform_later(io_phi);
3005   transform_later(res_phi);
3006 
3007   // Do not let stores that initialize this buffer be reordered with a subsequent
3008   // store that would make this buffer accessible by other threads.
3009   MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
3010   transform_later(mb);
3011   mb->init_req(TypeFunc::Memory, mem_phi);
3012   mb->init_req(TypeFunc::Control, r);
3013   r = new ProjNode(mb, TypeFunc::Control);
3014   transform_later(r);
3015   mem_phi = new ProjNode(mb, TypeFunc::Memory);
3016   transform_later(mem_phi);
3017 
3018   assert(projs->nb_resproj == 1, "unexpected number of results");
3019   _igvn.replace_in_uses(projs->fallthrough_catchproj, r);
3020   _igvn.replace_in_uses(projs->fallthrough_memproj, mem_phi);
3021   _igvn.replace_in_uses(projs->fallthrough_ioproj, io_phi);
3022   _igvn.replace_in_uses(projs->resproj[0], res_phi);
3023   _igvn.replace_in_uses(projs->catchall_catchproj, ex_r);
3024   _igvn.replace_in_uses(projs->catchall_memproj, ex_mem_phi);
3025   _igvn.replace_in_uses(projs->catchall_ioproj, ex_io_phi);
3026   // The CatchNode should not use the ex_io_phi. Re-connect it to the catchall_ioproj.
3027   Node* cn = projs->fallthrough_catchproj->in(0);
3028   _igvn.replace_input_of(cn, 1, projs->catchall_ioproj);
3029 
3030   _igvn.replace_node(ctl, projs->fallthrough_catchproj);
3031   _igvn.replace_node(mem, projs->fallthrough_memproj);
3032   _igvn.replace_node(io, projs->fallthrough_ioproj);
3033   _igvn.replace_node(res, projs->resproj[0]);
3034   _igvn.replace_node(ex_ctl, projs->catchall_catchproj);
3035   _igvn.replace_node(ex_mem, projs->catchall_memproj);
3036   _igvn.replace_node(ex_io, projs->catchall_ioproj);
3037  }
3038 
3039 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
3040   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
3041   Node* bol = check->unique_out();
3042   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
3043   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
3044   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
3045 
3046   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
3047     Node* iff = bol->last_out(i);
3048     assert(iff->is_If(), "where's the if?");
3049 
3050     if (iff->in(0)->is_top()) {
3051       _igvn.replace_input_of(iff, 1, C->top());
3052       continue;
3053     }
3054 
3055     IfTrueNode* iftrue = iff->as_If()->true_proj();
3056     IfFalseNode* iffalse = iff->as_If()->false_proj();
3057     Node* ctrl = iff->in(0);
3058 
3059     Node* subklass = nullptr;
3060     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
3061       subklass = obj_or_subklass;
3062     } else {
3063       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
3064       subklass = _igvn.transform(LoadKlassNode::make(_igvn, C->immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
3065     }
3066 
3067     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci());
3068 
3069     _igvn.replace_input_of(iff, 0, C->top());
3070     _igvn.replace_node(iftrue, not_subtype_ctrl);
3071     _igvn.replace_node(iffalse, ctrl);
3072   }
3073   _igvn.replace_node(check, C->top());
3074 }
3075 
3076 // FlatArrayCheckNode (array1 array2 ...) is expanded into:
3077 //
3078 // long mark = array1.mark | array2.mark | ...;
3079 // long locked_bit = markWord::unlocked_value & array1.mark & array2.mark & ...;
3080 // if (locked_bit == 0) {
3081 //   // One array is locked, load prototype header from the klass
3082 //   mark = array1.klass.proto | array2.klass.proto | ...
3083 // }
3084 // if ((mark & markWord::flat_array_bit_in_place) == 0) {
3085 //    ...
3086 // }
3087 void PhaseMacroExpand::expand_flatarraycheck_node(FlatArrayCheckNode* check) {
3088   bool array_inputs = _igvn.type(check->in(FlatArrayCheckNode::ArrayOrKlass))->isa_oopptr() != nullptr;
3089   if (array_inputs) {
3090     Node* mark = MakeConX(0);
3091     Node* locked_bit = MakeConX(markWord::unlocked_value);
3092     Node* mem = check->in(FlatArrayCheckNode::Memory);
3093     for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
3094       Node* ary = check->in(i);
3095       const TypeOopPtr* t = _igvn.type(ary)->isa_oopptr();
3096       assert(t != nullptr, "Mixing array and klass inputs");
3097       assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
3098       Node* mark_adr = basic_plus_adr(ary, oopDesc::mark_offset_in_bytes());
3099       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));
3100       mark = _igvn.transform(new OrXNode(mark, mark_load));
3101       locked_bit = _igvn.transform(new AndXNode(locked_bit, mark_load));
3102     }
3103     assert(!mark->is_Con(), "Should have been optimized out");
3104     Node* cmp = _igvn.transform(new CmpXNode(locked_bit, MakeConX(0)));
3105     Node* is_unlocked = _igvn.transform(new BoolNode(cmp, BoolTest::ne));
3106 
3107     // BoolNode might be shared, replace each if user
3108     Node* old_bol = check->unique_out();
3109     assert(old_bol->is_Bool() && old_bol->as_Bool()->_test._test == BoolTest::ne, "unexpected condition");
3110     for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) {
3111       IfNode* old_iff = old_bol->last_out(i)->as_If();
3112       Node* ctrl = old_iff->in(0);
3113       RegionNode* region = new RegionNode(3);
3114       Node* mark_phi = new PhiNode(region, TypeX_X);
3115 
3116       // Check if array is unlocked
3117       IfNode* iff = _igvn.transform(new IfNode(ctrl, is_unlocked, PROB_MAX, COUNT_UNKNOWN))->as_If();
3118 
3119       // Unlocked: Use bits from mark word
3120       region->init_req(1, _igvn.transform(new IfTrueNode(iff)));
3121       mark_phi->init_req(1, mark);
3122 
3123       // Locked: Load prototype header from klass
3124       ctrl = _igvn.transform(new IfFalseNode(iff));
3125       Node* proto = MakeConX(0);
3126       for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
3127         Node* ary = check->in(i);
3128         // Make loads control dependent to make sure they are only executed if array is locked
3129         Node* klass_adr = basic_plus_adr(ary, oopDesc::klass_offset_in_bytes());
3130         Node* klass = _igvn.transform(LoadKlassNode::make(_igvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
3131         Node* proto_adr = basic_plus_adr(top(), klass, in_bytes(Klass::prototype_header_offset()));
3132         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));
3133         proto = _igvn.transform(new OrXNode(proto, proto_load));
3134       }
3135       region->init_req(2, ctrl);
3136       mark_phi->init_req(2, proto);
3137 
3138       // Check if flat array bits are set
3139       Node* mask = MakeConX(markWord::flat_array_bit_in_place);
3140       Node* masked = _igvn.transform(new AndXNode(_igvn.transform(mark_phi), mask));
3141       cmp = _igvn.transform(new CmpXNode(masked, MakeConX(0)));
3142       Node* is_not_flat = _igvn.transform(new BoolNode(cmp, BoolTest::eq));
3143 
3144       ctrl = _igvn.transform(region);
3145       iff = _igvn.transform(new IfNode(ctrl, is_not_flat, PROB_MAX, COUNT_UNKNOWN))->as_If();
3146       _igvn.replace_node(old_iff, iff);
3147     }
3148     _igvn.replace_node(check, C->top());
3149   } else {
3150     // Fall back to layout helper check
3151     Node* lhs = intcon(0);
3152     for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
3153       Node* array_or_klass = check->in(i);
3154       Node* klass = nullptr;
3155       const TypePtr* t = _igvn.type(array_or_klass)->is_ptr();
3156       assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
3157       if (t->isa_oopptr() != nullptr) {
3158         Node* klass_adr = basic_plus_adr(array_or_klass, oopDesc::klass_offset_in_bytes());
3159         klass = transform_later(LoadKlassNode::make(_igvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
3160       } else {
3161         assert(t->isa_klassptr(), "Unexpected input type");
3162         klass = array_or_klass;
3163       }
3164       Node* lh_addr = basic_plus_adr(top(), klass, in_bytes(Klass::layout_helper_offset()));
3165       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));
3166       lhs = _igvn.transform(new OrINode(lhs, lh_val));
3167     }
3168     Node* masked = transform_later(new AndINode(lhs, intcon(Klass::_lh_array_tag_flat_value_bit_inplace)));
3169     Node* cmp = transform_later(new CmpINode(masked, intcon(0)));
3170     Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
3171     Node* m2b = transform_later(new Conv2BNode(masked));
3172     // The matcher expects the input to If/CMove nodes to be produced by a Bool(CmpI..)
3173     // pattern, but the input to other potential users (e.g. Phi) to be some
3174     // other pattern (e.g. a Conv2B node, possibly idealized as a CMoveI).
3175     Node* old_bol = check->unique_out();
3176     for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) {
3177       Node* user = old_bol->last_out(i);
3178       for (uint j = 0; j < user->req(); j++) {
3179         Node* n = user->in(j);
3180         if (n == old_bol) {
3181           _igvn.replace_input_of(user, j, (user->is_If() || user->is_CMove()) ? bol : m2b);
3182         }
3183       }
3184     }
3185     _igvn.replace_node(check, C->top());
3186   }
3187 }
3188 
3189 // Perform refining of strip mined loop nodes in the macro nodes list.
3190 void PhaseMacroExpand::refine_strip_mined_loop_macro_nodes() {
3191    for (int i = C->macro_count(); i > 0; i--) {
3192     Node* n = C->macro_node(i - 1);
3193     if (n->is_OuterStripMinedLoop()) {
3194       n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
3195     }
3196   }
3197 }
3198 
3199 //---------------------------eliminate_macro_nodes----------------------
3200 // Eliminate scalar replaced allocations and associated locks.
3201 void PhaseMacroExpand::eliminate_macro_nodes(bool eliminate_locks) {
3202   if (C->macro_count() == 0) {
3203     return;
3204   }
3205 
3206   if (StressMacroElimination) {
3207     C->shuffle_macro_nodes();
3208   }
3209   NOT_PRODUCT(int membar_before = count_MemBar(C);)
3210 
3211   int iteration = 0;
3212   while (C->macro_count() > 0) {
3213     if (iteration++ > 100) {
3214       assert(false, "Too slow convergence of macro elimination");
3215       break;


3216     }










3217 
3218     // Postpone lock elimination to after EA when most allocations are eliminated
3219     // because they might block lock elimination if their escape state isn't
3220     // determined yet and we only got one chance at eliminating the lock.
3221     if (eliminate_locks) {
3222       // Before elimination may re-mark (change to Nested or NonEscObj)
3223       // all associated (same box and obj) lock and unlock nodes.
3224       int cnt = C->macro_count();
3225       for (int i=0; i < cnt; i++) {
3226         Node *n = C->macro_node(i);
3227         if (n->is_AbstractLock()) { // Lock and Unlock nodes
3228           mark_eliminated_locking_nodes(n->as_AbstractLock());


3229         }

3230       }
3231       // Re-marking may break consistency of Coarsened locks.
3232       if (!C->coarsened_locks_consistent()) {
3233         return; // recompile without Coarsened locks if broken
3234       } else {
3235         // After coarsened locks are eliminated locking regions
3236         // become unbalanced. We should not execute any more
3237         // locks elimination optimizations on them.
3238         C->mark_unbalanced_boxes();
3239       }
3240     }
3241 
3242     bool progress = false;



3243     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
3244       Node* n = C->macro_node(i - 1);
3245       bool success = false;
3246       DEBUG_ONLY(int old_macro_count = C->macro_count();)
3247       switch (n->class_id()) {
3248       case Node::Class_Allocate:
3249       case Node::Class_AllocateArray:
3250         success = eliminate_allocate_node(n->as_Allocate());
3251 #ifndef PRODUCT
3252         if (success && PrintOptoStatistics) {
3253           AtomicAccess::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
3254         }
3255 #endif
3256         break;
3257       case Node::Class_CallStaticJava: {
3258         CallStaticJavaNode* call = n->as_CallStaticJava();
3259         if (!call->method()->is_method_handle_intrinsic()) {
3260           success = eliminate_boxing_node(n->as_CallStaticJava());
3261         }
3262         break;
3263       }
3264       case Node::Class_Lock:
3265       case Node::Class_Unlock:
3266         if (eliminate_locks) {
3267           success = eliminate_locking_node(n->as_AbstractLock());
3268 #ifndef PRODUCT
3269           if (success && PrintOptoStatistics) {
3270             AtomicAccess::inc(&PhaseMacroExpand::_monitor_objects_removed_counter);
3271           }
3272 #endif
3273         }
3274         break;
3275       case Node::Class_ArrayCopy:
3276         break;
3277       case Node::Class_OuterStripMinedLoop:
3278         break;
3279       case Node::Class_SubTypeCheck:
3280         break;
3281       case Node::Class_Opaque1:
3282         break;
3283       case Node::Class_FlatArrayCheck:
3284         break;
3285       default:
3286         assert(n->Opcode() == Op_LoopLimit ||
3287                n->Opcode() == Op_ModD ||
3288                n->Opcode() == Op_ModF ||
3289                n->Opcode() == Op_PowD ||
3290                n->is_OpaqueConstantBool()    ||
3291                n->is_OpaqueInitializedAssertionPredicate() ||
3292                n->Opcode() == Op_MaxL      ||
3293                n->Opcode() == Op_MinL      ||
3294                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
3295                "unknown node type in macro list");
3296       }
3297       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
3298       progress = progress || success;
3299       if (success) {
3300         C->print_method(PHASE_AFTER_MACRO_ELIMINATION_STEP, 5, n);
3301       }
3302     }
3303 
3304     // Ensure the graph after PhaseMacroExpand::eliminate_macro_nodes is canonical (no igvn
3305     // transformation is pending). If an allocation is used only in safepoints, elimination of
3306     // other macro nodes can remove all these safepoints, allowing the allocation to be removed.
3307     // Hence after igvn we retry removing macro nodes if some progress that has been made in this
3308     // iteration.
3309     _igvn.set_delay_transform(false);
3310     _igvn.optimize();
3311     if (C->failing()) {
3312       return;
3313     }
3314     _igvn.set_delay_transform(true);
3315 
3316     if (!progress) {
3317       break;
3318     }
3319   }
3320 #ifndef PRODUCT
3321   if (PrintOptoStatistics) {
3322     int membar_after = count_MemBar(C);
3323     AtomicAccess::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
3324   }
3325 #endif
3326 }
3327 
3328 void PhaseMacroExpand::eliminate_opaque_looplimit_macro_nodes() {
3329   if (C->macro_count() == 0) {
3330     return;
3331   }
3332   refine_strip_mined_loop_macro_nodes();
3333   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
3334   bool progress = true;
3335   while (progress) {
3336     progress = false;
3337     for (int i = C->macro_count(); i > 0; i--) {
3338       Node* n = C->macro_node(i-1);
3339       bool success = false;
3340       DEBUG_ONLY(int old_macro_count = C->macro_count();)
3341       if (n->Opcode() == Op_LoopLimit) {
3342         // Remove it from macro list and put on IGVN worklist to optimize.
3343         C->remove_macro_node(n);
3344         _igvn._worklist.push(n);
3345         success = true;
3346       } else if (n->Opcode() == Op_CallStaticJava) {
3347         CallStaticJavaNode* call = n->as_CallStaticJava();
3348         if (!call->method()->is_method_handle_intrinsic()) {
3349           // Remove it from macro list and put on IGVN worklist to optimize.
3350           C->remove_macro_node(n);
3351           _igvn._worklist.push(n);
3352           success = true;
3353         }
3354       } else if (n->is_Opaque1()) {
3355         _igvn.replace_node(n, n->in(1));
3356         success = true;
3357       } else if (n->is_OpaqueConstantBool()) {
3358         // Tests with OpaqueConstantBool nodes are implicitly known. Replace the node with true/false. In debug builds,
3359         // we leave the test in the graph to have an additional sanity check at runtime. If the test fails (i.e. a bug),
3360         // we will execute a Halt node.
3361 #ifdef ASSERT
3362         _igvn.replace_node(n, n->in(1));
3363 #else
3364         _igvn.replace_node(n, _igvn.intcon(n->as_OpaqueConstantBool()->constant()));
3365 #endif
3366         success = true;
3367       } else if (n->is_OpaqueInitializedAssertionPredicate()) {
3368           // Initialized Assertion Predicates must always evaluate to true. Therefore, we get rid of them in product
3369           // builds as they are useless. In debug builds we keep them as additional verification code. Even though
3370           // loop opts are already over, we want to keep Initialized Assertion Predicates alive as long as possible to
3371           // enable folding of dead control paths within which cast nodes become top after due to impossible types -
3372           // even after loop opts are over. Therefore, we delay the removal of these opaque nodes until now.
3373 #ifdef ASSERT

3442     // Worst case is a macro node gets expanded into about 200 nodes.
3443     // Allow 50% more for optimization.
3444     if (C->check_node_count(300, "out of nodes before macro expansion")) {
3445       return true;
3446     }
3447 
3448     DEBUG_ONLY(int old_macro_count = C->macro_count();)
3449     switch (n->class_id()) {
3450     case Node::Class_Lock:
3451       expand_lock_node(n->as_Lock());
3452       break;
3453     case Node::Class_Unlock:
3454       expand_unlock_node(n->as_Unlock());
3455       break;
3456     case Node::Class_ArrayCopy:
3457       expand_arraycopy_node(n->as_ArrayCopy());
3458       break;
3459     case Node::Class_SubTypeCheck:
3460       expand_subtypecheck_node(n->as_SubTypeCheck());
3461       break;
3462     case Node::Class_CallStaticJava:
3463       expand_mh_intrinsic_return(n->as_CallStaticJava());
3464       C->remove_macro_node(n);
3465       break;
3466     case Node::Class_FlatArrayCheck:
3467       expand_flatarraycheck_node(n->as_FlatArrayCheck());
3468       break;
3469     default:
3470       switch (n->Opcode()) {
3471       case Op_ModD:
3472       case Op_ModF:
3473       case Op_PowD: {
3474         CallLeafPureNode* call_macro = n->as_CallLeafPure();
3475         CallLeafPureNode* call = call_macro->inline_call_leaf_pure_node();
3476         _igvn.replace_node(call_macro, call);
3477         transform_later(call);
3478         break;
3479       }
3480       default:
3481         assert(false, "unknown node type in macro list");
3482       }
3483     }
3484     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3485     if (C->failing())  return true;
3486     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
3487 
3488     // Clean up the graph so we're less likely to hit the maximum node
< prev index next >