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