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