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