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