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