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