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