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