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