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