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