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