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