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