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