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