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