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