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