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