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