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