< prev index next >

src/hotspot/share/opto/macro.cpp

Print this page

   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"

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

  39 #include "opto/intrinsicnode.hpp"
  40 #include "opto/locknode.hpp"
  41 #include "opto/loopnode.hpp"
  42 #include "opto/macro.hpp"
  43 #include "opto/memnode.hpp"
  44 #include "opto/narrowptrnode.hpp"
  45 #include "opto/node.hpp"
  46 #include "opto/opaquenode.hpp"
  47 #include "opto/phaseX.hpp"
  48 #include "opto/rootnode.hpp"
  49 #include "opto/runtime.hpp"
  50 #include "opto/subnode.hpp"
  51 #include "opto/subtypenode.hpp"
  52 #include "opto/type.hpp"
  53 #include "prims/jvmtiExport.hpp"
  54 #include "runtime/continuation.hpp"
  55 #include "runtime/sharedRuntime.hpp"

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

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

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

 239       }
 240       // Otherwise skip it (the call updated 'mem' value).
 241     } else if (mem->Opcode() == Op_SCMemProj) {
 242       mem = mem->in(0);
 243       Node* adr = nullptr;
 244       if (mem->is_LoadStore()) {
 245         adr = mem->in(MemNode::Address);
 246       } else {
 247         assert(mem->Opcode() == Op_EncodeISOArray ||
 248                mem->Opcode() == Op_StrCompressedCopy, "sanity");
 249         adr = mem->in(3); // Destination array
 250       }
 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 LoadStore node accesses its field");
 256         return nullptr;
 257       }
 258       mem = mem->in(MemNode::Memory);
 259    } else if (mem->Opcode() == Op_StrInflatedCopy) {
 260       Node* adr = mem->in(3); // Destination array
 261       const TypePtr* atype = adr->bottom_type()->is_ptr();
 262       int adr_idx = phase->C->get_alias_index(atype);
 263       if (adr_idx == alias_idx) {
 264         DEBUG_ONLY(mem->dump();)
 265         assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
 266         return nullptr;
 267       }
 268       mem = mem->in(MemNode::Memory);
 269     } else {
 270       return mem;
 271     }
 272     assert(mem != orig_mem, "dead memory loop");
 273   }
 274 }
 275 
 276 // Generate loads from source of the arraycopy for fields of
 277 // destination needed at a deoptimization point
 278 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
 279   BasicType bt = ft;

 284   }
 285   Node* res = nullptr;
 286   if (ac->is_clonebasic()) {
 287     assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
 288     Node* base = ac->in(ArrayCopyNode::Src);
 289     Node* adr = _igvn.transform(new AddPNode(base, base, _igvn.MakeConX(offset)));
 290     const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
 291     MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 292     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 293     res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 294   } else {
 295     if (ac->modifies(offset, offset, &_igvn, true)) {
 296       assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
 297       uint shift = exact_log2(type2aelembytes(bt));
 298       Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
 299       Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
 300       const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
 301       const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
 302 
 303       Node* adr = nullptr;
 304       const TypePtr* adr_type = nullptr;




 305       if (src_pos_t->is_con() && dest_pos_t->is_con()) {
 306         intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
 307         Node* base = ac->in(ArrayCopyNode::Src);
 308         adr = _igvn.transform(new AddPNode(base, base, _igvn.MakeConX(off)));
 309         adr_type = _igvn.type(base)->is_ptr()->add_offset(off);

 310         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 311           // Don't emit a new load from src if src == dst but try to get the value from memory instead
 312           return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type->isa_oopptr(), alloc);
 313         }
 314       } else {





 315         Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 316 #ifdef _LP64
 317         diff = _igvn.transform(new ConvI2LNode(diff));
 318 #endif
 319         diff = _igvn.transform(new LShiftXNode(diff, _igvn.intcon(shift)));
 320 
 321         Node* off = _igvn.transform(new AddXNode(_igvn.MakeConX(offset), diff));
 322         Node* base = ac->in(ArrayCopyNode::Src);
 323         adr = _igvn.transform(new AddPNode(base, base, off));
 324         adr_type = _igvn.type(base)->is_ptr()->add_offset(Type::OffsetBot);
 325         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 326           // Non constant offset in the array: we can't statically
 327           // determine the value
 328           return nullptr;
 329         }
 330       }
 331       MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 332       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 333       res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 334     }
 335   }
 336   if (res != nullptr) {
 337     if (ftype->isa_narrowoop()) {
 338       // PhaseMacroExpand::scalar_replacement adds DecodeN nodes

 339       res = _igvn.transform(new EncodePNode(res, ftype));
 340     }
 341     return res;
 342   }
 343   return nullptr;
 344 }
 345 
 346 //
 347 // Given a Memory Phi, compute a value Phi containing the values from stores
 348 // on the input paths.
 349 // Note: this function is recursive, its depth is limited by the "level" argument
 350 // Returns the computed Phi, or null if it cannot compute it.
 351 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) {
 352   assert(mem->is_Phi(), "sanity");
 353   int alias_idx = C->get_alias_index(adr_t);
 354   int offset = adr_t->offset();
 355   int instance_id = adr_t->instance_id();
 356 
 357   // Check if an appropriate value phi already exists.
 358   Node* region = mem->in(0);
 359   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
 360     Node* phi = region->fast_out(k);
 361     if (phi->is_Phi() && phi != mem &&
 362         phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
 363       return phi;
 364     }
 365   }
 366   // Check if an appropriate new value phi already exists.
 367   Node* new_phi = value_phis->find(mem->_idx);
 368   if (new_phi != nullptr)
 369     return new_phi;
 370 
 371   if (level <= 0) {
 372     return nullptr; // Give up: phi tree too deep
 373   }
 374   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 375   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 376   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 377 
 378   uint length = mem->req();
 379   GrowableArray <Node *> values(length, length, nullptr);
 380 
 381   // create a new Phi for the value
 382   PhiNode *phi = new PhiNode(mem->in(0), phi_type, nullptr, mem->_idx, instance_id, alias_idx, offset);
 383   transform_later(phi);
 384   value_phis->push(phi, mem->_idx);
 385 
 386   for (uint j = 1; j < length; j++) {
 387     Node *in = mem->in(j);
 388     if (in == nullptr || in->is_top()) {
 389       values.at_put(j, in);
 390     } else  {
 391       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
 392       if (val == start_mem || val == alloc_mem) {
 393         // hit a sentinel, return appropriate 0 value
 394         values.at_put(j, _igvn.zerocon(ft));






 395         continue;
 396       }
 397       if (val->is_Initialize()) {
 398         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 399       }
 400       if (val == nullptr) {
 401         return nullptr;  // can't find a value on this path
 402       }
 403       if (val == mem) {
 404         values.at_put(j, mem);
 405       } else if (val->is_Store()) {
 406         Node* n = val->in(MemNode::ValueIn);
 407         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 408         n = bs->step_over_gc_barrier(n);
 409         if (is_subword_type(ft)) {
 410           n = Compile::narrow_value(ft, n, phi_type, &_igvn, true);
 411         }
 412         values.at_put(j, n);
 413       } else if(val->is_Proj() && val->in(0) == alloc) {
 414         values.at_put(j, _igvn.zerocon(ft));






 415       } else if (val->is_Phi()) {
 416         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 417         if (val == nullptr) {
 418           return nullptr;
 419         }
 420         values.at_put(j, val);
 421       } else if (val->Opcode() == Op_SCMemProj) {
 422         assert(val->in(0)->is_LoadStore() ||
 423                val->in(0)->Opcode() == Op_EncodeISOArray ||
 424                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
 425         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 426         return nullptr;
 427       } else if (val->is_ArrayCopy()) {
 428         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
 429         if (res == nullptr) {
 430           return nullptr;
 431         }
 432         values.at_put(j, res);
 433       } else {
 434         DEBUG_ONLY( val->dump(); )

 438     }
 439   }
 440   // Set Phi's inputs
 441   for (uint j = 1; j < length; j++) {
 442     if (values.at(j) == mem) {
 443       phi->init_req(j, phi);
 444     } else {
 445       phi->init_req(j, values.at(j));
 446     }
 447   }
 448   return phi;
 449 }
 450 
 451 // Search the last value stored into the object's field.
 452 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
 453   assert(adr_t->is_known_instance_field(), "instance required");
 454   int instance_id = adr_t->instance_id();
 455   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 456 
 457   int alias_idx = C->get_alias_index(adr_t);
 458   int offset = adr_t->offset();
 459   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 460   Node *alloc_ctrl = alloc->in(TypeFunc::Control);
 461   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 462   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 463   VectorSet visited;
 464 
 465   bool done = sfpt_mem == alloc_mem;
 466   Node *mem = sfpt_mem;
 467   while (!done) {
 468     if (visited.test_set(mem->_idx)) {
 469       return nullptr;  // found a loop, give up
 470     }
 471     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 472     if (mem == start_mem || mem == alloc_mem) {
 473       done = true;  // hit a sentinel, return appropriate 0 value
 474     } else if (mem->is_Initialize()) {
 475       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 476       if (mem == nullptr) {
 477         done = true; // Something go wrong.
 478       } else if (mem->is_Store()) {
 479         const TypePtr* atype = mem->as_Store()->adr_type();
 480         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 481         done = true;
 482       }
 483     } else if (mem->is_Store()) {
 484       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 485       assert(atype != nullptr, "address type must be oopptr");
 486       assert(C->get_alias_index(atype) == alias_idx &&
 487              atype->is_known_instance_field() && atype->offset() == offset &&
 488              atype->instance_id() == instance_id, "store is correct memory slice");
 489       done = true;
 490     } else if (mem->is_Phi()) {
 491       // try to find a phi's unique input
 492       Node *unique_input = nullptr;
 493       Node *top = C->top();
 494       for (uint i = 1; i < mem->req(); i++) {
 495         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 496         if (n == nullptr || n == top || n == mem) {
 497           continue;
 498         } else if (unique_input == nullptr) {
 499           unique_input = n;
 500         } else if (unique_input != n) {
 501           unique_input = top;
 502           break;
 503         }
 504       }
 505       if (unique_input != nullptr && unique_input != top) {
 506         mem = unique_input;
 507       } else {
 508         done = true;
 509       }
 510     } else if (mem->is_ArrayCopy()) {
 511       done = true;
 512     } else {
 513       DEBUG_ONLY( mem->dump(); )
 514       assert(false, "unexpected node");
 515     }
 516   }
 517   if (mem != nullptr) {
 518     if (mem == start_mem || mem == alloc_mem) {
 519       // hit a sentinel, return appropriate 0 value





 520       return _igvn.zerocon(ft);
 521     } else if (mem->is_Store()) {
 522       Node* n = mem->in(MemNode::ValueIn);
 523       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 524       n = bs->step_over_gc_barrier(n);
 525       return n;
 526     } else if (mem->is_Phi()) {
 527       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 528       Node_Stack value_phis(8);
 529       Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 530       if (phi != nullptr) {
 531         return phi;
 532       } else {
 533         // Kill all new Phis
 534         while(value_phis.is_nonempty()) {
 535           Node* n = value_phis.node();
 536           _igvn.replace_node(n, C->top());
 537           value_phis.pop();
 538         }
 539       }
 540     } else if (mem->is_ArrayCopy()) {
 541       Node* ctl = mem->in(0);
 542       Node* m = mem->in(TypeFunc::Memory);
 543       if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj()) {
 544         // pin the loads in the uncommon trap path
 545         ctl = sfpt_ctl;
 546         m = sfpt_mem;
 547       }
 548       return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
 549     }
 550   }
 551   // Something go wrong.
 552   return nullptr;
 553 }
 554 










































 555 // Check the possibility of scalar replacement.
 556 bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode *alloc, GrowableArray <SafePointNode *>* safepoints) {
 557   //  Scan the uses of the allocation to check for anything that would
 558   //  prevent us from eliminating it.
 559   NOT_PRODUCT( const char* fail_eliminate = nullptr; )
 560   DEBUG_ONLY( Node* disq_node = nullptr; )
 561   bool can_eliminate = true;
 562   bool reduce_merge_precheck = (safepoints == nullptr);
 563 

 564   Node* res = alloc->result_cast();
 565   const TypeOopPtr* res_type = nullptr;
 566   if (res == nullptr) {
 567     // All users were eliminated.
 568   } else if (!res->is_CheckCastPP()) {
 569     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 570     can_eliminate = false;
 571   } else {

 572     res_type = igvn->type(res)->isa_oopptr();
 573     if (res_type == nullptr) {
 574       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
 575       can_eliminate = false;
 576     } else if (!res_type->klass_is_exact()) {
 577       NOT_PRODUCT(fail_eliminate = "Not an exact type.";)
 578       can_eliminate = false;
 579     } else if (res_type->isa_aryptr()) {
 580       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 581       if (length < 0) {
 582         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 583         can_eliminate = false;
 584       }
 585     }
 586   }
 587 
 588   if (can_eliminate && res != nullptr) {
 589     BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 590     for (DUIterator_Fast jmax, j = res->fast_outs(jmax);
 591                                j < jmax && can_eliminate; j++) {
 592       Node* use = res->fast_out(j);
 593 
 594       if (use->is_AddP()) {
 595         const TypePtr* addp_type = igvn->type(use)->is_ptr();
 596         int offset = addp_type->offset();
 597 
 598         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 599           NOT_PRODUCT(fail_eliminate = "Undefined field reference";)
 600           can_eliminate = false;
 601           break;
 602         }
 603         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 604                                    k < kmax && can_eliminate; k++) {
 605           Node* n = use->fast_out(k);
 606           if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n) && !reduce_merge_precheck) {
 607             DEBUG_ONLY(disq_node = n;)
 608             if (n->is_Load() || n->is_LoadStore()) {
 609               NOT_PRODUCT(fail_eliminate = "Field load";)
 610             } else {
 611               NOT_PRODUCT(fail_eliminate = "Not store field reference";)

 617                  (use->as_ArrayCopy()->is_clonebasic() ||
 618                   use->as_ArrayCopy()->is_arraycopy_validated() ||
 619                   use->as_ArrayCopy()->is_copyof_validated() ||
 620                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
 621                  use->in(ArrayCopyNode::Dest) == res) {
 622         // ok to eliminate
 623       } else if (use->is_SafePoint()) {
 624         SafePointNode* sfpt = use->as_SafePoint();
 625         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 626           // Object is passed as argument.
 627           DEBUG_ONLY(disq_node = use;)
 628           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 629           can_eliminate = false;
 630         }
 631         Node* sfptMem = sfpt->memory();
 632         if (sfptMem == nullptr || sfptMem->is_top()) {
 633           DEBUG_ONLY(disq_node = use;)
 634           NOT_PRODUCT(fail_eliminate = "null or TOP memory";)
 635           can_eliminate = false;
 636         } else if (!reduce_merge_precheck) {

 637           safepoints->append_if_missing(sfpt);
 638         }























 639       } else if (reduce_merge_precheck &&
 640                  (use->is_Phi() || use->is_EncodeP() ||
 641                   use->Opcode() == Op_MemBarRelease ||
 642                   (UseStoreStoreForCtor && use->Opcode() == Op_MemBarStoreStore))) {
 643         // Nothing to do
 644       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 645         if (use->is_Phi()) {
 646           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 647             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 648           } else {
 649             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 650           }
 651           DEBUG_ONLY(disq_node = use;)
 652         } else {
 653           if (use->Opcode() == Op_Return) {
 654             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 655           } else {
 656             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 657           }
 658           DEBUG_ONLY(disq_node = use;)
 659         }
 660         can_eliminate = false;



 661       }
 662     }
 663   }
 664 
 665 #ifndef PRODUCT
 666   if (PrintEliminateAllocations && safepoints != nullptr) {
 667     if (can_eliminate) {
 668       tty->print("Scalar ");
 669       if (res == nullptr)
 670         alloc->dump();
 671       else
 672         res->dump();
 673     } else if (alloc->_is_scalar_replaceable) {
 674       tty->print("NotScalar (%s)", fail_eliminate);
 675       if (res == nullptr)
 676         alloc->dump();
 677       else
 678         res->dump();
 679 #ifdef ASSERT
 680       if (disq_node != nullptr) {
 681           tty->print("  >>>> ");
 682           disq_node->dump();
 683       }
 684 #endif /*ASSERT*/
 685     }
 686   }
 687 
 688   if (TraceReduceAllocationMerges && !can_eliminate && reduce_merge_precheck) {
 689     tty->print_cr("\tCan't eliminate allocation because '%s': ", fail_eliminate != nullptr ? fail_eliminate : "");
 690     DEBUG_ONLY(if (disq_node != nullptr) disq_node->dump();)
 691   }
 692 #endif
 693   return can_eliminate;

 723     JVMState *jvms = sfpt_done->jvms();
 724     jvms->set_endoff(sfpt_done->req());
 725     // Now make a pass over the debug information replacing any references
 726     // to SafePointScalarObjectNode with the allocated object.
 727     int start = jvms->debug_start();
 728     int end   = jvms->debug_end();
 729     for (int i = start; i < end; i++) {
 730       if (sfpt_done->in(i)->is_SafePointScalarObject()) {
 731         SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
 732         if (scobj->first_index(jvms) == sfpt_done->req() &&
 733             scobj->n_fields() == (uint)nfields) {
 734           assert(scobj->alloc() == alloc, "sanity");
 735           sfpt_done->set_req(i, res);
 736         }
 737       }
 738     }
 739     _igvn._worklist.push(sfpt_done);
 740   }
 741 }
 742 
 743 SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_description(AllocateNode *alloc, SafePointNode* sfpt) {

 744   // Fields of scalar objs are referenced only at the end
 745   // of regular debuginfo at the last (youngest) JVMS.
 746   // Record relative start index.
 747   ciInstanceKlass* iklass    = nullptr;
 748   BasicType basic_elem_type  = T_ILLEGAL;
 749   const Type* field_type     = nullptr;
 750   const TypeOopPtr* res_type = nullptr;
 751   int nfields                = 0;
 752   int array_base             = 0;
 753   int element_size           = 0;
 754   uint first_ind             = (sfpt->req() - sfpt->jvms()->scloff());
 755   Node* res                  = alloc->result_cast();
 756 
 757   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
 758   assert(sfpt->jvms() != nullptr, "missed JVMS");
 759 
 760   if (res != nullptr) { // Could be null when there are no users
 761     res_type = _igvn.type(res)->isa_oopptr();
 762 
 763     if (res_type->isa_instptr()) {
 764       // find the fields of the class which will be needed for safepoint debug information
 765       iklass = res_type->is_instptr()->instance_klass();
 766       nfields = iklass->nof_nonstatic_fields();
 767     } else {
 768       // find the array's elements which will be needed for safepoint debug information
 769       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 770       assert(nfields >= 0, "must be an array klass.");
 771       basic_elem_type = res_type->is_aryptr()->elem()->array_element_basic_type();
 772       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 773       element_size = type2aelembytes(basic_elem_type);
 774       field_type = res_type->is_aryptr()->elem();














 775     }
 776   }
 777 
 778   SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type, alloc, first_ind, sfpt->jvms()->depth(), nfields);
 779   sobj->init_req(0, C->root());
 780   transform_later(sobj);
 781 
 782   // Scan object's fields adding an input to the safepoint for each field.
 783   for (int j = 0; j < nfields; j++) {
 784     intptr_t offset;
 785     ciField* field = nullptr;
 786     if (iklass != nullptr) {
 787       field = iklass->nonstatic_field_at(j);
 788       offset = field->offset_in_bytes();
 789       ciType* elem_type = field->type();
 790       basic_elem_type = field->layout_type();

 791 
 792       // The next code is taken from Parse::do_get_xxx().
 793       if (is_reference_type(basic_elem_type)) {
 794         if (!elem_type->is_loaded()) {
 795           field_type = TypeInstPtr::BOTTOM;
 796         } else if (field != nullptr && field->is_static_constant()) {
 797           ciObject* con = field->constant_value().as_object();
 798           // Do not "join" in the previous type; it doesn't add value,
 799           // and may yield a vacuous result if the field is of interface type.
 800           field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 801           assert(field_type != nullptr, "field singleton type must be consistent");
 802         } else {
 803           field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 804         }
 805         if (UseCompressedOops) {
 806           field_type = field_type->make_narrowoop();
 807           basic_elem_type = T_NARROWOOP;
 808         }
 809       } else {
 810         field_type = Type::get_const_basic_type(basic_elem_type);
 811       }
 812     } else {
 813       offset = array_base + j * (intptr_t)element_size;
 814     }
 815 
 816     const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 817 
 818     Node *field_val = value_from_mem(sfpt->memory(), sfpt->control(), basic_elem_type, field_type, field_addr_type, alloc);






 819 
 820     // We weren't able to find a value for this field,
 821     // give up on eliminating this allocation.
 822     if (field_val == nullptr) {
 823       uint last = sfpt->req() - 1;
 824       for (int k = 0;  k < j; k++) {
 825         sfpt->del_req(last--);
 826       }
 827       _igvn._worklist.push(sfpt);
 828 
 829 #ifndef PRODUCT
 830       if (PrintEliminateAllocations) {
 831         if (field != nullptr) {
 832           tty->print("=== At SafePoint node %d can't find value of field: ", sfpt->_idx);
 833           field->print();
 834           int field_idx = C->get_alias_index(field_addr_type);
 835           tty->print(" (alias_idx=%d)", field_idx);
 836         } else { // Array's element
 837           tty->print("=== At SafePoint node %d can't find value of array element [%d]", sfpt->_idx, j);
 838         }
 839         tty->print(", which prevents elimination of: ");
 840         if (res == nullptr)
 841           alloc->dump();
 842         else
 843           res->dump();
 844       }
 845 #endif
 846 
 847       return nullptr;
 848     }
 849 
 850     if (UseCompressedOops && field_type->isa_narrowoop()) {
 851       // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 852       // to be able scalar replace the allocation.
 853       if (field_val->is_EncodeP()) {
 854         field_val = field_val->in(1);
 855       } else {
 856         field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 857       }
 858     }













 859     sfpt->add_req(field_val);
 860   }
 861 
 862   sfpt->jvms()->set_endoff(sfpt->req());
 863 
 864   return sobj;
 865 }
 866 
 867 // Do scalar replacement.
 868 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 869   GrowableArray <SafePointNode *> safepoints_done;
 870   Node* res = alloc->result_cast();
 871   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");




 872 
 873   // Process the safepoint uses



 874   while (safepoints.length() > 0) {
 875     SafePointNode* sfpt = safepoints.pop();
 876     SafePointScalarObjectNode* sobj = create_scalarized_object_description(alloc, sfpt);
 877 
 878     if (sobj == nullptr) {
 879       undo_previous_scalarizations(safepoints_done, alloc);
 880       return false;
 881     }
 882 
 883     // Now make a pass over the debug information replacing any references
 884     // to the allocated object with "sobj"
 885     JVMState *jvms = sfpt->jvms();
 886     sfpt->replace_edges_in_range(res, sobj, jvms->debug_start(), jvms->debug_end(), &_igvn);
 887     _igvn._worklist.push(sfpt);
 888 
 889     // keep it for rollback
 890     safepoints_done.append_if_missing(sfpt);
 891   }
 892 







 893   return true;
 894 }
 895 
 896 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
 897   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
 898   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
 899   if (ctl_proj != nullptr) {
 900     igvn.replace_node(ctl_proj, n->in(0));
 901   }
 902   if (mem_proj != nullptr) {
 903     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
 904   }
 905 }
 906 
 907 // Process users of eliminated allocation.
 908 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc) {

 909   Node* res = alloc->result_cast();
 910   if (res != nullptr) {




 911     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
 912       Node *use = res->last_out(j);
 913       uint oc1 = res->outcnt();
 914 
 915       if (use->is_AddP()) {
 916         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
 917           Node *n = use->last_out(k);
 918           uint oc2 = use->outcnt();
 919           if (n->is_Store()) {
 920 #ifdef ASSERT
 921             // Verify that there is no dependent MemBarVolatile nodes,
 922             // they should be removed during IGVN, see MemBarNode::Ideal().
 923             for (DUIterator_Fast pmax, p = n->fast_outs(pmax);
 924                                        p < pmax; p++) {
 925               Node* mb = n->fast_out(p);
 926               assert(mb->is_Initialize() || !mb->is_MemBar() ||
 927                      mb->req() <= MemBarNode::Precedent ||
 928                      mb->in(MemBarNode::Precedent) != n,
 929                      "MemBarVolatile should be eliminated for non-escaping object");
 930             }
 931 #endif
 932             _igvn.replace_node(n, n->in(MemNode::Memory));
 933           } else {
 934             eliminate_gc_barrier(n);
 935           }
 936           k -= (oc2 - use->outcnt());
 937         }
 938         _igvn.remove_dead_node(use);
 939       } else if (use->is_ArrayCopy()) {
 940         // Disconnect ArrayCopy node
 941         ArrayCopyNode* ac = use->as_ArrayCopy();
 942         if (ac->is_clonebasic()) {
 943           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
 944           disconnect_projections(ac, _igvn);
 945           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
 946           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
 947           disconnect_projections(membar_before->as_MemBar(), _igvn);
 948           if (membar_after->is_MemBar()) {
 949             disconnect_projections(membar_after->as_MemBar(), _igvn);
 950           }
 951         } else {
 952           assert(ac->is_arraycopy_validated() ||
 953                  ac->is_copyof_validated() ||
 954                  ac->is_copyofrange_validated(), "unsupported");
 955           CallProjections callprojs;
 956           ac->extract_projections(&callprojs, true);
 957 
 958           _igvn.replace_node(callprojs.fallthrough_ioproj, ac->in(TypeFunc::I_O));
 959           _igvn.replace_node(callprojs.fallthrough_memproj, ac->in(TypeFunc::Memory));
 960           _igvn.replace_node(callprojs.fallthrough_catchproj, ac->in(TypeFunc::Control));
 961 
 962           // Set control to top. IGVN will remove the remaining projections
 963           ac->set_req(0, top());
 964           ac->replace_edge(res, top(), &_igvn);
 965 
 966           // Disconnect src right away: it can help find new
 967           // opportunities for allocation elimination
 968           Node* src = ac->in(ArrayCopyNode::Src);
 969           ac->replace_edge(src, top(), &_igvn);
 970           // src can be top at this point if src and dest of the
 971           // arraycopy were the same
 972           if (src->outcnt() == 0 && !src->is_top()) {
 973             _igvn.remove_dead_node(src);
 974           }
 975         }
 976         _igvn._worklist.push(ac);























 977       } else {
 978         eliminate_gc_barrier(use);
 979       }
 980       j -= (oc1 - res->outcnt());
 981     }
 982     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
 983     _igvn.remove_dead_node(res);
 984   }
 985 
 986   //
 987   // Process other users of allocation's projections
 988   //
 989   if (_callprojs.resproj != nullptr && _callprojs.resproj->outcnt() != 0) {
 990     // First disconnect stores captured by Initialize node.
 991     // If Initialize node is eliminated first in the following code,
 992     // it will kill such stores and DUIterator_Last will assert.
 993     for (DUIterator_Fast jmax, j = _callprojs.resproj->fast_outs(jmax);  j < jmax; j++) {
 994       Node* use = _callprojs.resproj->fast_out(j);
 995       if (use->is_AddP()) {
 996         // raw memory addresses used only by the initialization
 997         _igvn.replace_node(use, C->top());
 998         --j; --jmax;
 999       }
1000     }
1001     for (DUIterator_Last jmin, j = _callprojs.resproj->last_outs(jmin); j >= jmin; ) {
1002       Node* use = _callprojs.resproj->last_out(j);
1003       uint oc1 = _callprojs.resproj->outcnt();
1004       if (use->is_Initialize()) {
1005         // Eliminate Initialize node.
1006         InitializeNode *init = use->as_Initialize();
1007         assert(init->outcnt() <= 2, "only a control and memory projection expected");
1008         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1009         if (ctrl_proj != nullptr) {
1010           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1011 #ifdef ASSERT
1012           // If the InitializeNode has no memory out, it will die, and tmp will become null
1013           Node* tmp = init->in(TypeFunc::Control);
1014           assert(tmp == nullptr || tmp == _callprojs.fallthrough_catchproj, "allocation control projection");
1015 #endif
1016         }
1017         Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
1018         if (mem_proj != nullptr) {
1019           Node *mem = init->in(TypeFunc::Memory);
1020 #ifdef ASSERT
1021           if (mem->is_MergeMem()) {
1022             assert(mem->in(TypeFunc::Memory) == _callprojs.fallthrough_memproj, "allocation memory projection");
1023           } else {
1024             assert(mem == _callprojs.fallthrough_memproj, "allocation memory projection");
1025           }
1026 #endif
1027           _igvn.replace_node(mem_proj, mem);
1028         }




1029       } else  {
1030         assert(false, "only Initialize or AddP expected");
1031       }
1032       j -= (oc1 - _callprojs.resproj->outcnt());
1033     }
1034   }
1035   if (_callprojs.fallthrough_catchproj != nullptr) {
1036     _igvn.replace_node(_callprojs.fallthrough_catchproj, alloc->in(TypeFunc::Control));
1037   }
1038   if (_callprojs.fallthrough_memproj != nullptr) {
1039     _igvn.replace_node(_callprojs.fallthrough_memproj, alloc->in(TypeFunc::Memory));
1040   }
1041   if (_callprojs.catchall_memproj != nullptr) {
1042     _igvn.replace_node(_callprojs.catchall_memproj, C->top());
1043   }
1044   if (_callprojs.fallthrough_ioproj != nullptr) {
1045     _igvn.replace_node(_callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
1046   }
1047   if (_callprojs.catchall_ioproj != nullptr) {
1048     _igvn.replace_node(_callprojs.catchall_ioproj, C->top());
1049   }
1050   if (_callprojs.catchall_catchproj != nullptr) {
1051     _igvn.replace_node(_callprojs.catchall_catchproj, C->top());
1052   }
1053 }
1054 
1055 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1056   // If reallocation fails during deoptimization we'll pop all
1057   // interpreter frames for this compiled frame and that won't play
1058   // nice with JVMTI popframe.
1059   // We avoid this issue by eager reallocation when the popframe request
1060   // is received.
1061   if (!EliminateAllocations || !alloc->_is_non_escaping) {
1062     return false;
1063   }
1064   Node* klass = alloc->in(AllocateNode::KlassNode);
1065   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1066   Node* res = alloc->result_cast();







1067   // Eliminate boxing allocations which are not used
1068   // regardless scalar replaceable status.
1069   bool boxing_alloc = C->eliminate_boxing() &&

1070                       tklass->isa_instklassptr() &&
1071                       tklass->is_instklassptr()->instance_klass()->is_box_klass();
1072   if (!alloc->_is_scalar_replaceable && (!boxing_alloc || (res != nullptr))) {
1073     return false;
1074   }
1075 
1076   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1077 
1078   GrowableArray <SafePointNode *> safepoints;
1079   if (!can_eliminate_allocation(&_igvn, alloc, &safepoints)) {
1080     return false;
1081   }
1082 
1083   if (!alloc->_is_scalar_replaceable) {
1084     assert(res == nullptr, "sanity");
1085     // We can only eliminate allocation if all debug info references
1086     // are already replaced with SafePointScalarObject because
1087     // we can't search for a fields value without instance_id.
1088     if (safepoints.length() > 0) {


1089       return false;
1090     }
1091   }
1092 
1093   if (!scalar_replacement(alloc, safepoints)) {
1094     return false;
1095   }
1096 
1097   CompileLog* log = C->log();
1098   if (log != nullptr) {
1099     log->head("eliminate_allocation type='%d'",
1100               log->identify(tklass->exact_klass()));
1101     JVMState* p = alloc->jvms();
1102     while (p != nullptr) {
1103       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1104       p = p->caller();
1105     }
1106     log->tail("eliminate_allocation");
1107   }
1108 
1109   process_users_of_allocation(alloc);
1110 
1111 #ifndef PRODUCT
1112   if (PrintEliminateAllocations) {
1113     if (alloc->is_AllocateArray())
1114       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1115     else
1116       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1117   }
1118 #endif
1119 
1120   return true;
1121 }
1122 
1123 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1124   // EA should remove all uses of non-escaping boxing node.
1125   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != nullptr) {
1126     return false;
1127   }
1128 
1129   assert(boxing->result_cast() == nullptr, "unexpected boxing node result");
1130 
1131   boxing->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1132 
1133   const TypeTuple* r = boxing->tf()->range();
1134   assert(r->cnt() > TypeFunc::Parms, "sanity");
1135   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1136   assert(t != nullptr, "sanity");
1137 
1138   CompileLog* log = C->log();
1139   if (log != nullptr) {
1140     log->head("eliminate_boxing type='%d'",
1141               log->identify(t->instance_klass()));
1142     JVMState* p = boxing->jvms();
1143     while (p != nullptr) {
1144       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1145       p = p->caller();
1146     }
1147     log->tail("eliminate_boxing");
1148   }
1149 
1150   process_users_of_allocation(boxing);
1151 
1152 #ifndef PRODUCT
1153   if (PrintEliminateAllocations) {

1299 #endif
1300       yank_alloc_node(alloc);
1301       return;
1302     }
1303   }
1304 
1305   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1306   Node *slow_region = nullptr;
1307   Node *toobig_false = ctrl;
1308 
1309   // generate the initial test if necessary
1310   if (initial_slow_test != nullptr ) {
1311     assert (expand_fast_path, "Only need test if there is a fast path");
1312     slow_region = new RegionNode(3);
1313 
1314     // Now make the initial failure test.  Usually a too-big test but
1315     // might be a TRUE for finalizers.
1316     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1317     transform_later(toobig_iff);
1318     // Plug the failing-too-big test into the slow-path region
1319     Node *toobig_true = new IfTrueNode( toobig_iff );
1320     transform_later(toobig_true);
1321     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1322     toobig_false = new IfFalseNode( toobig_iff );
1323     transform_later(toobig_false);
1324   } else {
1325     // No initial test, just fall into next case
1326     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1327     toobig_false = ctrl;
1328     debug_only(slow_region = NodeSentinel);
1329   }
1330 
1331   // If we are here there are several possibilities
1332   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1333   // no_initial_check means a constant allocation.
1334   // - If check always evaluates to false -> expand_fast_path is false (see above)
1335   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1336   // if !allocation_has_use the fast path is empty
1337   // if !allocation_has_use && no_initial_check
1338   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1339   //   removed by yank_alloc_node above.
1340 
1341   Node *slow_mem = mem;  // save the current memory state for slow path
1342   // generate the fast allocation code unless we know that the initial test will always go slow
1343   if (expand_fast_path) {
1344     // Fast path modifies only raw memory.
1345     if (mem->is_MergeMem()) {
1346       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1347     }
1348 
1349     // allocate the Region and Phi nodes for the result
1350     result_region = new RegionNode(3);
1351     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1352     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1353 
1354     // Grab regular I/O before optional prefetch may change it.
1355     // Slow-path does no I/O so just set it to the original I/O.
1356     result_phi_i_o->init_req(slow_result_path, i_o);
1357 
1358     // Name successful fast-path variables
1359     Node* fast_oop_ctrl;
1360     Node* fast_oop_rawmem;

1361     if (allocation_has_use) {
1362       Node* needgc_ctrl = nullptr;
1363       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1364 
1365       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1366       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1367       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1368                                         fast_oop_ctrl, fast_oop_rawmem,
1369                                         prefetch_lines);
1370 
1371       if (initial_slow_test != nullptr) {
1372         // This completes all paths into the slow merge point
1373         slow_region->init_req(need_gc_path, needgc_ctrl);
1374         transform_later(slow_region);
1375       } else {
1376         // No initial slow path needed!
1377         // Just fall from the need-GC path straight into the VM call.
1378         slow_region = needgc_ctrl;
1379       }
1380 

1398     result_phi_i_o   ->init_req(fast_result_path, i_o);
1399     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1400   } else {
1401     slow_region = ctrl;
1402     result_phi_i_o = i_o; // Rename it to use in the following code.
1403   }
1404 
1405   // Generate slow-path call
1406   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1407                                OptoRuntime::stub_name(slow_call_address),
1408                                TypePtr::BOTTOM);
1409   call->init_req(TypeFunc::Control,   slow_region);
1410   call->init_req(TypeFunc::I_O,       top());    // does no i/o
1411   call->init_req(TypeFunc::Memory,    slow_mem); // may gc ptrs
1412   call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1413   call->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1414 
1415   call->init_req(TypeFunc::Parms+0, klass_node);
1416   if (length != nullptr) {
1417     call->init_req(TypeFunc::Parms+1, length);



1418   }
1419 
1420   // Copy debug information and adjust JVMState information, then replace
1421   // allocate node with the call
1422   call->copy_call_debug_info(&_igvn, alloc);
1423   // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify
1424   // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough
1425   // path dies).
1426   if (valid_length_test != nullptr) {
1427     call->add_req(valid_length_test);
1428   }
1429   if (expand_fast_path) {
1430     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1431   } else {
1432     // Hook i_o projection to avoid its elimination during allocation
1433     // replacement (when only a slow call is generated).
1434     call->set_req(TypeFunc::I_O, result_phi_i_o);
1435   }
1436   _igvn.replace_node(alloc, call);
1437   transform_later(call);
1438 
1439   // Identify the output projections from the allocate node and
1440   // adjust any references to them.
1441   // The control and io projections look like:
1442   //
1443   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1444   //  Allocate                   Catch
1445   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1446   //
1447   //  We are interested in the CatchProj nodes.
1448   //
1449   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1450 
1451   // An allocate node has separate memory projections for the uses on
1452   // the control and i_o paths. Replace the control memory projection with
1453   // result_phi_rawmem (unless we are only generating a slow call when
1454   // both memory projections are combined)
1455   if (expand_fast_path && _callprojs.fallthrough_memproj != nullptr) {
1456     migrate_outs(_callprojs.fallthrough_memproj, result_phi_rawmem);
1457   }
1458   // Now change uses of catchall_memproj to use fallthrough_memproj and delete
1459   // catchall_memproj so we end up with a call that has only 1 memory projection.
1460   if (_callprojs.catchall_memproj != nullptr ) {
1461     if (_callprojs.fallthrough_memproj == nullptr) {
1462       _callprojs.fallthrough_memproj = new ProjNode(call, TypeFunc::Memory);
1463       transform_later(_callprojs.fallthrough_memproj);
1464     }
1465     migrate_outs(_callprojs.catchall_memproj, _callprojs.fallthrough_memproj);
1466     _igvn.remove_dead_node(_callprojs.catchall_memproj);
1467   }
1468 
1469   // An allocate node has separate i_o projections for the uses on the control
1470   // and i_o paths. Always replace the control i_o projection with result i_o
1471   // otherwise incoming i_o become dead when only a slow call is generated
1472   // (it is different from memory projections where both projections are
1473   // combined in such case).
1474   if (_callprojs.fallthrough_ioproj != nullptr) {
1475     migrate_outs(_callprojs.fallthrough_ioproj, result_phi_i_o);
1476   }
1477   // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete
1478   // catchall_ioproj so we end up with a call that has only 1 i_o projection.
1479   if (_callprojs.catchall_ioproj != nullptr ) {
1480     if (_callprojs.fallthrough_ioproj == nullptr) {
1481       _callprojs.fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O);
1482       transform_later(_callprojs.fallthrough_ioproj);
1483     }
1484     migrate_outs(_callprojs.catchall_ioproj, _callprojs.fallthrough_ioproj);
1485     _igvn.remove_dead_node(_callprojs.catchall_ioproj);
1486   }
1487 
1488   // if we generated only a slow call, we are done
1489   if (!expand_fast_path) {
1490     // Now we can unhook i_o.
1491     if (result_phi_i_o->outcnt() > 1) {
1492       call->set_req(TypeFunc::I_O, top());
1493     } else {
1494       assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1495       // Case of new array with negative size known during compilation.
1496       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1497       // following code since call to runtime will throw exception.
1498       // As result there will be no users of i_o after the call.
1499       // Leave i_o attached to this call to avoid problems in preceding graph.
1500     }
1501     return;
1502   }
1503 
1504   if (_callprojs.fallthrough_catchproj != nullptr) {
1505     ctrl = _callprojs.fallthrough_catchproj->clone();
1506     transform_later(ctrl);
1507     _igvn.replace_node(_callprojs.fallthrough_catchproj, result_region);
1508   } else {
1509     ctrl = top();
1510   }
1511   Node *slow_result;
1512   if (_callprojs.resproj == nullptr) {
1513     // no uses of the allocation result
1514     slow_result = top();
1515   } else {
1516     slow_result = _callprojs.resproj->clone();
1517     transform_later(slow_result);
1518     _igvn.replace_node(_callprojs.resproj, result_phi_rawoop);
1519   }
1520 
1521   // Plug slow-path into result merge point
1522   result_region->init_req( slow_result_path, ctrl);
1523   transform_later(result_region);
1524   if (allocation_has_use) {
1525     result_phi_rawoop->init_req(slow_result_path, slow_result);
1526     transform_later(result_phi_rawoop);
1527   }
1528   result_phi_rawmem->init_req(slow_result_path, _callprojs.fallthrough_memproj);
1529   transform_later(result_phi_rawmem);
1530   transform_later(result_phi_i_o);
1531   // This completes all paths into the result merge point
1532 }
1533 
1534 // Remove alloc node that has no uses.
1535 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1536   Node* ctrl = alloc->in(TypeFunc::Control);
1537   Node* mem  = alloc->in(TypeFunc::Memory);
1538   Node* i_o  = alloc->in(TypeFunc::I_O);
1539 
1540   alloc->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
1541   if (_callprojs.resproj != nullptr) {
1542     for (DUIterator_Fast imax, i = _callprojs.resproj->fast_outs(imax); i < imax; i++) {
1543       Node* use = _callprojs.resproj->fast_out(i);
1544       use->isa_MemBar()->remove(&_igvn);
1545       --imax;
1546       --i; // back up iterator
1547     }
1548     assert(_callprojs.resproj->outcnt() == 0, "all uses must be deleted");
1549     _igvn.remove_dead_node(_callprojs.resproj);
1550   }
1551   if (_callprojs.fallthrough_catchproj != nullptr) {
1552     migrate_outs(_callprojs.fallthrough_catchproj, ctrl);
1553     _igvn.remove_dead_node(_callprojs.fallthrough_catchproj);
1554   }
1555   if (_callprojs.catchall_catchproj != nullptr) {
1556     _igvn.rehash_node_delayed(_callprojs.catchall_catchproj);
1557     _callprojs.catchall_catchproj->set_req(0, top());
1558   }
1559   if (_callprojs.fallthrough_proj != nullptr) {
1560     Node* catchnode = _callprojs.fallthrough_proj->unique_ctrl_out();
1561     _igvn.remove_dead_node(catchnode);
1562     _igvn.remove_dead_node(_callprojs.fallthrough_proj);
1563   }
1564   if (_callprojs.fallthrough_memproj != nullptr) {
1565     migrate_outs(_callprojs.fallthrough_memproj, mem);
1566     _igvn.remove_dead_node(_callprojs.fallthrough_memproj);
1567   }
1568   if (_callprojs.fallthrough_ioproj != nullptr) {
1569     migrate_outs(_callprojs.fallthrough_ioproj, i_o);
1570     _igvn.remove_dead_node(_callprojs.fallthrough_ioproj);
1571   }
1572   if (_callprojs.catchall_memproj != nullptr) {
1573     _igvn.rehash_node_delayed(_callprojs.catchall_memproj);
1574     _callprojs.catchall_memproj->set_req(0, top());
1575   }
1576   if (_callprojs.catchall_ioproj != nullptr) {
1577     _igvn.rehash_node_delayed(_callprojs.catchall_ioproj);
1578     _callprojs.catchall_ioproj->set_req(0, top());
1579   }
1580 #ifndef PRODUCT
1581   if (PrintEliminateAllocations) {
1582     if (alloc->is_AllocateArray()) {
1583       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1584     } else {
1585       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1586     }
1587   }
1588 #endif
1589   _igvn.remove_dead_node(alloc);
1590 }
1591 
1592 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1593                                                 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1594   // If initialization is performed by an array copy, any required
1595   // MemBarStoreStore was already added. If the object does not
1596   // escape no need for a MemBarStoreStore. If the object does not
1597   // escape in its initializer and memory barrier (MemBarStoreStore or
1598   // stronger) is already added at exit of initializer, also no need

1676     Node* thread = new ThreadLocalNode();
1677     transform_later(thread);
1678 
1679     call->init_req(TypeFunc::Parms + 0, thread);
1680     call->init_req(TypeFunc::Parms + 1, oop);
1681     call->init_req(TypeFunc::Control, ctrl);
1682     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1683     call->init_req(TypeFunc::Memory , rawmem);
1684     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1685     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1686     transform_later(call);
1687     ctrl = new ProjNode(call, TypeFunc::Control);
1688     transform_later(ctrl);
1689     rawmem = new ProjNode(call, TypeFunc::Memory);
1690     transform_later(rawmem);
1691   }
1692 }
1693 
1694 // Helper for PhaseMacroExpand::expand_allocate_common.
1695 // Initializes the newly-allocated storage.
1696 Node*
1697 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1698                                     Node* control, Node* rawmem, Node* object,
1699                                     Node* klass_node, Node* length,
1700                                     Node* size_in_bytes) {
1701   InitializeNode* init = alloc->initialization();
1702   // Store the klass & mark bits
1703   Node* mark_node = alloc->make_ideal_mark(&_igvn, object, control, rawmem);
1704   if (!mark_node->is_Con()) {
1705     transform_later(mark_node);
1706   }
1707   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1708 
1709   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1710   int header_size = alloc->minimum_header_size();  // conservatively small
1711 
1712   // Array length
1713   if (length != nullptr) {         // Arrays need length field
1714     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1715     // conservatively small header size:
1716     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1717     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
1718       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
1719       if (is_reference_type(elem, true)) {
1720         elem = T_OBJECT;
1721       }
1722       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
1723     }
1724   }
1725 
1726   // Clear the object body, if necessary.
1727   if (init == nullptr) {
1728     // The init has somehow disappeared; be cautious and clear everything.
1729     //
1730     // This can happen if a node is allocated but an uncommon trap occurs
1731     // immediately.  In this case, the Initialize gets associated with the
1732     // trap, and may be placed in a different (outer) loop, if the Allocate
1733     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1734     // there can be two Allocates to one Initialize.  The answer in all these
1735     // edge cases is safety first.  It is always safe to clear immediately
1736     // within an Allocate, and then (maybe or maybe not) clear some more later.
1737     if (!(UseTLAB && ZeroTLAB)) {
1738       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,


1739                                             header_size, size_in_bytes,
1740                                             &_igvn);
1741     }
1742   } else {
1743     if (!init->is_complete()) {
1744       // Try to win by zeroing only what the init does not store.
1745       // We can also try to do some peephole optimizations,
1746       // such as combining some adjacent subword stores.
1747       rawmem = init->complete_stores(control, rawmem, object,
1748                                      header_size, size_in_bytes, &_igvn);
1749     }
1750     // We have no more use for this link, since the AllocateNode goes away:
1751     init->set_req(InitializeNode::RawAddress, top());
1752     // (If we keep the link, it just confuses the register allocator,
1753     // who thinks he sees a real use of the address by the membar.)
1754   }
1755 
1756   return rawmem;
1757 }
1758 

2126 #ifdef ASSERT
2127   if (!alock->is_coarsened()) {
2128     // Check that new "eliminated" BoxLock node is created.
2129     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2130     assert(oldbox->is_eliminated(), "should be done already");
2131   }
2132 #endif
2133 
2134   alock->log_lock_optimization(C, "eliminate_lock");
2135 
2136 #ifndef PRODUCT
2137   if (PrintEliminateLocks) {
2138     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2139   }
2140 #endif
2141 
2142   Node* mem  = alock->in(TypeFunc::Memory);
2143   Node* ctrl = alock->in(TypeFunc::Control);
2144   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2145 
2146   alock->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2147   // There are 2 projections from the lock.  The lock node will
2148   // be deleted when its last use is subsumed below.
2149   assert(alock->outcnt() == 2 &&
2150          _callprojs.fallthrough_proj != nullptr &&
2151          _callprojs.fallthrough_memproj != nullptr,
2152          "Unexpected projections from Lock/Unlock");
2153 
2154   Node* fallthroughproj = _callprojs.fallthrough_proj;
2155   Node* memproj_fallthrough = _callprojs.fallthrough_memproj;
2156 
2157   // The memory projection from a lock/unlock is RawMem
2158   // The input to a Lock is merged memory, so extract its RawMem input
2159   // (unless the MergeMem has been optimized away.)
2160   if (alock->is_Lock()) {
2161     // Search for MemBarAcquireLock node and delete it also.
2162     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2163     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2164     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2165     Node* memproj = membar->proj_out(TypeFunc::Memory);
2166     _igvn.replace_node(ctrlproj, fallthroughproj);
2167     _igvn.replace_node(memproj, memproj_fallthrough);
2168 
2169     // Delete FastLock node also if this Lock node is unique user
2170     // (a loop peeling may clone a Lock node).
2171     Node* flock = alock->as_Lock()->fastlock_node();
2172     if (flock->outcnt() == 1) {
2173       assert(flock->unique_out() == alock, "sanity");
2174       _igvn.replace_node(flock, top());
2175     }

2206   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2207 
2208   // Make the merge point
2209   Node *region;
2210   Node *mem_phi;
2211   Node *slow_path;
2212 
2213   region  = new RegionNode(3);
2214   // create a Phi for the memory state
2215   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2216 
2217   // Optimize test; set region slot 2
2218   slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2219   mem_phi->init_req(2, mem);
2220 
2221   // Make slow path call
2222   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2223                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2224                                   obj, box, nullptr);
2225 
2226   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2227 
2228   // Slow path can only throw asynchronous exceptions, which are always
2229   // de-opted.  So the compiler thinks the slow-call can never throw an
2230   // exception.  If it DOES throw an exception we would need the debug
2231   // info removed first (since if it throws there is no monitor).
2232   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2233          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2234 
2235   // Capture slow path
2236   // disconnect fall-through projection from call and create a new one
2237   // hook up users of fall-through projection to region
2238   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2239   transform_later(slow_ctrl);
2240   _igvn.hash_delete(_callprojs.fallthrough_proj);
2241   _callprojs.fallthrough_proj->disconnect_inputs(C);
2242   region->init_req(1, slow_ctrl);
2243   // region inputs are now complete
2244   transform_later(region);
2245   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2246 
2247   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2248 
2249   mem_phi->init_req(1, memproj);
2250 
2251   transform_later(mem_phi);
2252 
2253   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2254 }
2255 
2256 //------------------------------expand_unlock_node----------------------
2257 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2258 
2259   Node* ctrl = unlock->in(TypeFunc::Control);
2260   Node* mem = unlock->in(TypeFunc::Memory);
2261   Node* obj = unlock->obj_node();
2262   Node* box = unlock->box_node();
2263 
2264   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2265 
2266   // No need for a null check on unlock
2267 
2268   // Make the merge point
2269   Node *region;
2270   Node *mem_phi;
2271 
2272   region  = new RegionNode(3);
2273   // create a Phi for the memory state
2274   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2275 
2276   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2277   funlock = transform_later( funlock )->as_FastUnlock();
2278   // Optimize test; set region slot 2
2279   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2280   Node *thread = transform_later(new ThreadLocalNode());
2281 
2282   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2283                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2284                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2285 
2286   call->extract_projections(&_callprojs, false /*separate_io_proj*/, false /*do_asserts*/);
2287   assert(_callprojs.fallthrough_ioproj == nullptr && _callprojs.catchall_ioproj == nullptr &&
2288          _callprojs.catchall_memproj == nullptr && _callprojs.catchall_catchproj == nullptr, "Unexpected projection from Lock");
2289 
2290   // No exceptions for unlocking
2291   // Capture slow path
2292   // disconnect fall-through projection from call and create a new one
2293   // hook up users of fall-through projection to region
2294   Node *slow_ctrl = _callprojs.fallthrough_proj->clone();
2295   transform_later(slow_ctrl);
2296   _igvn.hash_delete(_callprojs.fallthrough_proj);
2297   _callprojs.fallthrough_proj->disconnect_inputs(C);
2298   region->init_req(1, slow_ctrl);
2299   // region inputs are now complete
2300   transform_later(region);
2301   _igvn.replace_node(_callprojs.fallthrough_proj, region);
2302 
2303   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2304   mem_phi->init_req(1, memproj );
2305   mem_phi->init_req(2, mem);
2306   transform_later(mem_phi);
2307 
2308   _igvn.replace_node(_callprojs.fallthrough_memproj, mem_phi);
2309 }
2310 



















































































































































































































2311 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2312   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2313   Node* bol = check->unique_out();
2314   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2315   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2316   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2317 
2318   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2319     Node* iff = bol->last_out(i);
2320     assert(iff->is_If(), "where's the if?");
2321 
2322     if (iff->in(0)->is_top()) {
2323       _igvn.replace_input_of(iff, 1, C->top());
2324       continue;
2325     }
2326 
2327     Node* iftrue = iff->as_If()->proj_out(1);
2328     Node* iffalse = iff->as_If()->proj_out(0);
2329     Node* ctrl = iff->in(0);
2330 
2331     Node* subklass = nullptr;
2332     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2333       subklass = obj_or_subklass;
2334     } else {
2335       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2336       subklass = _igvn.transform(LoadKlassNode::make(_igvn, nullptr, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2337     }
2338 
2339     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci());
2340 
2341     _igvn.replace_input_of(iff, 0, C->top());
2342     _igvn.replace_node(iftrue, not_subtype_ctrl);
2343     _igvn.replace_node(iffalse, ctrl);
2344   }
2345   _igvn.replace_node(check, C->top());
2346 }
2347 

















































































































2348 //---------------------------eliminate_macro_nodes----------------------
2349 // Eliminate scalar replaced allocations and associated locks.
2350 void PhaseMacroExpand::eliminate_macro_nodes() {
2351   if (C->macro_count() == 0)
2352     return;
2353   NOT_PRODUCT(int membar_before = count_MemBar(C);)
2354 
2355   // Before elimination may re-mark (change to Nested or NonEscObj)
2356   // all associated (same box and obj) lock and unlock nodes.
2357   int cnt = C->macro_count();
2358   for (int i=0; i < cnt; i++) {
2359     Node *n = C->macro_node(i);
2360     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2361       mark_eliminated_locking_nodes(n->as_AbstractLock());
2362     }
2363   }
2364   // Re-marking may break consistency of Coarsened locks.
2365   if (!C->coarsened_locks_consistent()) {
2366     return; // recompile without Coarsened locks if broken
2367   } else {

2393   }
2394   // Next, attempt to eliminate allocations
2395   _has_locks = false;
2396   progress = true;
2397   while (progress) {
2398     progress = false;
2399     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2400       Node* n = C->macro_node(i - 1);
2401       bool success = false;
2402       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2403       switch (n->class_id()) {
2404       case Node::Class_Allocate:
2405       case Node::Class_AllocateArray:
2406         success = eliminate_allocate_node(n->as_Allocate());
2407 #ifndef PRODUCT
2408         if (success && PrintOptoStatistics) {
2409           Atomic::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
2410         }
2411 #endif
2412         break;
2413       case Node::Class_CallStaticJava:
2414         success = eliminate_boxing_node(n->as_CallStaticJava());



2415         break;

2416       case Node::Class_Lock:
2417       case Node::Class_Unlock:
2418         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2419         _has_locks = true;
2420         break;
2421       case Node::Class_ArrayCopy:
2422         break;
2423       case Node::Class_OuterStripMinedLoop:
2424         break;
2425       case Node::Class_SubTypeCheck:
2426         break;
2427       case Node::Class_Opaque1:
2428         break;


2429       default:
2430         assert(n->Opcode() == Op_LoopLimit ||
2431                n->is_OpaqueNotNull()       ||
2432                n->is_OpaqueInitializedAssertionPredicate() ||
2433                n->Opcode() == Op_MaxL      ||
2434                n->Opcode() == Op_MinL      ||
2435                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2436                "unknown node type in macro list");
2437       }
2438       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2439       progress = progress || success;
2440     }
2441   }
2442 #ifndef PRODUCT
2443   if (PrintOptoStatistics) {
2444     int membar_after = count_MemBar(C);
2445     Atomic::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
2446   }
2447 #endif
2448 }

2456     C->shuffle_macro_nodes();
2457   }
2458   // Last attempt to eliminate macro nodes.
2459   eliminate_macro_nodes();
2460   if (C->failing())  return true;
2461 
2462   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2463   bool progress = true;
2464   while (progress) {
2465     progress = false;
2466     for (int i = C->macro_count(); i > 0; i--) {
2467       Node* n = C->macro_node(i-1);
2468       bool success = false;
2469       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2470       if (n->Opcode() == Op_LoopLimit) {
2471         // Remove it from macro list and put on IGVN worklist to optimize.
2472         C->remove_macro_node(n);
2473         _igvn._worklist.push(n);
2474         success = true;
2475       } else if (n->Opcode() == Op_CallStaticJava) {
2476         // Remove it from macro list and put on IGVN worklist to optimize.
2477         C->remove_macro_node(n);
2478         _igvn._worklist.push(n);
2479         success = true;



2480       } else if (n->is_Opaque1()) {
2481         _igvn.replace_node(n, n->in(1));
2482         success = true;
2483       } else if (n->is_OpaqueNotNull()) {
2484         // Tests with OpaqueNotNull nodes are implicitly known to be true. Replace the node with true. In debug builds,
2485         // we leave the test in the graph to have an additional sanity check at runtime. If the test fails (i.e. a bug),
2486         // we will execute a Halt node.
2487 #ifdef ASSERT
2488         _igvn.replace_node(n, n->in(1));
2489 #else
2490         _igvn.replace_node(n, _igvn.intcon(1));
2491 #endif
2492         success = true;
2493       } else if (n->is_OpaqueInitializedAssertionPredicate()) {
2494           // Initialized Assertion Predicates must always evaluate to true. Therefore, we get rid of them in product
2495           // builds as they are useless. In debug builds we keep them as additional verification code. Even though
2496           // loop opts are already over, we want to keep Initialized Assertion Predicates alive as long as possible to
2497           // enable folding of dead control paths within which cast nodes become top after due to impossible types -
2498           // even after loop opts are over. Therefore, we delay the removal of these opaque nodes until now.
2499 #ifdef ASSERT

2561     // Worst case is a macro node gets expanded into about 200 nodes.
2562     // Allow 50% more for optimization.
2563     if (C->check_node_count(300, "out of nodes before macro expansion")) {
2564       return true;
2565     }
2566 
2567     DEBUG_ONLY(int old_macro_count = C->macro_count();)
2568     switch (n->class_id()) {
2569     case Node::Class_Lock:
2570       expand_lock_node(n->as_Lock());
2571       break;
2572     case Node::Class_Unlock:
2573       expand_unlock_node(n->as_Unlock());
2574       break;
2575     case Node::Class_ArrayCopy:
2576       expand_arraycopy_node(n->as_ArrayCopy());
2577       break;
2578     case Node::Class_SubTypeCheck:
2579       expand_subtypecheck_node(n->as_SubTypeCheck());
2580       break;







2581     default:
2582       assert(false, "unknown node type in macro list");
2583     }
2584     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2585     if (C->failing())  return true;
2586     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
2587 
2588     // Clean up the graph so we're less likely to hit the maximum node
2589     // limit
2590     _igvn.set_delay_transform(false);
2591     _igvn.optimize();
2592     if (C->failing())  return true;
2593     _igvn.set_delay_transform(true);
2594   }
2595 
2596   // All nodes except Allocate nodes are expanded now. There could be
2597   // new optimization opportunities (such as folding newly created
2598   // load from a just allocated object). Run IGVN.
2599 
2600   // expand "macro" nodes

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












  88 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word, int mask, int bits, bool return_fast_path) {
  89   Node* cmp;
  90   if (mask != 0) {
  91     Node* and_node = transform_later(new AndXNode(word, MakeConX(mask)));
  92     cmp = transform_later(new CmpXNode(and_node, MakeConX(bits)));
  93   } else {
  94     cmp = word;
  95   }
  96   Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
  97   IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
  98   transform_later(iff);
  99 
 100   // Fast path taken.
 101   Node *fast_taken = transform_later(new IfFalseNode(iff));
 102 
 103   // Fast path not-taken, i.e. slow path
 104   Node *slow_taken = transform_later(new IfTrueNode(iff));
 105 
 106   if (return_fast_path) {
 107     region->init_req(edge, slow_taken); // Capture slow-control

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

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

 230       }
 231       // Otherwise skip it (the call updated 'mem' value).
 232     } else if (mem->Opcode() == Op_SCMemProj) {
 233       mem = mem->in(0);
 234       Node* adr = nullptr;
 235       if (mem->is_LoadStore()) {
 236         adr = mem->in(MemNode::Address);
 237       } else {
 238         assert(mem->Opcode() == Op_EncodeISOArray ||
 239                mem->Opcode() == Op_StrCompressedCopy, "sanity");
 240         adr = mem->in(3); // Destination array
 241       }
 242       const TypePtr* atype = adr->bottom_type()->is_ptr();
 243       int adr_idx = phase->C->get_alias_index(atype);
 244       if (adr_idx == alias_idx) {
 245         DEBUG_ONLY(mem->dump();)
 246         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 247         return nullptr;
 248       }
 249       mem = mem->in(MemNode::Memory);
 250     } else if (mem->Opcode() == Op_StrInflatedCopy) {
 251       Node* adr = mem->in(3); // Destination array
 252       const TypePtr* atype = adr->bottom_type()->is_ptr();
 253       int adr_idx = phase->C->get_alias_index(atype);
 254       if (adr_idx == alias_idx) {
 255         DEBUG_ONLY(mem->dump();)
 256         assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
 257         return nullptr;
 258       }
 259       mem = mem->in(MemNode::Memory);
 260     } else {
 261       return mem;
 262     }
 263     assert(mem != orig_mem, "dead memory loop");
 264   }
 265 }
 266 
 267 // Generate loads from source of the arraycopy for fields of
 268 // destination needed at a deoptimization point
 269 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
 270   BasicType bt = ft;

 275   }
 276   Node* res = nullptr;
 277   if (ac->is_clonebasic()) {
 278     assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
 279     Node* base = ac->in(ArrayCopyNode::Src);
 280     Node* adr = _igvn.transform(new AddPNode(base, base, _igvn.MakeConX(offset)));
 281     const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
 282     MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 283     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 284     res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 285   } else {
 286     if (ac->modifies(offset, offset, &_igvn, true)) {
 287       assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
 288       uint shift = exact_log2(type2aelembytes(bt));
 289       Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
 290       Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
 291       const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
 292       const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
 293 
 294       Node* adr = nullptr;
 295       Node* base = ac->in(ArrayCopyNode::Src);
 296       const TypeAryPtr* adr_type = _igvn.type(base)->is_aryptr();
 297       if (adr_type->is_flat()) {
 298         shift = adr_type->flat_log_elem_size();
 299       }
 300       if (src_pos_t->is_con() && dest_pos_t->is_con()) {
 301         intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;

 302         adr = _igvn.transform(new AddPNode(base, base, _igvn.MakeConX(off)));
 303         adr_type = _igvn.type(adr)->is_aryptr();
 304         assert(adr_type == _igvn.type(base)->is_aryptr()->add_field_offset_and_offset(off), "incorrect address type");
 305         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 306           // Don't emit a new load from src if src == dst but try to get the value from memory instead
 307           return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type, alloc);
 308         }
 309       } else {
 310         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
 311           // Non constant offset in the array: we can't statically
 312           // determine the value
 313           return nullptr;
 314         }
 315         Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 316 #ifdef _LP64
 317         diff = _igvn.transform(new ConvI2LNode(diff));
 318 #endif
 319         diff = _igvn.transform(new LShiftXNode(diff, _igvn.intcon(shift)));
 320 
 321         Node* off = _igvn.transform(new AddXNode(_igvn.MakeConX(offset), diff));

 322         adr = _igvn.transform(new AddPNode(base, base, off));
 323         // In the case of a flat inline type array, each field has its
 324         // own slice so we need to extract the field being accessed from
 325         // the address computation
 326         adr_type = adr_type->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot)->is_aryptr();
 327         adr = _igvn.transform(new CastPPNode(ctl, adr, adr_type));

 328       }
 329       MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
 330       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 331       res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
 332     }
 333   }
 334   if (res != nullptr) {
 335     if (ftype->isa_narrowoop()) {
 336       // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
 337       assert(res->isa_DecodeN(), "should be narrow oop");
 338       res = _igvn.transform(new EncodePNode(res, ftype));
 339     }
 340     return res;
 341   }
 342   return nullptr;
 343 }
 344 
 345 //
 346 // Given a Memory Phi, compute a value Phi containing the values from stores
 347 // on the input paths.
 348 // Note: this function is recursive, its depth is limited by the "level" argument
 349 // Returns the computed Phi, or null if it cannot compute it.
 350 Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, AllocateNode *alloc, Node_Stack *value_phis, int level) {
 351   assert(mem->is_Phi(), "sanity");
 352   int alias_idx = C->get_alias_index(adr_t);
 353   int offset = adr_t->flat_offset();
 354   int instance_id = adr_t->instance_id();
 355 
 356   // Check if an appropriate value phi already exists.
 357   Node* region = mem->in(0);
 358   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
 359     Node* phi = region->fast_out(k);
 360     if (phi->is_Phi() && phi != mem &&
 361         phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
 362       return phi;
 363     }
 364   }
 365   // Check if an appropriate new value phi already exists.
 366   Node* new_phi = value_phis->find(mem->_idx);
 367   if (new_phi != nullptr)
 368     return new_phi;
 369 
 370   if (level <= 0) {
 371     return nullptr; // Give up: phi tree too deep
 372   }
 373   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
 374   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 375   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 376 
 377   uint length = mem->req();
 378   GrowableArray <Node *> values(length, length, nullptr);
 379 
 380   // create a new Phi for the value
 381   PhiNode *phi = new PhiNode(mem->in(0), phi_type, nullptr, mem->_idx, instance_id, alias_idx, offset);
 382   transform_later(phi);
 383   value_phis->push(phi, mem->_idx);
 384 
 385   for (uint j = 1; j < length; j++) {
 386     Node *in = mem->in(j);
 387     if (in == nullptr || in->is_top()) {
 388       values.at_put(j, in);
 389     } else {
 390       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
 391       if (val == start_mem || val == alloc_mem) {
 392         // hit a sentinel, return appropriate 0 value
 393         Node* default_value = alloc->in(AllocateNode::DefaultValue);
 394         if (default_value != nullptr) {
 395           values.at_put(j, default_value);
 396         } else {
 397           assert(alloc->in(AllocateNode::RawDefaultValue) == nullptr, "default value may not be null");
 398           values.at_put(j, _igvn.zerocon(ft));
 399         }
 400         continue;
 401       }
 402       if (val->is_Initialize()) {
 403         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 404       }
 405       if (val == nullptr) {
 406         return nullptr;  // can't find a value on this path
 407       }
 408       if (val == mem) {
 409         values.at_put(j, mem);
 410       } else if (val->is_Store()) {
 411         Node* n = val->in(MemNode::ValueIn);
 412         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 413         n = bs->step_over_gc_barrier(n);
 414         if (is_subword_type(ft)) {
 415           n = Compile::narrow_value(ft, n, phi_type, &_igvn, true);
 416         }
 417         values.at_put(j, n);
 418       } else if(val->is_Proj() && val->in(0) == alloc) {
 419         Node* default_value = alloc->in(AllocateNode::DefaultValue);
 420         if (default_value != nullptr) {
 421           values.at_put(j, default_value);
 422         } else {
 423           assert(alloc->in(AllocateNode::RawDefaultValue) == nullptr, "default value may not be null");
 424           values.at_put(j, _igvn.zerocon(ft));
 425         }
 426       } else if (val->is_Phi()) {
 427         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 428         if (val == nullptr) {
 429           return nullptr;
 430         }
 431         values.at_put(j, val);
 432       } else if (val->Opcode() == Op_SCMemProj) {
 433         assert(val->in(0)->is_LoadStore() ||
 434                val->in(0)->Opcode() == Op_EncodeISOArray ||
 435                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
 436         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
 437         return nullptr;
 438       } else if (val->is_ArrayCopy()) {
 439         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
 440         if (res == nullptr) {
 441           return nullptr;
 442         }
 443         values.at_put(j, res);
 444       } else {
 445         DEBUG_ONLY( val->dump(); )

 449     }
 450   }
 451   // Set Phi's inputs
 452   for (uint j = 1; j < length; j++) {
 453     if (values.at(j) == mem) {
 454       phi->init_req(j, phi);
 455     } else {
 456       phi->init_req(j, values.at(j));
 457     }
 458   }
 459   return phi;
 460 }
 461 
 462 // Search the last value stored into the object's field.
 463 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
 464   assert(adr_t->is_known_instance_field(), "instance required");
 465   int instance_id = adr_t->instance_id();
 466   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 467 
 468   int alias_idx = C->get_alias_index(adr_t);
 469   int offset = adr_t->flat_offset();
 470   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);

 471   Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
 472   assert(alloc_mem != nullptr, "Allocation without a memory projection.");
 473   VectorSet visited;
 474 
 475   bool done = sfpt_mem == alloc_mem;
 476   Node *mem = sfpt_mem;
 477   while (!done) {
 478     if (visited.test_set(mem->_idx)) {
 479       return nullptr;  // found a loop, give up
 480     }
 481     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 482     if (mem == start_mem || mem == alloc_mem) {
 483       done = true;  // hit a sentinel, return appropriate 0 value
 484     } else if (mem->is_Initialize()) {
 485       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 486       if (mem == nullptr) {
 487         done = true; // Something went wrong.
 488       } else if (mem->is_Store()) {
 489         const TypePtr* atype = mem->as_Store()->adr_type();
 490         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 491         done = true;
 492       }
 493     } else if (mem->is_Store()) {
 494       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 495       assert(atype != nullptr, "address type must be oopptr");
 496       assert(C->get_alias_index(atype) == alias_idx &&
 497              atype->is_known_instance_field() && atype->flat_offset() == offset &&
 498              atype->instance_id() == instance_id, "store is correct memory slice");
 499       done = true;
 500     } else if (mem->is_Phi()) {
 501       // try to find a phi's unique input
 502       Node *unique_input = nullptr;
 503       Node *top = C->top();
 504       for (uint i = 1; i < mem->req(); i++) {
 505         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 506         if (n == nullptr || n == top || n == mem) {
 507           continue;
 508         } else if (unique_input == nullptr) {
 509           unique_input = n;
 510         } else if (unique_input != n) {
 511           unique_input = top;
 512           break;
 513         }
 514       }
 515       if (unique_input != nullptr && unique_input != top) {
 516         mem = unique_input;
 517       } else {
 518         done = true;
 519       }
 520     } else if (mem->is_ArrayCopy()) {
 521       done = true;
 522     } else {
 523       DEBUG_ONLY( mem->dump(); )
 524       assert(false, "unexpected node");
 525     }
 526   }
 527   if (mem != nullptr) {
 528     if (mem == start_mem || mem == alloc_mem) {
 529       // hit a sentinel, return appropriate 0 value
 530       Node* default_value = alloc->in(AllocateNode::DefaultValue);
 531       if (default_value != nullptr) {
 532         return default_value;
 533       }
 534       assert(alloc->in(AllocateNode::RawDefaultValue) == nullptr, "default value may not be null");
 535       return _igvn.zerocon(ft);
 536     } else if (mem->is_Store()) {
 537       Node* n = mem->in(MemNode::ValueIn);
 538       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 539       n = bs->step_over_gc_barrier(n);
 540       return n;
 541     } else if (mem->is_Phi()) {
 542       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 543       Node_Stack value_phis(8);
 544       Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 545       if (phi != nullptr) {
 546         return phi;
 547       } else {
 548         // Kill all new Phis
 549         while(value_phis.is_nonempty()) {
 550           Node* n = value_phis.node();
 551           _igvn.replace_node(n, C->top());
 552           value_phis.pop();
 553         }
 554       }
 555     } else if (mem->is_ArrayCopy()) {
 556       Node* ctl = mem->in(0);
 557       Node* m = mem->in(TypeFunc::Memory);
 558       if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj()) {
 559         // pin the loads in the uncommon trap path
 560         ctl = sfpt_ctl;
 561         m = sfpt_mem;
 562       }
 563       return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
 564     }
 565   }
 566   // Something went wrong.
 567   return nullptr;
 568 }
 569 
 570 // Search the last value stored into the inline type's fields.
 571 Node* PhaseMacroExpand::inline_type_from_mem(Node* mem, Node* ctl, ciInlineKlass* vk, const TypeAryPtr* adr_type, int offset, AllocateNode* alloc) {
 572   // Subtract the offset of the first field to account for the missing oop header
 573   offset -= vk->first_field_offset();
 574   // Create a new InlineTypeNode and retrieve the field values from memory
 575   InlineTypeNode* vt = InlineTypeNode::make_uninitialized(_igvn, vk);
 576   transform_later(vt);
 577   for (int i = 0; i < vk->nof_declared_nonstatic_fields(); ++i) {
 578     ciType* field_type = vt->field_type(i);
 579     int field_offset = offset + vt->field_offset(i);
 580     Node* value = nullptr;
 581     if (vt->field_is_flat(i)) {
 582       value = inline_type_from_mem(mem, ctl, field_type->as_inline_klass(), adr_type, field_offset, alloc);
 583     } else {
 584       const Type* ft = Type::get_const_type(field_type);
 585       BasicType bt = type2field[field_type->basic_type()];
 586       if (UseCompressedOops && !is_java_primitive(bt)) {
 587         ft = ft->make_narrowoop();
 588         bt = T_NARROWOOP;
 589       }
 590       // Each inline type field has its own memory slice
 591       adr_type = adr_type->with_field_offset(field_offset);
 592       value = value_from_mem(mem, ctl, bt, ft, adr_type, alloc);
 593       if (value != nullptr && ft->isa_narrowoop()) {
 594         assert(UseCompressedOops, "unexpected narrow oop");
 595         if (value->is_EncodeP()) {
 596           value = value->in(1);
 597         } else {
 598           value = transform_later(new DecodeNNode(value, value->get_ptr_type()));
 599         }
 600       }
 601     }
 602     if (value != nullptr) {
 603       vt->set_field_value(i, value);
 604     } else {
 605       // We might have reached the TrackedInitializationLimit
 606       return nullptr;
 607     }
 608   }
 609   return vt;
 610 }
 611 
 612 // Check the possibility of scalar replacement.
 613 bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode *alloc, GrowableArray <SafePointNode *>* safepoints) {
 614   //  Scan the uses of the allocation to check for anything that would
 615   //  prevent us from eliminating it.
 616   NOT_PRODUCT( const char* fail_eliminate = nullptr; )
 617   DEBUG_ONLY( Node* disq_node = nullptr; )
 618   bool can_eliminate = true;
 619   bool reduce_merge_precheck = (safepoints == nullptr);
 620 
 621   Unique_Node_List worklist;
 622   Node* res = alloc->result_cast();
 623   const TypeOopPtr* res_type = nullptr;
 624   if (res == nullptr) {
 625     // All users were eliminated.
 626   } else if (!res->is_CheckCastPP()) {
 627     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 628     can_eliminate = false;
 629   } else {
 630     worklist.push(res);
 631     res_type = igvn->type(res)->isa_oopptr();
 632     if (res_type == nullptr) {
 633       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
 634       can_eliminate = false;
 635     } else if (!res_type->klass_is_exact()) {
 636       NOT_PRODUCT(fail_eliminate = "Not an exact type.";)
 637       can_eliminate = false;
 638     } else if (res_type->isa_aryptr()) {
 639       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 640       if (length < 0) {
 641         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 642         can_eliminate = false;
 643       }
 644     }
 645   }
 646 
 647   while (can_eliminate && worklist.size() > 0) {
 648     BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
 649     res = worklist.pop();
 650     for (DUIterator_Fast jmax, j = res->fast_outs(jmax); j < jmax && can_eliminate; j++) {
 651       Node* use = res->fast_out(j);
 652 
 653       if (use->is_AddP()) {
 654         const TypePtr* addp_type = igvn->type(use)->is_ptr();
 655         int offset = addp_type->offset();
 656 
 657         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 658           NOT_PRODUCT(fail_eliminate = "Undefined field reference";)
 659           can_eliminate = false;
 660           break;
 661         }
 662         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 663                                    k < kmax && can_eliminate; k++) {
 664           Node* n = use->fast_out(k);
 665           if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n) && !reduce_merge_precheck) {
 666             DEBUG_ONLY(disq_node = n;)
 667             if (n->is_Load() || n->is_LoadStore()) {
 668               NOT_PRODUCT(fail_eliminate = "Field load";)
 669             } else {
 670               NOT_PRODUCT(fail_eliminate = "Not store field reference";)

 676                  (use->as_ArrayCopy()->is_clonebasic() ||
 677                   use->as_ArrayCopy()->is_arraycopy_validated() ||
 678                   use->as_ArrayCopy()->is_copyof_validated() ||
 679                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
 680                  use->in(ArrayCopyNode::Dest) == res) {
 681         // ok to eliminate
 682       } else if (use->is_SafePoint()) {
 683         SafePointNode* sfpt = use->as_SafePoint();
 684         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 685           // Object is passed as argument.
 686           DEBUG_ONLY(disq_node = use;)
 687           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 688           can_eliminate = false;
 689         }
 690         Node* sfptMem = sfpt->memory();
 691         if (sfptMem == nullptr || sfptMem->is_top()) {
 692           DEBUG_ONLY(disq_node = use;)
 693           NOT_PRODUCT(fail_eliminate = "null or TOP memory";)
 694           can_eliminate = false;
 695         } else if (!reduce_merge_precheck) {
 696           assert(!res->is_Phi() || !res->as_Phi()->can_be_inline_type(), "Inline type allocations should not have safepoint uses");
 697           safepoints->append_if_missing(sfpt);
 698         }
 699       } else if (use->is_InlineType() && use->as_InlineType()->get_oop() == res) {
 700         // Look at uses
 701         for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) {
 702           Node* u = use->fast_out(k);
 703           if (u->is_InlineType()) {
 704             // Use in flat field can be eliminated
 705             InlineTypeNode* vt = u->as_InlineType();
 706             for (uint i = 0; i < vt->field_count(); ++i) {
 707               if (vt->field_value(i) == use && !vt->field_is_flat(i)) {
 708                 can_eliminate = false; // Use in non-flat field
 709                 break;
 710               }
 711             }
 712           } else {
 713             // Add other uses to the worklist to process individually
 714             worklist.push(use);
 715           }
 716         }
 717       } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
 718         // Store to mark word of inline type larval buffer
 719         assert(res_type->is_inlinetypeptr(), "Unexpected store to mark word");
 720       } else if (res_type->is_inlinetypeptr() && (use->Opcode() == Op_MemBarRelease || use->Opcode() == Op_MemBarStoreStore)) {
 721         // Inline type buffer allocations are followed by a membar
 722       } else if (reduce_merge_precheck &&
 723                  (use->is_Phi() || use->is_EncodeP() ||
 724                   use->Opcode() == Op_MemBarRelease ||
 725                   (UseStoreStoreForCtor && use->Opcode() == Op_MemBarStoreStore))) {
 726         // Nothing to do
 727       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 728         if (use->is_Phi()) {
 729           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 730             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 731           } else {
 732             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 733           }
 734           DEBUG_ONLY(disq_node = use;)
 735         } else {
 736           if (use->Opcode() == Op_Return) {
 737             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 738           } else {
 739             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 740           }
 741           DEBUG_ONLY(disq_node = use;)
 742         }
 743         can_eliminate = false;
 744       } else {
 745         assert(use->Opcode() == Op_CastP2X, "should be");
 746         assert(!use->has_out_with(Op_OrL), "should have been removed because oop is never null");
 747       }
 748     }
 749   }
 750 
 751 #ifndef PRODUCT
 752   if (PrintEliminateAllocations && safepoints != nullptr) {
 753     if (can_eliminate) {
 754       tty->print("Scalar ");
 755       if (res == nullptr)
 756         alloc->dump();
 757       else
 758         res->dump();
 759     } else {
 760       tty->print("NotScalar (%s)", fail_eliminate);
 761       if (res == nullptr)
 762         alloc->dump();
 763       else
 764         res->dump();
 765 #ifdef ASSERT
 766       if (disq_node != nullptr) {
 767           tty->print("  >>>> ");
 768           disq_node->dump();
 769       }
 770 #endif /*ASSERT*/
 771     }
 772   }
 773 
 774   if (TraceReduceAllocationMerges && !can_eliminate && reduce_merge_precheck) {
 775     tty->print_cr("\tCan't eliminate allocation because '%s': ", fail_eliminate != nullptr ? fail_eliminate : "");
 776     DEBUG_ONLY(if (disq_node != nullptr) disq_node->dump();)
 777   }
 778 #endif
 779   return can_eliminate;

 809     JVMState *jvms = sfpt_done->jvms();
 810     jvms->set_endoff(sfpt_done->req());
 811     // Now make a pass over the debug information replacing any references
 812     // to SafePointScalarObjectNode with the allocated object.
 813     int start = jvms->debug_start();
 814     int end   = jvms->debug_end();
 815     for (int i = start; i < end; i++) {
 816       if (sfpt_done->in(i)->is_SafePointScalarObject()) {
 817         SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
 818         if (scobj->first_index(jvms) == sfpt_done->req() &&
 819             scobj->n_fields() == (uint)nfields) {
 820           assert(scobj->alloc() == alloc, "sanity");
 821           sfpt_done->set_req(i, res);
 822         }
 823       }
 824     }
 825     _igvn._worklist.push(sfpt_done);
 826   }
 827 }
 828 
 829 SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_description(AllocateNode *alloc, SafePointNode* sfpt,
 830                                                                                   Unique_Node_List* value_worklist) {
 831   // Fields of scalar objs are referenced only at the end
 832   // of regular debuginfo at the last (youngest) JVMS.
 833   // Record relative start index.
 834   ciInstanceKlass* iklass    = nullptr;
 835   BasicType basic_elem_type  = T_ILLEGAL;
 836   const Type* field_type     = nullptr;
 837   const TypeOopPtr* res_type = nullptr;
 838   int nfields                = 0;
 839   int array_base             = 0;
 840   int element_size           = 0;
 841   uint first_ind             = (sfpt->req() - sfpt->jvms()->scloff());
 842   Node* res                  = alloc->result_cast();
 843 
 844   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
 845   assert(sfpt->jvms() != nullptr, "missed JVMS");
 846 
 847   if (res != nullptr) { // Could be null when there are no users
 848     res_type = _igvn.type(res)->isa_oopptr();
 849 
 850     if (res_type->isa_instptr()) {
 851       // find the fields of the class which will be needed for safepoint debug information
 852       iklass = res_type->is_instptr()->instance_klass();
 853       nfields = iklass->nof_nonstatic_fields();
 854     } else {
 855       // find the array's elements which will be needed for safepoint debug information
 856       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 857       assert(nfields >= 0, "must be an array klass.");
 858       basic_elem_type = res_type->is_aryptr()->elem()->array_element_basic_type();
 859       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 860       element_size = type2aelembytes(basic_elem_type);
 861       field_type = res_type->is_aryptr()->elem();
 862       if (res_type->is_flat()) {
 863         // Flat inline type array
 864         element_size = res_type->is_aryptr()->flat_elem_size();
 865       }
 866     }
 867 
 868     if (res->bottom_type()->is_inlinetypeptr()) {
 869       // Nullable inline types have an IsInit field which is added to the safepoint when scalarizing them (see
 870       // InlineTypeNode::make_scalar_in_safepoint()). When having circular inline types, we stop scalarizing at depth 1
 871       // to avoid an endless recursion. Therefore, we do not have a SafePointScalarObjectNode node here, yet.
 872       // We are about to create a SafePointScalarObjectNode as if this is a normal object. Add an additional int input
 873       // with value 1 which sets IsInit to true to indicate that the object is always non-null. This input is checked
 874       // later in PhaseOutput::filLocArray() for inline types.
 875       sfpt->add_req(_igvn.intcon(1));
 876     }
 877   }
 878 
 879   SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type, alloc, first_ind, sfpt->jvms()->depth(), nfields);
 880   sobj->init_req(0, C->root());
 881   transform_later(sobj);
 882 
 883   // Scan object's fields adding an input to the safepoint for each field.
 884   for (int j = 0; j < nfields; j++) {
 885     intptr_t offset;
 886     ciField* field = nullptr;
 887     if (iklass != nullptr) {
 888       field = iklass->nonstatic_field_at(j);
 889       offset = field->offset_in_bytes();
 890       ciType* elem_type = field->type();
 891       basic_elem_type = field->layout_type();
 892       assert(!field->is_flat(), "flat inline type fields should not have safepoint uses");
 893 
 894       // The next code is taken from Parse::do_get_xxx().
 895       if (is_reference_type(basic_elem_type)) {
 896         if (!elem_type->is_loaded()) {
 897           field_type = TypeInstPtr::BOTTOM;
 898         } else if (field != nullptr && field->is_static_constant()) {
 899           ciObject* con = field->constant_value().as_object();
 900           // Do not "join" in the previous type; it doesn't add value,
 901           // and may yield a vacuous result if the field is of interface type.
 902           field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 903           assert(field_type != nullptr, "field singleton type must be consistent");
 904         } else {
 905           field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 906         }
 907         if (UseCompressedOops) {
 908           field_type = field_type->make_narrowoop();
 909           basic_elem_type = T_NARROWOOP;
 910         }
 911       } else {
 912         field_type = Type::get_const_basic_type(basic_elem_type);
 913       }
 914     } else {
 915       offset = array_base + j * (intptr_t)element_size;
 916     }
 917 
 918     Node* field_val = nullptr;
 919     const TypeOopPtr* field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 920     if (res_type->is_flat()) {
 921       ciInlineKlass* inline_klass = res_type->is_aryptr()->elem()->inline_klass();
 922       assert(inline_klass->flat_in_array(), "must be flat in array");
 923       field_val = inline_type_from_mem(sfpt->memory(), sfpt->control(), inline_klass, field_addr_type->isa_aryptr(), 0, alloc);
 924     } else {
 925       field_val = value_from_mem(sfpt->memory(), sfpt->control(), basic_elem_type, field_type, field_addr_type, alloc);
 926     }
 927 
 928     // We weren't able to find a value for this field,
 929     // give up on eliminating this allocation.
 930     if (field_val == nullptr) {
 931       uint last = sfpt->req() - 1;
 932       for (int k = 0;  k < j; k++) {
 933         sfpt->del_req(last--);
 934       }
 935       _igvn._worklist.push(sfpt);
 936 
 937 #ifndef PRODUCT
 938       if (PrintEliminateAllocations) {
 939         if (field != nullptr) {
 940           tty->print("=== At SafePoint node %d can't find value of field: ", sfpt->_idx);
 941           field->print();
 942           int field_idx = C->get_alias_index(field_addr_type);
 943           tty->print(" (alias_idx=%d)", field_idx);
 944         } else { // Array's element
 945           tty->print("=== At SafePoint node %d can't find value of array element [%d]", sfpt->_idx, j);
 946         }
 947         tty->print(", which prevents elimination of: ");
 948         if (res == nullptr)
 949           alloc->dump();
 950         else
 951           res->dump();
 952       }
 953 #endif
 954 
 955       return nullptr;
 956     }
 957 
 958     if (UseCompressedOops && field_type->isa_narrowoop()) {
 959       // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 960       // to be able scalar replace the allocation.
 961       if (field_val->is_EncodeP()) {
 962         field_val = field_val->in(1);
 963       } else if (!field_val->is_InlineType()) {
 964         field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
 965       }
 966     }
 967 
 968     // Keep track of inline types to scalarize them later
 969     if (field_val->is_InlineType()) {
 970       value_worklist->push(field_val);
 971     } else if (field_val->is_Phi()) {
 972       PhiNode* phi = field_val->as_Phi();
 973       // Eagerly replace inline type phis now since we could be removing an inline type allocation where we must
 974       // scalarize all its fields in safepoints.
 975       field_val = phi->try_push_inline_types_down(&_igvn, true);
 976       if (field_val->is_InlineType()) {
 977         value_worklist->push(field_val);
 978       }
 979     }
 980     sfpt->add_req(field_val);
 981   }
 982 
 983   sfpt->jvms()->set_endoff(sfpt->req());
 984 
 985   return sobj;
 986 }
 987 
 988 // Do scalar replacement.
 989 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 990   GrowableArray <SafePointNode *> safepoints_done;
 991   Node* res = alloc->result_cast();
 992   assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
 993   const TypeOopPtr* res_type = nullptr;
 994   if (res != nullptr) { // Could be null when there are no users
 995     res_type = _igvn.type(res)->isa_oopptr();
 996   }
 997 
 998   // Process the safepoint uses
 999   assert(safepoints.length() == 0 || !res_type->is_inlinetypeptr() || C->has_circular_inline_type(),
1000          "Inline type allocations should have been scalarized earlier");
1001   Unique_Node_List value_worklist;
1002   while (safepoints.length() > 0) {
1003     SafePointNode* sfpt = safepoints.pop();
1004     SafePointScalarObjectNode* sobj = create_scalarized_object_description(alloc, sfpt, &value_worklist);
1005 
1006     if (sobj == nullptr) {
1007       undo_previous_scalarizations(safepoints_done, alloc);
1008       return false;
1009     }
1010 
1011     // Now make a pass over the debug information replacing any references
1012     // to the allocated object with "sobj"
1013     JVMState *jvms = sfpt->jvms();
1014     sfpt->replace_edges_in_range(res, sobj, jvms->debug_start(), jvms->debug_end(), &_igvn);
1015     _igvn._worklist.push(sfpt);
1016 
1017     // keep it for rollback
1018     safepoints_done.append_if_missing(sfpt);
1019   }
1020   // Scalarize inline types that were added to the safepoint.
1021   // Don't allow linking a constant oop (if available) for flat array elements
1022   // because Deoptimization::reassign_flat_array_elements needs field values.
1023   bool allow_oop = (res_type != nullptr) && !res_type->is_flat();
1024   for (uint i = 0; i < value_worklist.size(); ++i) {
1025     InlineTypeNode* vt = value_worklist.at(i)->as_InlineType();
1026     vt->make_scalar_in_safepoints(&_igvn, allow_oop);
1027   }
1028   return true;
1029 }
1030 
1031 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
1032   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
1033   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
1034   if (ctl_proj != nullptr) {
1035     igvn.replace_node(ctl_proj, n->in(0));
1036   }
1037   if (mem_proj != nullptr) {
1038     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
1039   }
1040 }
1041 
1042 // Process users of eliminated allocation.
1043 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc, bool inline_alloc) {
1044   Unique_Node_List worklist;
1045   Node* res = alloc->result_cast();
1046   if (res != nullptr) {
1047     worklist.push(res);
1048   }
1049   while (worklist.size() > 0) {
1050     res = worklist.pop();
1051     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
1052       Node *use = res->last_out(j);
1053       uint oc1 = res->outcnt();
1054 
1055       if (use->is_AddP()) {
1056         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
1057           Node *n = use->last_out(k);
1058           uint oc2 = use->outcnt();
1059           if (n->is_Store()) {
1060             for (DUIterator_Fast pmax, p = n->fast_outs(pmax); p < pmax; p++) {
1061               MemBarNode* mb = n->fast_out(p)->isa_MemBar();
1062               if (mb != nullptr && mb->req() <= MemBarNode::Precedent && mb->in(MemBarNode::Precedent) == n) {
1063                 // MemBarVolatiles should have been removed by MemBarNode::Ideal() for non-inline allocations
1064                 assert(inline_alloc, "MemBarVolatile should be eliminated for non-escaping object");
1065                 mb->remove(&_igvn);
1066               }



1067             }

1068             _igvn.replace_node(n, n->in(MemNode::Memory));
1069           } else {
1070             eliminate_gc_barrier(n);
1071           }
1072           k -= (oc2 - use->outcnt());
1073         }
1074         _igvn.remove_dead_node(use);
1075       } else if (use->is_ArrayCopy()) {
1076         // Disconnect ArrayCopy node
1077         ArrayCopyNode* ac = use->as_ArrayCopy();
1078         if (ac->is_clonebasic()) {
1079           Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
1080           disconnect_projections(ac, _igvn);
1081           assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
1082           Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
1083           disconnect_projections(membar_before->as_MemBar(), _igvn);
1084           if (membar_after->is_MemBar()) {
1085             disconnect_projections(membar_after->as_MemBar(), _igvn);
1086           }
1087         } else {
1088           assert(ac->is_arraycopy_validated() ||
1089                  ac->is_copyof_validated() ||
1090                  ac->is_copyofrange_validated(), "unsupported");
1091           CallProjections* callprojs = ac->extract_projections(true);

1092 
1093           _igvn.replace_node(callprojs->fallthrough_ioproj, ac->in(TypeFunc::I_O));
1094           _igvn.replace_node(callprojs->fallthrough_memproj, ac->in(TypeFunc::Memory));
1095           _igvn.replace_node(callprojs->fallthrough_catchproj, ac->in(TypeFunc::Control));
1096 
1097           // Set control to top. IGVN will remove the remaining projections
1098           ac->set_req(0, top());
1099           ac->replace_edge(res, top(), &_igvn);
1100 
1101           // Disconnect src right away: it can help find new
1102           // opportunities for allocation elimination
1103           Node* src = ac->in(ArrayCopyNode::Src);
1104           ac->replace_edge(src, top(), &_igvn);
1105           // src can be top at this point if src and dest of the
1106           // arraycopy were the same
1107           if (src->outcnt() == 0 && !src->is_top()) {
1108             _igvn.remove_dead_node(src);
1109           }
1110         }
1111         _igvn._worklist.push(ac);
1112       } else if (use->is_InlineType()) {
1113         assert(use->as_InlineType()->get_oop() == res, "unexpected inline type ptr use");
1114         // Cut off oop input and remove known instance id from type
1115         _igvn.rehash_node_delayed(use);
1116         use->as_InlineType()->set_oop(_igvn, _igvn.zerocon(T_OBJECT));
1117         const TypeOopPtr* toop = _igvn.type(use)->is_oopptr()->cast_to_instance_id(TypeOopPtr::InstanceBot);
1118         _igvn.set_type(use, toop);
1119         use->as_InlineType()->set_type(toop);
1120         // Process users
1121         for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) {
1122           Node* u = use->fast_out(k);
1123           if (!u->is_InlineType()) {
1124             worklist.push(u);
1125           }
1126         }
1127       } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
1128         // Store to mark word of inline type larval buffer
1129         assert(inline_alloc, "Unexpected store to mark word");
1130         _igvn.replace_node(use, use->in(MemNode::Memory));
1131       } else if (use->Opcode() == Op_MemBarRelease || use->Opcode() == Op_MemBarStoreStore) {
1132         // Inline type buffer allocations are followed by a membar
1133         assert(inline_alloc, "Unexpected MemBarRelease");
1134         use->as_MemBar()->remove(&_igvn);
1135       } else {
1136         eliminate_gc_barrier(use);
1137       }
1138       j -= (oc1 - res->outcnt());
1139     }
1140     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1141     _igvn.remove_dead_node(res);
1142   }
1143 
1144   //
1145   // Process other users of allocation's projections
1146   //
1147   if (_callprojs->resproj[0] != nullptr && _callprojs->resproj[0]->outcnt() != 0) {
1148     // First disconnect stores captured by Initialize node.
1149     // If Initialize node is eliminated first in the following code,
1150     // it will kill such stores and DUIterator_Last will assert.
1151     for (DUIterator_Fast jmax, j = _callprojs->resproj[0]->fast_outs(jmax);  j < jmax; j++) {
1152       Node* use = _callprojs->resproj[0]->fast_out(j);
1153       if (use->is_AddP()) {
1154         // raw memory addresses used only by the initialization
1155         _igvn.replace_node(use, C->top());
1156         --j; --jmax;
1157       }
1158     }
1159     for (DUIterator_Last jmin, j = _callprojs->resproj[0]->last_outs(jmin); j >= jmin; ) {
1160       Node* use = _callprojs->resproj[0]->last_out(j);
1161       uint oc1 = _callprojs->resproj[0]->outcnt();
1162       if (use->is_Initialize()) {
1163         // Eliminate Initialize node.
1164         InitializeNode *init = use->as_Initialize();
1165         assert(init->outcnt() <= 2, "only a control and memory projection expected");
1166         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1167         if (ctrl_proj != nullptr) {
1168           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1169 #ifdef ASSERT
1170           // If the InitializeNode has no memory out, it will die, and tmp will become null
1171           Node* tmp = init->in(TypeFunc::Control);
1172           assert(tmp == nullptr || tmp == _callprojs->fallthrough_catchproj, "allocation control projection");
1173 #endif
1174         }
1175         Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
1176         if (mem_proj != nullptr) {
1177           Node *mem = init->in(TypeFunc::Memory);
1178 #ifdef ASSERT
1179           if (mem->is_MergeMem()) {
1180             assert(mem->in(TypeFunc::Memory) == _callprojs->fallthrough_memproj, "allocation memory projection");
1181           } else {
1182             assert(mem == _callprojs->fallthrough_memproj, "allocation memory projection");
1183           }
1184 #endif
1185           _igvn.replace_node(mem_proj, mem);
1186         }
1187       } else if (use->Opcode() == Op_MemBarStoreStore) {
1188         // Inline type buffer allocations are followed by a membar
1189         assert(inline_alloc, "Unexpected MemBarStoreStore");
1190         use->as_MemBar()->remove(&_igvn);
1191       } else  {
1192         assert(false, "only Initialize or AddP expected");
1193       }
1194       j -= (oc1 - _callprojs->resproj[0]->outcnt());
1195     }
1196   }
1197   if (_callprojs->fallthrough_catchproj != nullptr) {
1198     _igvn.replace_node(_callprojs->fallthrough_catchproj, alloc->in(TypeFunc::Control));
1199   }
1200   if (_callprojs->fallthrough_memproj != nullptr) {
1201     _igvn.replace_node(_callprojs->fallthrough_memproj, alloc->in(TypeFunc::Memory));
1202   }
1203   if (_callprojs->catchall_memproj != nullptr) {
1204     _igvn.replace_node(_callprojs->catchall_memproj, C->top());
1205   }
1206   if (_callprojs->fallthrough_ioproj != nullptr) {
1207     _igvn.replace_node(_callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
1208   }
1209   if (_callprojs->catchall_ioproj != nullptr) {
1210     _igvn.replace_node(_callprojs->catchall_ioproj, C->top());
1211   }
1212   if (_callprojs->catchall_catchproj != nullptr) {
1213     _igvn.replace_node(_callprojs->catchall_catchproj, C->top());
1214   }
1215 }
1216 
1217 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1218   // If reallocation fails during deoptimization we'll pop all
1219   // interpreter frames for this compiled frame and that won't play
1220   // nice with JVMTI popframe.
1221   // We avoid this issue by eager reallocation when the popframe request
1222   // is received.
1223   if (!EliminateAllocations) {
1224     return false;
1225   }
1226   Node* klass = alloc->in(AllocateNode::KlassNode);
1227   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1228 
1229   // Attempt to eliminate inline type buffer allocations
1230   // regardless of usage and escape/replaceable status.
1231   bool inline_alloc = tklass->isa_instklassptr() &&
1232                       tklass->is_instklassptr()->instance_klass()->is_inlinetype();
1233   if (!alloc->_is_non_escaping && !inline_alloc) {
1234     return false;
1235   }
1236   // Eliminate boxing allocations which are not used
1237   // regardless scalar replaceable status.
1238   Node* res = alloc->result_cast();
1239   bool boxing_alloc = (res == nullptr) && C->eliminate_boxing() &&
1240                       tklass->isa_instklassptr() &&
1241                       tklass->is_instklassptr()->instance_klass()->is_box_klass();
1242   if (!alloc->_is_scalar_replaceable && !boxing_alloc && !inline_alloc) {
1243     return false;
1244   }
1245 
1246   _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1247 
1248   GrowableArray <SafePointNode *> safepoints;
1249   if (!can_eliminate_allocation(&_igvn, alloc, &safepoints)) {
1250     return false;
1251   }
1252 
1253   if (!alloc->_is_scalar_replaceable) {
1254     assert(res == nullptr || inline_alloc, "sanity");
1255     // We can only eliminate allocation if all debug info references
1256     // are already replaced with SafePointScalarObject because
1257     // we can't search for a fields value without instance_id.
1258     if (safepoints.length() > 0) {
1259       assert(!inline_alloc || C->has_circular_inline_type(),
1260              "Inline type allocations should have been scalarized earlier");
1261       return false;
1262     }
1263   }
1264 
1265   if (!scalar_replacement(alloc, safepoints)) {
1266     return false;
1267   }
1268 
1269   CompileLog* log = C->log();
1270   if (log != nullptr) {
1271     log->head("eliminate_allocation type='%d'",
1272               log->identify(tklass->exact_klass()));
1273     JVMState* p = alloc->jvms();
1274     while (p != nullptr) {
1275       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1276       p = p->caller();
1277     }
1278     log->tail("eliminate_allocation");
1279   }
1280 
1281   process_users_of_allocation(alloc, inline_alloc);
1282 
1283 #ifndef PRODUCT
1284   if (PrintEliminateAllocations) {
1285     if (alloc->is_AllocateArray())
1286       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1287     else
1288       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1289   }
1290 #endif
1291 
1292   return true;
1293 }
1294 
1295 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1296   // EA should remove all uses of non-escaping boxing node.
1297   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != nullptr) {
1298     return false;
1299   }
1300 
1301   assert(boxing->result_cast() == nullptr, "unexpected boxing node result");
1302 
1303   _callprojs = boxing->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1304 
1305   const TypeTuple* r = boxing->tf()->range_sig();
1306   assert(r->cnt() > TypeFunc::Parms, "sanity");
1307   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1308   assert(t != nullptr, "sanity");
1309 
1310   CompileLog* log = C->log();
1311   if (log != nullptr) {
1312     log->head("eliminate_boxing type='%d'",
1313               log->identify(t->instance_klass()));
1314     JVMState* p = boxing->jvms();
1315     while (p != nullptr) {
1316       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1317       p = p->caller();
1318     }
1319     log->tail("eliminate_boxing");
1320   }
1321 
1322   process_users_of_allocation(boxing);
1323 
1324 #ifndef PRODUCT
1325   if (PrintEliminateAllocations) {

1471 #endif
1472       yank_alloc_node(alloc);
1473       return;
1474     }
1475   }
1476 
1477   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1478   Node *slow_region = nullptr;
1479   Node *toobig_false = ctrl;
1480 
1481   // generate the initial test if necessary
1482   if (initial_slow_test != nullptr ) {
1483     assert (expand_fast_path, "Only need test if there is a fast path");
1484     slow_region = new RegionNode(3);
1485 
1486     // Now make the initial failure test.  Usually a too-big test but
1487     // might be a TRUE for finalizers.
1488     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1489     transform_later(toobig_iff);
1490     // Plug the failing-too-big test into the slow-path region
1491     Node* toobig_true = new IfTrueNode(toobig_iff);
1492     transform_later(toobig_true);
1493     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1494     toobig_false = new IfFalseNode(toobig_iff);
1495     transform_later(toobig_false);
1496   } else {
1497     // No initial test, just fall into next case
1498     assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1499     toobig_false = ctrl;
1500     debug_only(slow_region = NodeSentinel);
1501   }
1502 
1503   // If we are here there are several possibilities
1504   // - expand_fast_path is false - then only a slow path is expanded. That's it.
1505   // no_initial_check means a constant allocation.
1506   // - If check always evaluates to false -> expand_fast_path is false (see above)
1507   // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1508   // if !allocation_has_use the fast path is empty
1509   // if !allocation_has_use && no_initial_check
1510   // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1511   //   removed by yank_alloc_node above.
1512 
1513   Node *slow_mem = mem;  // save the current memory state for slow path
1514   // generate the fast allocation code unless we know that the initial test will always go slow
1515   if (expand_fast_path) {
1516     // Fast path modifies only raw memory.
1517     if (mem->is_MergeMem()) {
1518       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1519     }
1520 
1521     // allocate the Region and Phi nodes for the result
1522     result_region = new RegionNode(3);
1523     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1524     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1525 
1526     // Grab regular I/O before optional prefetch may change it.
1527     // Slow-path does no I/O so just set it to the original I/O.
1528     result_phi_i_o->init_req(slow_result_path, i_o);
1529 
1530     // Name successful fast-path variables
1531     Node* fast_oop_ctrl;
1532     Node* fast_oop_rawmem;
1533 
1534     if (allocation_has_use) {
1535       Node* needgc_ctrl = nullptr;
1536       result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1537 
1538       intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1539       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1540       Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1541                                         fast_oop_ctrl, fast_oop_rawmem,
1542                                         prefetch_lines);
1543 
1544       if (initial_slow_test != nullptr) {
1545         // This completes all paths into the slow merge point
1546         slow_region->init_req(need_gc_path, needgc_ctrl);
1547         transform_later(slow_region);
1548       } else {
1549         // No initial slow path needed!
1550         // Just fall from the need-GC path straight into the VM call.
1551         slow_region = needgc_ctrl;
1552       }
1553 

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

1852     Node* thread = new ThreadLocalNode();
1853     transform_later(thread);
1854 
1855     call->init_req(TypeFunc::Parms + 0, thread);
1856     call->init_req(TypeFunc::Parms + 1, oop);
1857     call->init_req(TypeFunc::Control, ctrl);
1858     call->init_req(TypeFunc::I_O    , top()); // does no i/o
1859     call->init_req(TypeFunc::Memory , rawmem);
1860     call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1861     call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1862     transform_later(call);
1863     ctrl = new ProjNode(call, TypeFunc::Control);
1864     transform_later(ctrl);
1865     rawmem = new ProjNode(call, TypeFunc::Memory);
1866     transform_later(rawmem);
1867   }
1868 }
1869 
1870 // Helper for PhaseMacroExpand::expand_allocate_common.
1871 // Initializes the newly-allocated storage.
1872 Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1873                                           Node* control, Node* rawmem, Node* object,
1874                                           Node* klass_node, Node* length,
1875                                           Node* size_in_bytes) {

1876   InitializeNode* init = alloc->initialization();
1877   // Store the klass & mark bits
1878   Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem);
1879   if (!mark_node->is_Con()) {
1880     transform_later(mark_node);
1881   }
1882   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1883 
1884   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1885   int header_size = alloc->minimum_header_size();  // conservatively small
1886 
1887   // Array length
1888   if (length != nullptr) {         // Arrays need length field
1889     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1890     // conservatively small header size:
1891     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1892     if (_igvn.type(klass_node)->isa_aryklassptr()) {   // we know the exact header size in most cases:
1893       BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
1894       if (is_reference_type(elem, true)) {
1895         elem = T_OBJECT;
1896       }
1897       header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
1898     }
1899   }
1900 
1901   // Clear the object body, if necessary.
1902   if (init == nullptr) {
1903     // The init has somehow disappeared; be cautious and clear everything.
1904     //
1905     // This can happen if a node is allocated but an uncommon trap occurs
1906     // immediately.  In this case, the Initialize gets associated with the
1907     // trap, and may be placed in a different (outer) loop, if the Allocate
1908     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1909     // there can be two Allocates to one Initialize.  The answer in all these
1910     // edge cases is safety first.  It is always safe to clear immediately
1911     // within an Allocate, and then (maybe or maybe not) clear some more later.
1912     if (!(UseTLAB && ZeroTLAB)) {
1913       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1914                                             alloc->in(AllocateNode::DefaultValue),
1915                                             alloc->in(AllocateNode::RawDefaultValue),
1916                                             header_size, size_in_bytes,
1917                                             &_igvn);
1918     }
1919   } else {
1920     if (!init->is_complete()) {
1921       // Try to win by zeroing only what the init does not store.
1922       // We can also try to do some peephole optimizations,
1923       // such as combining some adjacent subword stores.
1924       rawmem = init->complete_stores(control, rawmem, object,
1925                                      header_size, size_in_bytes, &_igvn);
1926     }
1927     // We have no more use for this link, since the AllocateNode goes away:
1928     init->set_req(InitializeNode::RawAddress, top());
1929     // (If we keep the link, it just confuses the register allocator,
1930     // who thinks he sees a real use of the address by the membar.)
1931   }
1932 
1933   return rawmem;
1934 }
1935 

2303 #ifdef ASSERT
2304   if (!alock->is_coarsened()) {
2305     // Check that new "eliminated" BoxLock node is created.
2306     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2307     assert(oldbox->is_eliminated(), "should be done already");
2308   }
2309 #endif
2310 
2311   alock->log_lock_optimization(C, "eliminate_lock");
2312 
2313 #ifndef PRODUCT
2314   if (PrintEliminateLocks) {
2315     tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2316   }
2317 #endif
2318 
2319   Node* mem  = alock->in(TypeFunc::Memory);
2320   Node* ctrl = alock->in(TypeFunc::Control);
2321   guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2322 
2323   _callprojs = alock->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2324   // There are 2 projections from the lock.  The lock node will
2325   // be deleted when its last use is subsumed below.
2326   assert(alock->outcnt() == 2 &&
2327          _callprojs->fallthrough_proj != nullptr &&
2328          _callprojs->fallthrough_memproj != nullptr,
2329          "Unexpected projections from Lock/Unlock");
2330 
2331   Node* fallthroughproj = _callprojs->fallthrough_proj;
2332   Node* memproj_fallthrough = _callprojs->fallthrough_memproj;
2333 
2334   // The memory projection from a lock/unlock is RawMem
2335   // The input to a Lock is merged memory, so extract its RawMem input
2336   // (unless the MergeMem has been optimized away.)
2337   if (alock->is_Lock()) {
2338     // Search for MemBarAcquireLock node and delete it also.
2339     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2340     assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2341     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2342     Node* memproj = membar->proj_out(TypeFunc::Memory);
2343     _igvn.replace_node(ctrlproj, fallthroughproj);
2344     _igvn.replace_node(memproj, memproj_fallthrough);
2345 
2346     // Delete FastLock node also if this Lock node is unique user
2347     // (a loop peeling may clone a Lock node).
2348     Node* flock = alock->as_Lock()->fastlock_node();
2349     if (flock->outcnt() == 1) {
2350       assert(flock->unique_out() == alock, "sanity");
2351       _igvn.replace_node(flock, top());
2352     }

2383   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2384 
2385   // Make the merge point
2386   Node *region;
2387   Node *mem_phi;
2388   Node *slow_path;
2389 
2390   region  = new RegionNode(3);
2391   // create a Phi for the memory state
2392   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2393 
2394   // Optimize test; set region slot 2
2395   slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2396   mem_phi->init_req(2, mem);
2397 
2398   // Make slow path call
2399   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2400                                   OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2401                                   obj, box, nullptr);
2402 
2403   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2404 
2405   // Slow path can only throw asynchronous exceptions, which are always
2406   // de-opted.  So the compiler thinks the slow-call can never throw an
2407   // exception.  If it DOES throw an exception we would need the debug
2408   // info removed first (since if it throws there is no monitor).
2409   assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr &&
2410          _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock");
2411 
2412   // Capture slow path
2413   // disconnect fall-through projection from call and create a new one
2414   // hook up users of fall-through projection to region
2415   Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2416   transform_later(slow_ctrl);
2417   _igvn.hash_delete(_callprojs->fallthrough_proj);
2418   _callprojs->fallthrough_proj->disconnect_inputs(C);
2419   region->init_req(1, slow_ctrl);
2420   // region inputs are now complete
2421   transform_later(region);
2422   _igvn.replace_node(_callprojs->fallthrough_proj, region);
2423 
2424   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2425 
2426   mem_phi->init_req(1, memproj);
2427 
2428   transform_later(mem_phi);
2429 
2430   _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2431 }
2432 
2433 //------------------------------expand_unlock_node----------------------
2434 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2435 
2436   Node* ctrl = unlock->in(TypeFunc::Control);
2437   Node* mem = unlock->in(TypeFunc::Memory);
2438   Node* obj = unlock->obj_node();
2439   Node* box = unlock->box_node();
2440 
2441   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2442 
2443   // No need for a null check on unlock
2444 
2445   // Make the merge point
2446   Node *region;
2447   Node *mem_phi;
2448 
2449   region  = new RegionNode(3);
2450   // create a Phi for the memory state
2451   mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2452 
2453   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2454   funlock = transform_later( funlock )->as_FastUnlock();
2455   // Optimize test; set region slot 2
2456   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2457   Node *thread = transform_later(new ThreadLocalNode());
2458 
2459   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2460                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2461                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2462 
2463   _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2464   assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr &&
2465          _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock");
2466 
2467   // No exceptions for unlocking
2468   // Capture slow path
2469   // disconnect fall-through projection from call and create a new one
2470   // hook up users of fall-through projection to region
2471   Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2472   transform_later(slow_ctrl);
2473   _igvn.hash_delete(_callprojs->fallthrough_proj);
2474   _callprojs->fallthrough_proj->disconnect_inputs(C);
2475   region->init_req(1, slow_ctrl);
2476   // region inputs are now complete
2477   transform_later(region);
2478   _igvn.replace_node(_callprojs->fallthrough_proj, region);
2479 
2480   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2481   mem_phi->init_req(1, memproj );
2482   mem_phi->init_req(2, mem);
2483   transform_later(mem_phi);
2484 
2485   _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2486 }
2487 
2488 // An inline type might be returned from the call but we don't know its
2489 // type. Either we get a buffered inline type (and nothing needs to be done)
2490 // or one of the values being returned is the klass of the inline type
2491 // and we need to allocate an inline type instance of that type and
2492 // initialize it with other values being returned. In that case, we
2493 // first try a fast path allocation and initialize the value with the
2494 // inline klass's pack handler or we fall back to a runtime call.
2495 void PhaseMacroExpand::expand_mh_intrinsic_return(CallStaticJavaNode* call) {
2496   assert(call->method()->is_method_handle_intrinsic(), "must be a method handle intrinsic call");
2497   Node* ret = call->proj_out_or_null(TypeFunc::Parms);
2498   if (ret == nullptr) {
2499     return;
2500   }
2501   const TypeFunc* tf = call->_tf;
2502   const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc();
2503   const TypeFunc* new_tf = TypeFunc::make(tf->domain_sig(), tf->domain_cc(), tf->range_sig(), domain);
2504   call->_tf = new_tf;
2505   // Make sure the change of type is applied before projections are processed by igvn
2506   _igvn.set_type(call, call->Value(&_igvn));
2507   _igvn.set_type(ret, ret->Value(&_igvn));
2508 
2509   // Before any new projection is added:
2510   CallProjections* projs = call->extract_projections(true, true);
2511 
2512   // Create temporary hook nodes that will be replaced below.
2513   // Add an input to prevent hook nodes from being dead.
2514   Node* ctl = new Node(call);
2515   Node* mem = new Node(ctl);
2516   Node* io = new Node(ctl);
2517   Node* ex_ctl = new Node(ctl);
2518   Node* ex_mem = new Node(ctl);
2519   Node* ex_io = new Node(ctl);
2520   Node* res = new Node(ctl);
2521 
2522   // Allocate a new buffered inline type only if a new one is not returned
2523   Node* cast = transform_later(new CastP2XNode(ctl, res));
2524   Node* mask = MakeConX(0x1);
2525   Node* masked = transform_later(new AndXNode(cast, mask));
2526   Node* cmp = transform_later(new CmpXNode(masked, mask));
2527   Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
2528   IfNode* allocation_iff = new IfNode(ctl, bol, PROB_MAX, COUNT_UNKNOWN);
2529   transform_later(allocation_iff);
2530   Node* allocation_ctl = transform_later(new IfTrueNode(allocation_iff));
2531   Node* no_allocation_ctl = transform_later(new IfFalseNode(allocation_iff));
2532   Node* no_allocation_res = transform_later(new CheckCastPPNode(no_allocation_ctl, res, TypeInstPtr::BOTTOM));
2533 
2534   // Try to allocate a new buffered inline instance either from TLAB or eden space
2535   Node* needgc_ctrl = nullptr; // needgc means slowcase, i.e. allocation failed
2536   CallLeafNoFPNode* handler_call;
2537   const bool alloc_in_place = UseTLAB;
2538   if (alloc_in_place) {
2539     Node* fast_oop_ctrl = nullptr;
2540     Node* fast_oop_rawmem = nullptr;
2541     Node* mask2 = MakeConX(-2);
2542     Node* masked2 = transform_later(new AndXNode(cast, mask2));
2543     Node* rawklassptr = transform_later(new CastX2PNode(masked2));
2544     Node* klass_node = transform_later(new CheckCastPPNode(allocation_ctl, rawklassptr, TypeInstKlassPtr::OBJECT_OR_NULL));
2545     Node* layout_val = make_load(nullptr, mem, klass_node, in_bytes(Klass::layout_helper_offset()), TypeInt::INT, T_INT);
2546     Node* size_in_bytes = ConvI2X(layout_val);
2547     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2548     Node* fast_oop = bs->obj_allocate(this, mem, allocation_ctl, size_in_bytes, io, needgc_ctrl,
2549                                       fast_oop_ctrl, fast_oop_rawmem,
2550                                       AllocateInstancePrefetchLines);
2551     // Allocation succeed, initialize buffered inline instance header firstly,
2552     // and then initialize its fields with an inline class specific handler
2553     Node* mark_node = makecon(TypeRawPtr::make((address)markWord::inline_type_prototype().value()));
2554     fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::mark_offset_in_bytes(), mark_node, T_ADDRESS);
2555     fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2556     if (UseCompressedClassPointers) {
2557       fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_gap_offset_in_bytes(), intcon(0), T_INT);
2558     }
2559     Node* fixed_block  = make_load(fast_oop_ctrl, fast_oop_rawmem, klass_node, in_bytes(InstanceKlass::adr_inlineklass_fixed_block_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2560     Node* pack_handler = make_load(fast_oop_ctrl, fast_oop_rawmem, fixed_block, in_bytes(InlineKlass::pack_handler_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2561     handler_call = new CallLeafNoFPNode(OptoRuntime::pack_inline_type_Type(),
2562                                         nullptr,
2563                                         "pack handler",
2564                                         TypeRawPtr::BOTTOM);
2565     handler_call->init_req(TypeFunc::Control, fast_oop_ctrl);
2566     handler_call->init_req(TypeFunc::Memory, fast_oop_rawmem);
2567     handler_call->init_req(TypeFunc::I_O, top());
2568     handler_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2569     handler_call->init_req(TypeFunc::ReturnAdr, top());
2570     handler_call->init_req(TypeFunc::Parms, pack_handler);
2571     handler_call->init_req(TypeFunc::Parms+1, fast_oop);
2572   } else {
2573     needgc_ctrl = allocation_ctl;
2574   }
2575 
2576   // Allocation failed, fall back to a runtime call
2577   CallStaticJavaNode* slow_call = new CallStaticJavaNode(OptoRuntime::store_inline_type_fields_Type(),
2578                                                          StubRoutines::store_inline_type_fields_to_buf(),
2579                                                          "store_inline_type_fields",
2580                                                          TypePtr::BOTTOM);
2581   slow_call->init_req(TypeFunc::Control, needgc_ctrl);
2582   slow_call->init_req(TypeFunc::Memory, mem);
2583   slow_call->init_req(TypeFunc::I_O, io);
2584   slow_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2585   slow_call->init_req(TypeFunc::ReturnAdr, call->in(TypeFunc::ReturnAdr));
2586   slow_call->init_req(TypeFunc::Parms, res);
2587 
2588   Node* slow_ctl = transform_later(new ProjNode(slow_call, TypeFunc::Control));
2589   Node* slow_mem = transform_later(new ProjNode(slow_call, TypeFunc::Memory));
2590   Node* slow_io = transform_later(new ProjNode(slow_call, TypeFunc::I_O));
2591   Node* slow_res = transform_later(new ProjNode(slow_call, TypeFunc::Parms));
2592   Node* slow_catc = transform_later(new CatchNode(slow_ctl, slow_io, 2));
2593   Node* slow_norm = transform_later(new CatchProjNode(slow_catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci));
2594   Node* slow_excp = transform_later(new CatchProjNode(slow_catc, CatchProjNode::catch_all_index,    CatchProjNode::no_handler_bci));
2595 
2596   Node* ex_r = new RegionNode(3);
2597   Node* ex_mem_phi = new PhiNode(ex_r, Type::MEMORY, TypePtr::BOTTOM);
2598   Node* ex_io_phi = new PhiNode(ex_r, Type::ABIO);
2599   ex_r->init_req(1, slow_excp);
2600   ex_mem_phi->init_req(1, slow_mem);
2601   ex_io_phi->init_req(1, slow_io);
2602   ex_r->init_req(2, ex_ctl);
2603   ex_mem_phi->init_req(2, ex_mem);
2604   ex_io_phi->init_req(2, ex_io);
2605   transform_later(ex_r);
2606   transform_later(ex_mem_phi);
2607   transform_later(ex_io_phi);
2608 
2609   // We don't know how many values are returned. This assumes the
2610   // worst case, that all available registers are used.
2611   for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2612     if (domain->field_at(i) == Type::HALF) {
2613       slow_call->init_req(i, top());
2614       if (alloc_in_place) {
2615         handler_call->init_req(i+1, top());
2616       }
2617       continue;
2618     }
2619     Node* proj = transform_later(new ProjNode(call, i));
2620     slow_call->init_req(i, proj);
2621     if (alloc_in_place) {
2622       handler_call->init_req(i+1, proj);
2623     }
2624   }
2625   // We can safepoint at that new call
2626   slow_call->copy_call_debug_info(&_igvn, call);
2627   transform_later(slow_call);
2628   if (alloc_in_place) {
2629     transform_later(handler_call);
2630   }
2631 
2632   Node* fast_ctl = nullptr;
2633   Node* fast_res = nullptr;
2634   MergeMemNode* fast_mem = nullptr;
2635   if (alloc_in_place) {
2636     fast_ctl = transform_later(new ProjNode(handler_call, TypeFunc::Control));
2637     Node* rawmem = transform_later(new ProjNode(handler_call, TypeFunc::Memory));
2638     fast_res = transform_later(new ProjNode(handler_call, TypeFunc::Parms));
2639     fast_mem = MergeMemNode::make(mem);
2640     fast_mem->set_memory_at(Compile::AliasIdxRaw, rawmem);
2641     transform_later(fast_mem);
2642   }
2643 
2644   Node* r = new RegionNode(alloc_in_place ? 4 : 3);
2645   Node* mem_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM);
2646   Node* io_phi = new PhiNode(r, Type::ABIO);
2647   Node* res_phi = new PhiNode(r, TypeInstPtr::BOTTOM);
2648   r->init_req(1, no_allocation_ctl);
2649   mem_phi->init_req(1, mem);
2650   io_phi->init_req(1, io);
2651   res_phi->init_req(1, no_allocation_res);
2652   r->init_req(2, slow_norm);
2653   mem_phi->init_req(2, slow_mem);
2654   io_phi->init_req(2, slow_io);
2655   res_phi->init_req(2, slow_res);
2656   if (alloc_in_place) {
2657     r->init_req(3, fast_ctl);
2658     mem_phi->init_req(3, fast_mem);
2659     io_phi->init_req(3, io);
2660     res_phi->init_req(3, fast_res);
2661   }
2662   transform_later(r);
2663   transform_later(mem_phi);
2664   transform_later(io_phi);
2665   transform_later(res_phi);
2666 
2667   // Do not let stores that initialize this buffer be reordered with a subsequent
2668   // store that would make this buffer accessible by other threads.
2669   MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
2670   transform_later(mb);
2671   mb->init_req(TypeFunc::Memory, mem_phi);
2672   mb->init_req(TypeFunc::Control, r);
2673   r = new ProjNode(mb, TypeFunc::Control);
2674   transform_later(r);
2675   mem_phi = new ProjNode(mb, TypeFunc::Memory);
2676   transform_later(mem_phi);
2677 
2678   assert(projs->nb_resproj == 1, "unexpected number of results");
2679   _igvn.replace_in_uses(projs->fallthrough_catchproj, r);
2680   _igvn.replace_in_uses(projs->fallthrough_memproj, mem_phi);
2681   _igvn.replace_in_uses(projs->fallthrough_ioproj, io_phi);
2682   _igvn.replace_in_uses(projs->resproj[0], res_phi);
2683   _igvn.replace_in_uses(projs->catchall_catchproj, ex_r);
2684   _igvn.replace_in_uses(projs->catchall_memproj, ex_mem_phi);
2685   _igvn.replace_in_uses(projs->catchall_ioproj, ex_io_phi);
2686   // The CatchNode should not use the ex_io_phi. Re-connect it to the catchall_ioproj.
2687   Node* cn = projs->fallthrough_catchproj->in(0);
2688   _igvn.replace_input_of(cn, 1, projs->catchall_ioproj);
2689 
2690   _igvn.replace_node(ctl, projs->fallthrough_catchproj);
2691   _igvn.replace_node(mem, projs->fallthrough_memproj);
2692   _igvn.replace_node(io, projs->fallthrough_ioproj);
2693   _igvn.replace_node(res, projs->resproj[0]);
2694   _igvn.replace_node(ex_ctl, projs->catchall_catchproj);
2695   _igvn.replace_node(ex_mem, projs->catchall_memproj);
2696   _igvn.replace_node(ex_io, projs->catchall_ioproj);
2697  }
2698 
2699 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2700   assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2701   Node* bol = check->unique_out();
2702   Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2703   Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2704   assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2705 
2706   for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2707     Node* iff = bol->last_out(i);
2708     assert(iff->is_If(), "where's the if?");
2709 
2710     if (iff->in(0)->is_top()) {
2711       _igvn.replace_input_of(iff, 1, C->top());
2712       continue;
2713     }
2714 
2715     Node* iftrue = iff->as_If()->proj_out(1);
2716     Node* iffalse = iff->as_If()->proj_out(0);
2717     Node* ctrl = iff->in(0);
2718 
2719     Node* subklass = nullptr;
2720     if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2721       subklass = obj_or_subklass;
2722     } else {
2723       Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2724       subklass = _igvn.transform(LoadKlassNode::make(_igvn, nullptr, C->immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
2725     }
2726 
2727     Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci());
2728 
2729     _igvn.replace_input_of(iff, 0, C->top());
2730     _igvn.replace_node(iftrue, not_subtype_ctrl);
2731     _igvn.replace_node(iffalse, ctrl);
2732   }
2733   _igvn.replace_node(check, C->top());
2734 }
2735 
2736 // FlatArrayCheckNode (array1 array2 ...) is expanded into:
2737 //
2738 // long mark = array1.mark | array2.mark | ...;
2739 // long locked_bit = markWord::unlocked_value & array1.mark & array2.mark & ...;
2740 // if (locked_bit == 0) {
2741 //   // One array is locked, load prototype header from the klass
2742 //   mark = array1.klass.proto | array2.klass.proto | ...
2743 // }
2744 // if ((mark & markWord::flat_array_bit_in_place) == 0) {
2745 //    ...
2746 // }
2747 void PhaseMacroExpand::expand_flatarraycheck_node(FlatArrayCheckNode* check) {
2748   bool array_inputs = _igvn.type(check->in(FlatArrayCheckNode::ArrayOrKlass))->isa_oopptr() != nullptr;
2749   if (array_inputs) {
2750     Node* mark = MakeConX(0);
2751     Node* locked_bit = MakeConX(markWord::unlocked_value);
2752     Node* mem = check->in(FlatArrayCheckNode::Memory);
2753     for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
2754       Node* ary = check->in(i);
2755       const TypeOopPtr* t = _igvn.type(ary)->isa_oopptr();
2756       assert(t != nullptr, "Mixing array and klass inputs");
2757       assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
2758       Node* mark_adr = basic_plus_adr(ary, oopDesc::mark_offset_in_bytes());
2759       Node* mark_load = _igvn.transform(LoadNode::make(_igvn, nullptr, mem, mark_adr, mark_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered));
2760       mark = _igvn.transform(new OrXNode(mark, mark_load));
2761       locked_bit = _igvn.transform(new AndXNode(locked_bit, mark_load));
2762     }
2763     assert(!mark->is_Con(), "Should have been optimized out");
2764     Node* cmp = _igvn.transform(new CmpXNode(locked_bit, MakeConX(0)));
2765     Node* is_unlocked = _igvn.transform(new BoolNode(cmp, BoolTest::ne));
2766 
2767     // BoolNode might be shared, replace each if user
2768     Node* old_bol = check->unique_out();
2769     assert(old_bol->is_Bool() && old_bol->as_Bool()->_test._test == BoolTest::ne, "unexpected condition");
2770     for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) {
2771       IfNode* old_iff = old_bol->last_out(i)->as_If();
2772       Node* ctrl = old_iff->in(0);
2773       RegionNode* region = new RegionNode(3);
2774       Node* mark_phi = new PhiNode(region, TypeX_X);
2775 
2776       // Check if array is unlocked
2777       IfNode* iff = _igvn.transform(new IfNode(ctrl, is_unlocked, PROB_MAX, COUNT_UNKNOWN))->as_If();
2778 
2779       // Unlocked: Use bits from mark word
2780       region->init_req(1, _igvn.transform(new IfTrueNode(iff)));
2781       mark_phi->init_req(1, mark);
2782 
2783       // Locked: Load prototype header from klass
2784       ctrl = _igvn.transform(new IfFalseNode(iff));
2785       Node* proto = MakeConX(0);
2786       for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
2787         Node* ary = check->in(i);
2788         // Make loads control dependent to make sure they are only executed if array is locked
2789         Node* klass_adr = basic_plus_adr(ary, oopDesc::klass_offset_in_bytes());
2790         Node* klass = _igvn.transform(LoadKlassNode::make(_igvn, ctrl, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
2791         Node* proto_adr = basic_plus_adr(klass, in_bytes(Klass::prototype_header_offset()));
2792         Node* proto_load = _igvn.transform(LoadNode::make(_igvn, ctrl, C->immutable_memory(), proto_adr, proto_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered));
2793         proto = _igvn.transform(new OrXNode(proto, proto_load));
2794       }
2795       region->init_req(2, ctrl);
2796       mark_phi->init_req(2, proto);
2797 
2798       // Check if flat array bits are set
2799       Node* mask = MakeConX(markWord::flat_array_bit_in_place);
2800       Node* masked = _igvn.transform(new AndXNode(_igvn.transform(mark_phi), mask));
2801       cmp = _igvn.transform(new CmpXNode(masked, MakeConX(0)));
2802       Node* is_not_flat = _igvn.transform(new BoolNode(cmp, BoolTest::eq));
2803 
2804       ctrl = _igvn.transform(region);
2805       iff = _igvn.transform(new IfNode(ctrl, is_not_flat, PROB_MAX, COUNT_UNKNOWN))->as_If();
2806       _igvn.replace_node(old_iff, iff);
2807     }
2808     _igvn.replace_node(check, C->top());
2809   } else {
2810     // Fall back to layout helper check
2811     Node* lhs = intcon(0);
2812     for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
2813       Node* array_or_klass = check->in(i);
2814       Node* klass = nullptr;
2815       const TypePtr* t = _igvn.type(array_or_klass)->is_ptr();
2816       assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
2817       if (t->isa_oopptr() != nullptr) {
2818         Node* klass_adr = basic_plus_adr(array_or_klass, oopDesc::klass_offset_in_bytes());
2819         klass = transform_later(LoadKlassNode::make(_igvn, nullptr, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
2820       } else {
2821         assert(t->isa_klassptr(), "Unexpected input type");
2822         klass = array_or_klass;
2823       }
2824       Node* lh_addr = basic_plus_adr(klass, in_bytes(Klass::layout_helper_offset()));
2825       Node* lh_val = _igvn.transform(LoadNode::make(_igvn, nullptr, C->immutable_memory(), lh_addr, lh_addr->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered));
2826       lhs = _igvn.transform(new OrINode(lhs, lh_val));
2827     }
2828     Node* masked = transform_later(new AndINode(lhs, intcon(Klass::_lh_array_tag_flat_value_bit_inplace)));
2829     Node* cmp = transform_later(new CmpINode(masked, intcon(0)));
2830     Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
2831     Node* m2b = transform_later(new Conv2BNode(masked));
2832     // The matcher expects the input to If nodes to be produced by a Bool(CmpI..)
2833     // pattern, but the input to other potential users (e.g. Phi) to be some
2834     // other pattern (e.g. a Conv2B node, possibly idealized as a CMoveI).
2835     Node* old_bol = check->unique_out();
2836     for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) {
2837       Node* user = old_bol->last_out(i);
2838       for (uint j = 0; j < user->req(); j++) {
2839         Node* n = user->in(j);
2840         if (n == old_bol) {
2841           _igvn.replace_input_of(user, j, user->is_If() ? bol : m2b);
2842         }
2843       }
2844     }
2845     _igvn.replace_node(check, C->top());
2846   }
2847 }
2848 
2849 //---------------------------eliminate_macro_nodes----------------------
2850 // Eliminate scalar replaced allocations and associated locks.
2851 void PhaseMacroExpand::eliminate_macro_nodes() {
2852   if (C->macro_count() == 0)
2853     return;
2854   NOT_PRODUCT(int membar_before = count_MemBar(C);)
2855 
2856   // Before elimination may re-mark (change to Nested or NonEscObj)
2857   // all associated (same box and obj) lock and unlock nodes.
2858   int cnt = C->macro_count();
2859   for (int i=0; i < cnt; i++) {
2860     Node *n = C->macro_node(i);
2861     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2862       mark_eliminated_locking_nodes(n->as_AbstractLock());
2863     }
2864   }
2865   // Re-marking may break consistency of Coarsened locks.
2866   if (!C->coarsened_locks_consistent()) {
2867     return; // recompile without Coarsened locks if broken
2868   } else {

2894   }
2895   // Next, attempt to eliminate allocations
2896   _has_locks = false;
2897   progress = true;
2898   while (progress) {
2899     progress = false;
2900     for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
2901       Node* n = C->macro_node(i - 1);
2902       bool success = false;
2903       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2904       switch (n->class_id()) {
2905       case Node::Class_Allocate:
2906       case Node::Class_AllocateArray:
2907         success = eliminate_allocate_node(n->as_Allocate());
2908 #ifndef PRODUCT
2909         if (success && PrintOptoStatistics) {
2910           Atomic::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
2911         }
2912 #endif
2913         break;
2914       case Node::Class_CallStaticJava: {
2915         CallStaticJavaNode* call = n->as_CallStaticJava();
2916         if (!call->method()->is_method_handle_intrinsic()) {
2917           success = eliminate_boxing_node(n->as_CallStaticJava());
2918         }
2919         break;
2920       }
2921       case Node::Class_Lock:
2922       case Node::Class_Unlock:
2923         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2924         _has_locks = true;
2925         break;
2926       case Node::Class_ArrayCopy:
2927         break;
2928       case Node::Class_OuterStripMinedLoop:
2929         break;
2930       case Node::Class_SubTypeCheck:
2931         break;
2932       case Node::Class_Opaque1:
2933         break;
2934       case Node::Class_FlatArrayCheck:
2935         break;
2936       default:
2937         assert(n->Opcode() == Op_LoopLimit ||
2938                n->is_OpaqueNotNull()       ||
2939                n->is_OpaqueInitializedAssertionPredicate() ||
2940                n->Opcode() == Op_MaxL      ||
2941                n->Opcode() == Op_MinL      ||
2942                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2943                "unknown node type in macro list");
2944       }
2945       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2946       progress = progress || success;
2947     }
2948   }
2949 #ifndef PRODUCT
2950   if (PrintOptoStatistics) {
2951     int membar_after = count_MemBar(C);
2952     Atomic::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
2953   }
2954 #endif
2955 }

2963     C->shuffle_macro_nodes();
2964   }
2965   // Last attempt to eliminate macro nodes.
2966   eliminate_macro_nodes();
2967   if (C->failing())  return true;
2968 
2969   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2970   bool progress = true;
2971   while (progress) {
2972     progress = false;
2973     for (int i = C->macro_count(); i > 0; i--) {
2974       Node* n = C->macro_node(i-1);
2975       bool success = false;
2976       DEBUG_ONLY(int old_macro_count = C->macro_count();)
2977       if (n->Opcode() == Op_LoopLimit) {
2978         // Remove it from macro list and put on IGVN worklist to optimize.
2979         C->remove_macro_node(n);
2980         _igvn._worklist.push(n);
2981         success = true;
2982       } else if (n->Opcode() == Op_CallStaticJava) {
2983         CallStaticJavaNode* call = n->as_CallStaticJava();
2984         if (!call->method()->is_method_handle_intrinsic()) {
2985           // Remove it from macro list and put on IGVN worklist to optimize.
2986           C->remove_macro_node(n);
2987           _igvn._worklist.push(n);
2988           success = true;
2989         }
2990       } else if (n->is_Opaque1()) {
2991         _igvn.replace_node(n, n->in(1));
2992         success = true;
2993       } else if (n->is_OpaqueNotNull()) {
2994         // Tests with OpaqueNotNull nodes are implicitly known to be true. Replace the node with true. In debug builds,
2995         // we leave the test in the graph to have an additional sanity check at runtime. If the test fails (i.e. a bug),
2996         // we will execute a Halt node.
2997 #ifdef ASSERT
2998         _igvn.replace_node(n, n->in(1));
2999 #else
3000         _igvn.replace_node(n, _igvn.intcon(1));
3001 #endif
3002         success = true;
3003       } else if (n->is_OpaqueInitializedAssertionPredicate()) {
3004           // Initialized Assertion Predicates must always evaluate to true. Therefore, we get rid of them in product
3005           // builds as they are useless. In debug builds we keep them as additional verification code. Even though
3006           // loop opts are already over, we want to keep Initialized Assertion Predicates alive as long as possible to
3007           // enable folding of dead control paths within which cast nodes become top after due to impossible types -
3008           // even after loop opts are over. Therefore, we delay the removal of these opaque nodes until now.
3009 #ifdef ASSERT

3071     // Worst case is a macro node gets expanded into about 200 nodes.
3072     // Allow 50% more for optimization.
3073     if (C->check_node_count(300, "out of nodes before macro expansion")) {
3074       return true;
3075     }
3076 
3077     DEBUG_ONLY(int old_macro_count = C->macro_count();)
3078     switch (n->class_id()) {
3079     case Node::Class_Lock:
3080       expand_lock_node(n->as_Lock());
3081       break;
3082     case Node::Class_Unlock:
3083       expand_unlock_node(n->as_Unlock());
3084       break;
3085     case Node::Class_ArrayCopy:
3086       expand_arraycopy_node(n->as_ArrayCopy());
3087       break;
3088     case Node::Class_SubTypeCheck:
3089       expand_subtypecheck_node(n->as_SubTypeCheck());
3090       break;
3091     case Node::Class_CallStaticJava:
3092       expand_mh_intrinsic_return(n->as_CallStaticJava());
3093       C->remove_macro_node(n);
3094       break;
3095     case Node::Class_FlatArrayCheck:
3096       expand_flatarraycheck_node(n->as_FlatArrayCheck());
3097       break;
3098     default:
3099       assert(false, "unknown node type in macro list");
3100     }
3101     assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3102     if (C->failing())  return true;
3103     C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
3104 
3105     // Clean up the graph so we're less likely to hit the maximum node
3106     // limit
3107     _igvn.set_delay_transform(false);
3108     _igvn.optimize();
3109     if (C->failing())  return true;
3110     _igvn.set_delay_transform(true);
3111   }
3112 
3113   // All nodes except Allocate nodes are expanded now. There could be
3114   // new optimization opportunities (such as folding newly created
3115   // load from a just allocated object). Run IGVN.
3116 
3117   // expand "macro" nodes
< prev index next >