1 /*
   2  * Copyright 2005-2008 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 #include "incls/_precompiled.incl"
  26 #include "incls/_macro.cpp.incl"
  27 
  28 
  29 //
  30 // Replace any references to "oldref" in inputs to "use" with "newref".
  31 // Returns the number of replacements made.
  32 //
  33 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
  34   int nreplacements = 0;
  35   uint req = use->req();
  36   for (uint j = 0; j < use->len(); j++) {
  37     Node *uin = use->in(j);
  38     if (uin == oldref) {
  39       if (j < req)
  40         use->set_req(j, newref);
  41       else
  42         use->set_prec(j, newref);
  43       nreplacements++;
  44     } else if (j >= req && uin == NULL) {
  45       break;
  46     }
  47   }
  48   return nreplacements;
  49 }
  50 
  51 void PhaseMacroExpand::copy_call_debug_info(CallNode *oldcall, CallNode * newcall) {
  52   // Copy debug information and adjust JVMState information
  53   uint old_dbg_start = oldcall->tf()->domain()->cnt();
  54   uint new_dbg_start = newcall->tf()->domain()->cnt();
  55   int jvms_adj  = new_dbg_start - old_dbg_start;
  56   assert (new_dbg_start == newcall->req(), "argument count mismatch");
  57 
  58   Dict* sosn_map = new Dict(cmpkey,hashkey);
  59   for (uint i = old_dbg_start; i < oldcall->req(); i++) {
  60     Node* old_in = oldcall->in(i);
  61     // Clone old SafePointScalarObjectNodes, adjusting their field contents.
  62     if (old_in != NULL && old_in->is_SafePointScalarObject()) {
  63       SafePointScalarObjectNode* old_sosn = old_in->as_SafePointScalarObject();
  64       uint old_unique = C->unique();
  65       Node* new_in = old_sosn->clone(jvms_adj, sosn_map);
  66       if (old_unique != C->unique()) {
  67         new_in = transform_later(new_in); // Register new node.
  68       }
  69       old_in = new_in;
  70     }
  71     newcall->add_req(old_in);
  72   }
  73 
  74   newcall->set_jvms(oldcall->jvms());
  75   for (JVMState *jvms = newcall->jvms(); jvms != NULL; jvms = jvms->caller()) {
  76     jvms->set_map(newcall);
  77     jvms->set_locoff(jvms->locoff()+jvms_adj);
  78     jvms->set_stkoff(jvms->stkoff()+jvms_adj);
  79     jvms->set_monoff(jvms->monoff()+jvms_adj);
  80     jvms->set_scloff(jvms->scloff()+jvms_adj);
  81     jvms->set_endoff(jvms->endoff()+jvms_adj);
  82   }
  83 }
  84 
  85 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word, int mask, int bits, bool return_fast_path) {
  86   Node* cmp;
  87   if (mask != 0) {
  88     Node* and_node = transform_later(new (C, 3) AndXNode(word, MakeConX(mask)));
  89     cmp = transform_later(new (C, 3) CmpXNode(and_node, MakeConX(bits)));
  90   } else {
  91     cmp = word;
  92   }
  93   Node* bol = transform_later(new (C, 2) BoolNode(cmp, BoolTest::ne));
  94   IfNode* iff = new (C, 2) IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
  95   transform_later(iff);
  96 
  97   // Fast path taken.
  98   Node *fast_taken = transform_later( new (C, 1) IfFalseNode(iff) );
  99 
 100   // Fast path not-taken, i.e. slow path
 101   Node *slow_taken = transform_later( new (C, 1) IfTrueNode(iff) );
 102 
 103   if (return_fast_path) {
 104     region->init_req(edge, slow_taken); // Capture slow-control
 105     return fast_taken;
 106   } else {
 107     region->init_req(edge, fast_taken); // Capture fast-control
 108     return slow_taken;
 109   }
 110 }
 111 
 112 //--------------------copy_predefined_input_for_runtime_call--------------------
 113 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
 114   // Set fixed predefined input arguments
 115   call->init_req( TypeFunc::Control, ctrl );
 116   call->init_req( TypeFunc::I_O    , oldcall->in( TypeFunc::I_O) );
 117   call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ?????
 118   call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) );
 119   call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) );
 120 }
 121 
 122 //------------------------------make_slow_call---------------------------------
 123 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type, address slow_call, const char* leaf_name, Node* slow_path, Node* parm0, Node* parm1) {
 124 
 125   // Slow-path call
 126   int size = slow_call_type->domain()->cnt();
 127  CallNode *call = leaf_name
 128    ? (CallNode*)new (C, size) CallLeafNode      ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
 129    : (CallNode*)new (C, size) CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), oldcall->jvms()->bci(), TypeRawPtr::BOTTOM );
 130 
 131   // Slow path call has no side-effects, uses few values
 132   copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
 133   if (parm0 != NULL)  call->init_req(TypeFunc::Parms+0, parm0);
 134   if (parm1 != NULL)  call->init_req(TypeFunc::Parms+1, parm1);
 135   copy_call_debug_info(oldcall, call);
 136   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
 137   _igvn.hash_delete(oldcall);
 138   _igvn.subsume_node(oldcall, call);
 139   transform_later(call);
 140 
 141   return call;
 142 }
 143 
 144 void PhaseMacroExpand::extract_call_projections(CallNode *call) {
 145   _fallthroughproj = NULL;
 146   _fallthroughcatchproj = NULL;
 147   _ioproj_fallthrough = NULL;
 148   _ioproj_catchall = NULL;
 149   _catchallcatchproj = NULL;
 150   _memproj_fallthrough = NULL;
 151   _memproj_catchall = NULL;
 152   _resproj = NULL;
 153   for (DUIterator_Fast imax, i = call->fast_outs(imax); i < imax; i++) {
 154     ProjNode *pn = call->fast_out(i)->as_Proj();
 155     switch (pn->_con) {
 156       case TypeFunc::Control:
 157       {
 158         // For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
 159         _fallthroughproj = pn;
 160         DUIterator_Fast jmax, j = pn->fast_outs(jmax);
 161         const Node *cn = pn->fast_out(j);
 162         if (cn->is_Catch()) {
 163           ProjNode *cpn = NULL;
 164           for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
 165             cpn = cn->fast_out(k)->as_Proj();
 166             assert(cpn->is_CatchProj(), "must be a CatchProjNode");
 167             if (cpn->_con == CatchProjNode::fall_through_index)
 168               _fallthroughcatchproj = cpn;
 169             else {
 170               assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
 171               _catchallcatchproj = cpn;
 172             }
 173           }
 174         }
 175         break;
 176       }
 177       case TypeFunc::I_O:
 178         if (pn->_is_io_use)
 179           _ioproj_catchall = pn;
 180         else
 181           _ioproj_fallthrough = pn;
 182         break;
 183       case TypeFunc::Memory:
 184         if (pn->_is_io_use)
 185           _memproj_catchall = pn;
 186         else
 187           _memproj_fallthrough = pn;
 188         break;
 189       case TypeFunc::Parms:
 190         _resproj = pn;
 191         break;
 192       default:
 193         assert(false, "unexpected projection from allocation node.");
 194     }
 195   }
 196 
 197 }
 198 
 199 // Eliminate a card mark sequence.  p2x is a ConvP2XNode
 200 void PhaseMacroExpand::eliminate_card_mark(Node *p2x) {
 201   assert(p2x->Opcode() == Op_CastP2X, "ConvP2XNode required");
 202   Node *shift = p2x->unique_out();
 203   Node *addp = shift->unique_out();
 204   for (DUIterator_Last jmin, j = addp->last_outs(jmin); j >= jmin; --j) {
 205     Node *st = addp->last_out(j);
 206     assert(st->is_Store(), "store required");
 207     _igvn.replace_node(st, st->in(MemNode::Memory));
 208   }
 209 }
 210 
 211 // Search for a memory operation for the specified memory slice.
 212 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
 213   Node *orig_mem = mem;
 214   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 215   const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
 216   while (true) {
 217     if (mem == alloc_mem || mem == start_mem ) {
 218       return mem;  // hit one of our sentinals
 219     } else if (mem->is_MergeMem()) {
 220       mem = mem->as_MergeMem()->memory_at(alias_idx);
 221     } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
 222       Node *in = mem->in(0);
 223       // we can safely skip over safepoints, calls, locks and membars because we
 224       // already know that the object is safe to eliminate.
 225       if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
 226         return in;
 227       } else if (in->is_Call()) {
 228         CallNode *call = in->as_Call();
 229         if (!call->may_modify(tinst, phase)) {
 230           mem = call->in(TypeFunc::Memory);
 231         }
 232         mem = in->in(TypeFunc::Memory);
 233       } else if (in->is_MemBar()) {
 234         mem = in->in(TypeFunc::Memory);
 235       } else {
 236         assert(false, "unexpected projection");
 237       }
 238     } else if (mem->is_Store()) {
 239       const TypePtr* atype = mem->as_Store()->adr_type();
 240       int adr_idx = Compile::current()->get_alias_index(atype);
 241       if (adr_idx == alias_idx) {
 242         assert(atype->isa_oopptr(), "address type must be oopptr");
 243         int adr_offset = atype->offset();
 244         uint adr_iid = atype->is_oopptr()->instance_id();
 245         // Array elements references have the same alias_idx
 246         // but different offset and different instance_id.
 247         if (adr_offset == offset && adr_iid == alloc->_idx)
 248           return mem;
 249       } else {
 250         assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
 251       }
 252       mem = mem->in(MemNode::Memory);
 253     } else {
 254       return mem;
 255     }
 256     assert(mem != orig_mem, "dead memory loop");
 257   }
 258 }
 259 
 260 //
 261 // Given a Memory Phi, compute a value Phi containing the values from stores
 262 // on the input paths.
 263 // Note: this function is recursive, its depth is limied by the "level" argument
 264 // Returns the computed Phi, or NULL if it cannot compute it.
 265 Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, Node *alloc, Node_Stack *value_phis, int level) {
 266   assert(mem->is_Phi(), "sanity");
 267   int alias_idx = C->get_alias_index(adr_t);
 268   int offset = adr_t->offset();
 269   int instance_id = adr_t->instance_id();
 270 
 271   // Check if an appropriate value phi already exists.
 272   Node* region = mem->in(0);
 273   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
 274     Node* phi = region->fast_out(k);
 275     if (phi->is_Phi() && phi != mem &&
 276         phi->as_Phi()->is_same_inst_field(phi_type, instance_id, alias_idx, offset)) {
 277       return phi;
 278     }
 279   }
 280   // Check if an appropriate new value phi already exists.
 281   Node* new_phi = NULL;
 282   uint size = value_phis->size();
 283   for (uint i=0; i < size; i++) {
 284     if ( mem->_idx == value_phis->index_at(i) ) {
 285       return value_phis->node_at(i);
 286     }
 287   }
 288 
 289   if (level <= 0) {
 290     return NULL; // Give up: phi tree too deep
 291   }
 292   Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
 293   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 294 
 295   uint length = mem->req();
 296   GrowableArray <Node *> values(length, length, NULL);
 297 
 298   // create a new Phi for the value
 299   PhiNode *phi = new (C, length) PhiNode(mem->in(0), phi_type, NULL, instance_id, alias_idx, offset);
 300   transform_later(phi);
 301   value_phis->push(phi, mem->_idx);
 302 
 303   for (uint j = 1; j < length; j++) {
 304     Node *in = mem->in(j);
 305     if (in == NULL || in->is_top()) {
 306       values.at_put(j, in);
 307     } else  {
 308       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
 309       if (val == start_mem || val == alloc_mem) {
 310         // hit a sentinel, return appropriate 0 value
 311         values.at_put(j, _igvn.zerocon(ft));
 312         continue;
 313       }
 314       if (val->is_Initialize()) {
 315         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 316       }
 317       if (val == NULL) {
 318         return NULL;  // can't find a value on this path
 319       }
 320       if (val == mem) {
 321         values.at_put(j, mem);
 322       } else if (val->is_Store()) {
 323         values.at_put(j, val->in(MemNode::ValueIn));
 324       } else if(val->is_Proj() && val->in(0) == alloc) {
 325         values.at_put(j, _igvn.zerocon(ft));
 326       } else if (val->is_Phi()) {
 327         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
 328         if (val == NULL) {
 329           return NULL;
 330         }
 331         values.at_put(j, val);
 332       } else {
 333         assert(false, "unknown node on this path");
 334         return NULL;  // unknown node on this path
 335       }
 336     }
 337   }
 338   // Set Phi's inputs
 339   for (uint j = 1; j < length; j++) {
 340     if (values.at(j) == mem) {
 341       phi->init_req(j, phi);
 342     } else {
 343       phi->init_req(j, values.at(j));
 344     }
 345   }
 346   return phi;
 347 }
 348 
 349 // Search the last value stored into the object's field.
 350 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, Node *alloc) {
 351   assert(adr_t->is_known_instance_field(), "instance required");
 352   int instance_id = adr_t->instance_id();
 353   assert((uint)instance_id == alloc->_idx, "wrong allocation");
 354 
 355   int alias_idx = C->get_alias_index(adr_t);
 356   int offset = adr_t->offset();
 357   Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
 358   Node *alloc_ctrl = alloc->in(TypeFunc::Control);
 359   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 360   Arena *a = Thread::current()->resource_area();
 361   VectorSet visited(a);
 362 
 363 
 364   bool done = sfpt_mem == alloc_mem;
 365   Node *mem = sfpt_mem;
 366   while (!done) {
 367     if (visited.test_set(mem->_idx)) {
 368       return NULL;  // found a loop, give up
 369     }
 370     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
 371     if (mem == start_mem || mem == alloc_mem) {
 372       done = true;  // hit a sentinel, return appropriate 0 value
 373     } else if (mem->is_Initialize()) {
 374       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
 375       if (mem == NULL) {
 376         done = true; // Something go wrong.
 377       } else if (mem->is_Store()) {
 378         const TypePtr* atype = mem->as_Store()->adr_type();
 379         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
 380         done = true;
 381       }
 382     } else if (mem->is_Store()) {
 383       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
 384       assert(atype != NULL, "address type must be oopptr");
 385       assert(C->get_alias_index(atype) == alias_idx &&
 386              atype->is_known_instance_field() && atype->offset() == offset &&
 387              atype->instance_id() == instance_id, "store is correct memory slice");
 388       done = true;
 389     } else if (mem->is_Phi()) {
 390       // try to find a phi's unique input
 391       Node *unique_input = NULL;
 392       Node *top = C->top();
 393       for (uint i = 1; i < mem->req(); i++) {
 394         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
 395         if (n == NULL || n == top || n == mem) {
 396           continue;
 397         } else if (unique_input == NULL) {
 398           unique_input = n;
 399         } else if (unique_input != n) {
 400           unique_input = top;
 401           break;
 402         }
 403       }
 404       if (unique_input != NULL && unique_input != top) {
 405         mem = unique_input;
 406       } else {
 407         done = true;
 408       }
 409     } else {
 410       assert(false, "unexpected node");
 411     }
 412   }
 413   if (mem != NULL) {
 414     if (mem == start_mem || mem == alloc_mem) {
 415       // hit a sentinel, return appropriate 0 value
 416       return _igvn.zerocon(ft);
 417     } else if (mem->is_Store()) {
 418       return mem->in(MemNode::ValueIn);
 419     } else if (mem->is_Phi()) {
 420       // attempt to produce a Phi reflecting the values on the input paths of the Phi
 421       Node_Stack value_phis(a, 8);
 422       Node * phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
 423       if (phi != NULL) {
 424         return phi;
 425       } else {
 426         // Kill all new Phis
 427         while(value_phis.is_nonempty()) {
 428           Node* n = value_phis.node();
 429           _igvn.hash_delete(n);
 430           _igvn.subsume_node(n, C->top());
 431           value_phis.pop();
 432         }
 433       }
 434     }
 435   }
 436   // Something go wrong.
 437   return NULL;
 438 }
 439 
 440 // Check the possibility of scalar replacement.
 441 bool PhaseMacroExpand::can_eliminate_allocation(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 442   //  Scan the uses of the allocation to check for anything that would
 443   //  prevent us from eliminating it.
 444   NOT_PRODUCT( const char* fail_eliminate = NULL; )
 445   DEBUG_ONLY( Node* disq_node = NULL; )
 446   bool  can_eliminate = true;
 447 
 448   Node* res = alloc->result_cast();
 449   const TypeOopPtr* res_type = NULL;
 450   if (res == NULL) {
 451     // All users were eliminated.
 452   } else if (!res->is_CheckCastPP()) {
 453     alloc->_is_scalar_replaceable = false;  // don't try again
 454     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
 455     can_eliminate = false;
 456   } else {
 457     res_type = _igvn.type(res)->isa_oopptr();
 458     if (res_type == NULL) {
 459       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
 460       can_eliminate = false;
 461     } else if (res_type->isa_aryptr()) {
 462       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 463       if (length < 0) {
 464         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
 465         can_eliminate = false;
 466       }
 467     }
 468   }
 469 
 470   if (can_eliminate && res != NULL) {
 471     for (DUIterator_Fast jmax, j = res->fast_outs(jmax);
 472                                j < jmax && can_eliminate; j++) {
 473       Node* use = res->fast_out(j);
 474 
 475       if (use->is_AddP()) {
 476         const TypePtr* addp_type = _igvn.type(use)->is_ptr();
 477         int offset = addp_type->offset();
 478 
 479         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
 480           NOT_PRODUCT(fail_eliminate = "Undefined field referrence";)
 481           can_eliminate = false;
 482           break;
 483         }
 484         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
 485                                    k < kmax && can_eliminate; k++) {
 486           Node* n = use->fast_out(k);
 487           if (!n->is_Store() && n->Opcode() != Op_CastP2X) {
 488             DEBUG_ONLY(disq_node = n;)
 489             if (n->is_Load() || n->is_LoadStore()) {
 490               NOT_PRODUCT(fail_eliminate = "Field load";)
 491             } else {
 492               NOT_PRODUCT(fail_eliminate = "Not store field referrence";)
 493             }
 494             can_eliminate = false;
 495           }
 496         }
 497       } else if (use->is_SafePoint()) {
 498         SafePointNode* sfpt = use->as_SafePoint();
 499         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
 500           // Object is passed as argument.
 501           DEBUG_ONLY(disq_node = use;)
 502           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
 503           can_eliminate = false;
 504         }
 505         Node* sfptMem = sfpt->memory();
 506         if (sfptMem == NULL || sfptMem->is_top()) {
 507           DEBUG_ONLY(disq_node = use;)
 508           NOT_PRODUCT(fail_eliminate = "NULL or TOP memory";)
 509           can_eliminate = false;
 510         } else {
 511           safepoints.append_if_missing(sfpt);
 512         }
 513       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
 514         if (use->is_Phi()) {
 515           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
 516             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 517           } else {
 518             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
 519           }
 520           DEBUG_ONLY(disq_node = use;)
 521         } else {
 522           if (use->Opcode() == Op_Return) {
 523             NOT_PRODUCT(fail_eliminate = "Object is return value";)
 524           }else {
 525             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
 526           }
 527           DEBUG_ONLY(disq_node = use;)
 528         }
 529         can_eliminate = false;
 530       }
 531     }
 532   }
 533 
 534 #ifndef PRODUCT
 535   if (PrintEliminateAllocations) {
 536     if (can_eliminate) {
 537       tty->print("Scalar ");
 538       if (res == NULL)
 539         alloc->dump();
 540       else
 541         res->dump();
 542     } else {
 543       tty->print("NotScalar (%s)", fail_eliminate);
 544       if (res == NULL)
 545         alloc->dump();
 546       else
 547         res->dump();
 548 #ifdef ASSERT
 549       if (disq_node != NULL) {
 550           tty->print("  >>>> ");
 551           disq_node->dump();
 552       }
 553 #endif /*ASSERT*/
 554     }
 555   }
 556 #endif
 557   return can_eliminate;
 558 }
 559 
 560 // Do scalar replacement.
 561 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
 562   GrowableArray <SafePointNode *> safepoints_done;
 563 
 564   ciKlass* klass = NULL;
 565   ciInstanceKlass* iklass = NULL;
 566   int nfields = 0;
 567   int array_base;
 568   int element_size;
 569   BasicType basic_elem_type;
 570   ciType* elem_type;
 571 
 572   Node* res = alloc->result_cast();
 573   const TypeOopPtr* res_type = NULL;
 574   if (res != NULL) { // Could be NULL when there are no users
 575     res_type = _igvn.type(res)->isa_oopptr();
 576   }
 577 
 578   if (res != NULL) {
 579     klass = res_type->klass();
 580     if (res_type->isa_instptr()) {
 581       // find the fields of the class which will be needed for safepoint debug information
 582       assert(klass->is_instance_klass(), "must be an instance klass.");
 583       iklass = klass->as_instance_klass();
 584       nfields = iklass->nof_nonstatic_fields();
 585     } else {
 586       // find the array's elements which will be needed for safepoint debug information
 587       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
 588       assert(klass->is_array_klass() && nfields >= 0, "must be an array klass.");
 589       elem_type = klass->as_array_klass()->element_type();
 590       basic_elem_type = elem_type->basic_type();
 591       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
 592       element_size = type2aelembytes(basic_elem_type);
 593     }
 594   }
 595   //
 596   // Process the safepoint uses
 597   //
 598   while (safepoints.length() > 0) {
 599     SafePointNode* sfpt = safepoints.pop();
 600     Node* mem = sfpt->memory();
 601     uint first_ind = sfpt->req();
 602     SafePointScalarObjectNode* sobj = new (C, 1) SafePointScalarObjectNode(res_type,
 603 #ifdef ASSERT
 604                                                  alloc,
 605 #endif
 606                                                  first_ind, nfields);
 607     sobj->init_req(0, sfpt->in(TypeFunc::Control));
 608     transform_later(sobj);
 609 
 610     // Scan object's fields adding an input to the safepoint for each field.
 611     for (int j = 0; j < nfields; j++) {
 612       intptr_t offset;
 613       ciField* field = NULL;
 614       if (iklass != NULL) {
 615         field = iklass->nonstatic_field_at(j);
 616         offset = field->offset();
 617         elem_type = field->type();
 618         basic_elem_type = field->layout_type();
 619       } else {
 620         offset = array_base + j * (intptr_t)element_size;
 621       }
 622 
 623       const Type *field_type;
 624       // The next code is taken from Parse::do_get_xxx().
 625       if (basic_elem_type == T_OBJECT || basic_elem_type == T_ARRAY) {
 626         if (!elem_type->is_loaded()) {
 627           field_type = TypeInstPtr::BOTTOM;
 628         } else if (field != NULL && field->is_constant()) {
 629           // This can happen if the constant oop is non-perm.
 630           ciObject* con = field->constant_value().as_object();
 631           // Do not "join" in the previous type; it doesn't add value,
 632           // and may yield a vacuous result if the field is of interface type.
 633           field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 634           assert(field_type != NULL, "field singleton type must be consistent");
 635         } else {
 636           field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
 637         }
 638         if (UseCompressedOops) {
 639           field_type = field_type->make_narrowoop();
 640           basic_elem_type = T_NARROWOOP;
 641         }
 642       } else {
 643         field_type = Type::get_const_basic_type(basic_elem_type);
 644       }
 645 
 646       const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
 647 
 648       Node *field_val = value_from_mem(mem, basic_elem_type, field_type, field_addr_type, alloc);
 649       if (field_val == NULL) {
 650         // we weren't able to find a value for this field,
 651         // give up on eliminating this allocation
 652         alloc->_is_scalar_replaceable = false;  // don't try again
 653         // remove any extra entries we added to the safepoint
 654         uint last = sfpt->req() - 1;
 655         for (int k = 0;  k < j; k++) {
 656           sfpt->del_req(last--);
 657         }
 658         // rollback processed safepoints
 659         while (safepoints_done.length() > 0) {
 660           SafePointNode* sfpt_done = safepoints_done.pop();
 661           // remove any extra entries we added to the safepoint
 662           last = sfpt_done->req() - 1;
 663           for (int k = 0;  k < nfields; k++) {
 664             sfpt_done->del_req(last--);
 665           }
 666           JVMState *jvms = sfpt_done->jvms();
 667           jvms->set_endoff(sfpt_done->req());
 668           // Now make a pass over the debug information replacing any references
 669           // to SafePointScalarObjectNode with the allocated object.
 670           int start = jvms->debug_start();
 671           int end   = jvms->debug_end();
 672           for (int i = start; i < end; i++) {
 673             if (sfpt_done->in(i)->is_SafePointScalarObject()) {
 674               SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
 675               if (scobj->first_index() == sfpt_done->req() &&
 676                   scobj->n_fields() == (uint)nfields) {
 677                 assert(scobj->alloc() == alloc, "sanity");
 678                 sfpt_done->set_req(i, res);
 679               }
 680             }
 681           }
 682         }
 683 #ifndef PRODUCT
 684         if (PrintEliminateAllocations) {
 685           if (field != NULL) {
 686             tty->print("=== At SafePoint node %d can't find value of Field: ",
 687                        sfpt->_idx);
 688             field->print();
 689             int field_idx = C->get_alias_index(field_addr_type);
 690             tty->print(" (alias_idx=%d)", field_idx);
 691           } else { // Array's element
 692             tty->print("=== At SafePoint node %d can't find value of array element [%d]",
 693                        sfpt->_idx, j);
 694           }
 695           tty->print(", which prevents elimination of: ");
 696           if (res == NULL)
 697             alloc->dump();
 698           else
 699             res->dump();
 700         }
 701 #endif
 702         return false;
 703       }
 704       if (UseCompressedOops && field_type->isa_narrowoop()) {
 705         // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
 706         // to be able scalar replace the allocation.
 707         if (field_val->is_EncodeP()) {
 708           field_val = field_val->in(1);
 709         } else {
 710           field_val = transform_later(new (C, 2) DecodeNNode(field_val, field_val->bottom_type()->make_ptr()));
 711         }
 712       }
 713       sfpt->add_req(field_val);
 714     }
 715     JVMState *jvms = sfpt->jvms();
 716     jvms->set_endoff(sfpt->req());
 717     // Now make a pass over the debug information replacing any references
 718     // to the allocated object with "sobj"
 719     int start = jvms->debug_start();
 720     int end   = jvms->debug_end();
 721     for (int i = start; i < end; i++) {
 722       if (sfpt->in(i) == res) {
 723         sfpt->set_req(i, sobj);
 724       }
 725     }
 726     safepoints_done.append_if_missing(sfpt); // keep it for rollback
 727   }
 728   return true;
 729 }
 730 
 731 // Process users of eliminated allocation.
 732 void PhaseMacroExpand::process_users_of_allocation(AllocateNode *alloc) {
 733   Node* res = alloc->result_cast();
 734   if (res != NULL) {
 735     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
 736       Node *use = res->last_out(j);
 737       uint oc1 = res->outcnt();
 738 
 739       if (use->is_AddP()) {
 740         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
 741           Node *n = use->last_out(k);
 742           uint oc2 = use->outcnt();
 743           if (n->is_Store()) {
 744             _igvn.replace_node(n, n->in(MemNode::Memory));
 745           } else {
 746             assert( n->Opcode() == Op_CastP2X, "CastP2X required");
 747             eliminate_card_mark(n);
 748           }
 749           k -= (oc2 - use->outcnt());
 750         }
 751       } else {
 752         assert( !use->is_SafePoint(), "safepoint uses must have been already elimiated");
 753         assert( use->Opcode() == Op_CastP2X, "CastP2X required");
 754         eliminate_card_mark(use);
 755       }
 756       j -= (oc1 - res->outcnt());
 757     }
 758     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
 759     _igvn.remove_dead_node(res);
 760   }
 761 
 762   //
 763   // Process other users of allocation's projections
 764   //
 765   if (_resproj != NULL && _resproj->outcnt() != 0) {
 766     for (DUIterator_Last jmin, j = _resproj->last_outs(jmin); j >= jmin; ) {
 767       Node *use = _resproj->last_out(j);
 768       uint oc1 = _resproj->outcnt();
 769       if (use->is_Initialize()) {
 770         // Eliminate Initialize node.
 771         InitializeNode *init = use->as_Initialize();
 772         assert(init->outcnt() <= 2, "only a control and memory projection expected");
 773         Node *ctrl_proj = init->proj_out(TypeFunc::Control);
 774         if (ctrl_proj != NULL) {
 775            assert(init->in(TypeFunc::Control) == _fallthroughcatchproj, "allocation control projection");
 776           _igvn.replace_node(ctrl_proj, _fallthroughcatchproj);
 777         }
 778         Node *mem_proj = init->proj_out(TypeFunc::Memory);
 779         if (mem_proj != NULL) {
 780           Node *mem = init->in(TypeFunc::Memory);
 781 #ifdef ASSERT
 782           if (mem->is_MergeMem()) {
 783             assert(mem->in(TypeFunc::Memory) == _memproj_fallthrough, "allocation memory projection");
 784           } else {
 785             assert(mem == _memproj_fallthrough, "allocation memory projection");
 786           }
 787 #endif
 788           _igvn.replace_node(mem_proj, mem);
 789         }
 790       } else if (use->is_AddP()) {
 791         // raw memory addresses used only by the initialization
 792         _igvn.hash_delete(use);
 793         _igvn.subsume_node(use, C->top());
 794       } else  {
 795         assert(false, "only Initialize or AddP expected");
 796       }
 797       j -= (oc1 - _resproj->outcnt());
 798     }
 799   }
 800   if (_fallthroughcatchproj != NULL) {
 801     _igvn.replace_node(_fallthroughcatchproj, alloc->in(TypeFunc::Control));
 802   }
 803   if (_memproj_fallthrough != NULL) {
 804     _igvn.replace_node(_memproj_fallthrough, alloc->in(TypeFunc::Memory));
 805   }
 806   if (_memproj_catchall != NULL) {
 807     _igvn.replace_node(_memproj_catchall, C->top());
 808   }
 809   if (_ioproj_fallthrough != NULL) {
 810     _igvn.replace_node(_ioproj_fallthrough, alloc->in(TypeFunc::I_O));
 811   }
 812   if (_ioproj_catchall != NULL) {
 813     _igvn.replace_node(_ioproj_catchall, C->top());
 814   }
 815   if (_catchallcatchproj != NULL) {
 816     _igvn.replace_node(_catchallcatchproj, C->top());
 817   }
 818 }
 819 
 820 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
 821 
 822   if (!EliminateAllocations || !alloc->_is_scalar_replaceable) {
 823     return false;
 824   }
 825 
 826   extract_call_projections(alloc);
 827 
 828   GrowableArray <SafePointNode *> safepoints;
 829   if (!can_eliminate_allocation(alloc, safepoints)) {
 830     return false;
 831   }
 832 
 833   if (!scalar_replacement(alloc, safepoints)) {
 834     return false;
 835   }
 836 
 837   process_users_of_allocation(alloc);
 838 
 839 #ifndef PRODUCT
 840 if (PrintEliminateAllocations) {
 841   if (alloc->is_AllocateArray())
 842     tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
 843   else
 844     tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
 845 }
 846 #endif
 847 
 848   return true;
 849 }
 850 
 851 
 852 //---------------------------set_eden_pointers-------------------------
 853 void PhaseMacroExpand::set_eden_pointers(Node* &eden_top_adr, Node* &eden_end_adr) {
 854   if (UseTLAB) {                // Private allocation: load from TLS
 855     Node* thread = transform_later(new (C, 1) ThreadLocalNode());
 856     int tlab_top_offset = in_bytes(JavaThread::tlab_top_offset());
 857     int tlab_end_offset = in_bytes(JavaThread::tlab_end_offset());
 858     eden_top_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_top_offset);
 859     eden_end_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_end_offset);
 860   } else {                      // Shared allocation: load from globals
 861     CollectedHeap* ch = Universe::heap();
 862     address top_adr = (address)ch->top_addr();
 863     address end_adr = (address)ch->end_addr();
 864     eden_top_adr = makecon(TypeRawPtr::make(top_adr));
 865     eden_end_adr = basic_plus_adr(eden_top_adr, end_adr - top_adr);
 866   }
 867 }
 868 
 869 
 870 Node* PhaseMacroExpand::make_load(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) {
 871   Node* adr = basic_plus_adr(base, offset);
 872   const TypePtr* adr_type = adr->bottom_type()->is_ptr();
 873   Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt);
 874   transform_later(value);
 875   return value;
 876 }
 877 
 878 
 879 Node* PhaseMacroExpand::make_store(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) {
 880   Node* adr = basic_plus_adr(base, offset);
 881   mem = StoreNode::make(_igvn, ctl, mem, adr, NULL, value, bt);
 882   transform_later(mem);
 883   return mem;
 884 }
 885 
 886 //=============================================================================
 887 //
 888 //                              A L L O C A T I O N
 889 //
 890 // Allocation attempts to be fast in the case of frequent small objects.
 891 // It breaks down like this:
 892 //
 893 // 1) Size in doublewords is computed.  This is a constant for objects and
 894 // variable for most arrays.  Doubleword units are used to avoid size
 895 // overflow of huge doubleword arrays.  We need doublewords in the end for
 896 // rounding.
 897 //
 898 // 2) Size is checked for being 'too large'.  Too-large allocations will go
 899 // the slow path into the VM.  The slow path can throw any required
 900 // exceptions, and does all the special checks for very large arrays.  The
 901 // size test can constant-fold away for objects.  For objects with
 902 // finalizers it constant-folds the otherway: you always go slow with
 903 // finalizers.
 904 //
 905 // 3) If NOT using TLABs, this is the contended loop-back point.
 906 // Load-Locked the heap top.  If using TLABs normal-load the heap top.
 907 //
 908 // 4) Check that heap top + size*8 < max.  If we fail go the slow ` route.
 909 // NOTE: "top+size*8" cannot wrap the 4Gig line!  Here's why: for largish
 910 // "size*8" we always enter the VM, where "largish" is a constant picked small
 911 // enough that there's always space between the eden max and 4Gig (old space is
 912 // there so it's quite large) and large enough that the cost of entering the VM
 913 // is dwarfed by the cost to initialize the space.
 914 //
 915 // 5) If NOT using TLABs, Store-Conditional the adjusted heap top back
 916 // down.  If contended, repeat at step 3.  If using TLABs normal-store
 917 // adjusted heap top back down; there is no contention.
 918 //
 919 // 6) If !ZeroTLAB then Bulk-clear the object/array.  Fill in klass & mark
 920 // fields.
 921 //
 922 // 7) Merge with the slow-path; cast the raw memory pointer to the correct
 923 // oop flavor.
 924 //
 925 //=============================================================================
 926 // FastAllocateSizeLimit value is in DOUBLEWORDS.
 927 // Allocations bigger than this always go the slow route.
 928 // This value must be small enough that allocation attempts that need to
 929 // trigger exceptions go the slow route.  Also, it must be small enough so
 930 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
 931 //=============================================================================j//
 932 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
 933 // The allocator will coalesce int->oop copies away.  See comment in
 934 // coalesce.cpp about how this works.  It depends critically on the exact
 935 // code shape produced here, so if you are changing this code shape
 936 // make sure the GC info for the heap-top is correct in and around the
 937 // slow-path call.
 938 //
 939 
 940 void PhaseMacroExpand::expand_allocate_common(
 941             AllocateNode* alloc, // allocation node to be expanded
 942             Node* length,  // array length for an array allocation
 943             const TypeFunc* slow_call_type, // Type of slow call
 944             address slow_call_address  // Address of slow call
 945     )
 946 {
 947 
 948   Node* ctrl = alloc->in(TypeFunc::Control);
 949   Node* mem  = alloc->in(TypeFunc::Memory);
 950   Node* i_o  = alloc->in(TypeFunc::I_O);
 951   Node* size_in_bytes     = alloc->in(AllocateNode::AllocSize);
 952   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
 953   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
 954 
 955   // With escape analysis, the entire memory state was needed to be able to
 956   // eliminate the allocation.  Since the allocations cannot be eliminated,
 957   // optimize it to the raw slice.
 958   if (mem->is_MergeMem()) {
 959     mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
 960   }
 961 
 962   assert(ctrl != NULL, "must have control");
 963   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
 964   // they will not be used if "always_slow" is set
 965   enum { slow_result_path = 1, fast_result_path = 2 };
 966   Node *result_region;
 967   Node *result_phi_rawmem;
 968   Node *result_phi_rawoop;
 969   Node *result_phi_i_o;
 970 
 971   // The initial slow comparison is a size check, the comparison
 972   // we want to do is a BoolTest::gt
 973   bool always_slow = false;
 974   int tv = _igvn.find_int_con(initial_slow_test, -1);
 975   if (tv >= 0) {
 976     always_slow = (tv == 1);
 977     initial_slow_test = NULL;
 978   } else {
 979     initial_slow_test = BoolNode::make_predicate(initial_slow_test, &_igvn);
 980   }
 981 
 982   if (DTraceAllocProbes ||
 983       !UseTLAB && (!Universe::heap()->supports_inline_contig_alloc() ||
 984                    (UseConcMarkSweepGC && CMSIncrementalMode))) {
 985     // Force slow-path allocation
 986     always_slow = true;
 987     initial_slow_test = NULL;
 988   }
 989 
 990 
 991   enum { too_big_or_final_path = 1, need_gc_path = 2 };
 992   Node *slow_region = NULL;
 993   Node *toobig_false = ctrl;
 994 
 995   assert (initial_slow_test == NULL || !always_slow, "arguments must be consistent");
 996   // generate the initial test if necessary
 997   if (initial_slow_test != NULL ) {
 998     slow_region = new (C, 3) RegionNode(3);
 999 
1000     // Now make the initial failure test.  Usually a too-big test but
1001     // might be a TRUE for finalizers or a fancy class check for
1002     // newInstance0.
1003     IfNode *toobig_iff = new (C, 2) IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1004     transform_later(toobig_iff);
1005     // Plug the failing-too-big test into the slow-path region
1006     Node *toobig_true = new (C, 1) IfTrueNode( toobig_iff );
1007     transform_later(toobig_true);
1008     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1009     toobig_false = new (C, 1) IfFalseNode( toobig_iff );
1010     transform_later(toobig_false);
1011   } else {         // No initial test, just fall into next case
1012     toobig_false = ctrl;
1013     debug_only(slow_region = NodeSentinel);
1014   }
1015 
1016   Node *slow_mem = mem;  // save the current memory state for slow path
1017   // generate the fast allocation code unless we know that the initial test will always go slow
1018   if (!always_slow) {
1019     Node* eden_top_adr;
1020     Node* eden_end_adr;
1021 
1022     set_eden_pointers(eden_top_adr, eden_end_adr);
1023 
1024     // Load Eden::end.  Loop invariant and hoisted.
1025     //
1026     // Note: We set the control input on "eden_end" and "old_eden_top" when using
1027     //       a TLAB to work around a bug where these values were being moved across
1028     //       a safepoint.  These are not oops, so they cannot be include in the oop
1029     //       map, but the can be changed by a GC.   The proper way to fix this would
1030     //       be to set the raw memory state when generating a  SafepointNode.  However
1031     //       this will require extensive changes to the loop optimization in order to
1032     //       prevent a degradation of the optimization.
1033     //       See comment in memnode.hpp, around line 227 in class LoadPNode.
1034     Node *eden_end = make_load(ctrl, mem, eden_end_adr, 0, TypeRawPtr::BOTTOM, T_ADDRESS);
1035 
1036     // allocate the Region and Phi nodes for the result
1037     result_region = new (C, 3) RegionNode(3);
1038     result_phi_rawmem = new (C, 3) PhiNode( result_region, Type::MEMORY, TypeRawPtr::BOTTOM );
1039     result_phi_rawoop = new (C, 3) PhiNode( result_region, TypeRawPtr::BOTTOM );
1040     result_phi_i_o    = new (C, 3) PhiNode( result_region, Type::ABIO ); // I/O is used for Prefetch
1041 
1042     // We need a Region for the loop-back contended case.
1043     enum { fall_in_path = 1, contended_loopback_path = 2 };
1044     Node *contended_region;
1045     Node *contended_phi_rawmem;
1046     if( UseTLAB ) {
1047       contended_region = toobig_false;
1048       contended_phi_rawmem = mem;
1049     } else {
1050       contended_region = new (C, 3) RegionNode(3);
1051       contended_phi_rawmem = new (C, 3) PhiNode( contended_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1052       // Now handle the passing-too-big test.  We fall into the contended
1053       // loop-back merge point.
1054       contended_region    ->init_req( fall_in_path, toobig_false );
1055       contended_phi_rawmem->init_req( fall_in_path, mem );
1056       transform_later(contended_region);
1057       transform_later(contended_phi_rawmem);
1058     }
1059 
1060     // Load(-locked) the heap top.
1061     // See note above concerning the control input when using a TLAB
1062     Node *old_eden_top = UseTLAB
1063       ? new (C, 3) LoadPNode     ( ctrl, contended_phi_rawmem, eden_top_adr, TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM )
1064       : new (C, 3) LoadPLockedNode( contended_region, contended_phi_rawmem, eden_top_adr );
1065 
1066     transform_later(old_eden_top);
1067     // Add to heap top to get a new heap top
1068     Node *new_eden_top = new (C, 4) AddPNode( top(), old_eden_top, size_in_bytes );
1069     transform_later(new_eden_top);
1070     // Check for needing a GC; compare against heap end
1071     Node *needgc_cmp = new (C, 3) CmpPNode( new_eden_top, eden_end );
1072     transform_later(needgc_cmp);
1073     Node *needgc_bol = new (C, 2) BoolNode( needgc_cmp, BoolTest::ge );
1074     transform_later(needgc_bol);
1075     IfNode *needgc_iff = new (C, 2) IfNode(contended_region, needgc_bol, PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
1076     transform_later(needgc_iff);
1077 
1078     // Plug the failing-heap-space-need-gc test into the slow-path region
1079     Node *needgc_true = new (C, 1) IfTrueNode( needgc_iff );
1080     transform_later(needgc_true);
1081     if( initial_slow_test ) {
1082       slow_region    ->init_req( need_gc_path, needgc_true );
1083       // This completes all paths into the slow merge point
1084       transform_later(slow_region);
1085     } else {                      // No initial slow path needed!
1086       // Just fall from the need-GC path straight into the VM call.
1087       slow_region    = needgc_true;
1088     }
1089     // No need for a GC.  Setup for the Store-Conditional
1090     Node *needgc_false = new (C, 1) IfFalseNode( needgc_iff );
1091     transform_later(needgc_false);
1092 
1093     // Grab regular I/O before optional prefetch may change it.
1094     // Slow-path does no I/O so just set it to the original I/O.
1095     result_phi_i_o->init_req( slow_result_path, i_o );
1096 
1097     i_o = prefetch_allocation(i_o, needgc_false, contended_phi_rawmem,
1098                               old_eden_top, new_eden_top, length);
1099 
1100     // Store (-conditional) the modified eden top back down.
1101     // StorePConditional produces flags for a test PLUS a modified raw
1102     // memory state.
1103     Node *store_eden_top;
1104     Node *fast_oop_ctrl;
1105     if( UseTLAB ) {
1106       store_eden_top = new (C, 4) StorePNode( needgc_false, contended_phi_rawmem, eden_top_adr, TypeRawPtr::BOTTOM, new_eden_top );
1107       transform_later(store_eden_top);
1108       fast_oop_ctrl = needgc_false; // No contention, so this is the fast path
1109     } else {
1110       store_eden_top = new (C, 5) StorePConditionalNode( needgc_false, contended_phi_rawmem, eden_top_adr, new_eden_top, old_eden_top );
1111       transform_later(store_eden_top);
1112       Node *contention_check = new (C, 2) BoolNode( store_eden_top, BoolTest::ne );
1113       transform_later(contention_check);
1114       store_eden_top = new (C, 1) SCMemProjNode(store_eden_top);
1115       transform_later(store_eden_top);
1116 
1117       // If not using TLABs, check to see if there was contention.
1118       IfNode *contention_iff = new (C, 2) IfNode ( needgc_false, contention_check, PROB_MIN, COUNT_UNKNOWN );
1119       transform_later(contention_iff);
1120       Node *contention_true = new (C, 1) IfTrueNode( contention_iff );
1121       transform_later(contention_true);
1122       // If contention, loopback and try again.
1123       contended_region->init_req( contended_loopback_path, contention_true );
1124       contended_phi_rawmem->init_req( contended_loopback_path, store_eden_top );
1125 
1126       // Fast-path succeeded with no contention!
1127       Node *contention_false = new (C, 1) IfFalseNode( contention_iff );
1128       transform_later(contention_false);
1129       fast_oop_ctrl = contention_false;
1130     }
1131 
1132     // Rename successful fast-path variables to make meaning more obvious
1133     Node* fast_oop        = old_eden_top;
1134     Node* fast_oop_rawmem = store_eden_top;
1135     fast_oop_rawmem = initialize_object(alloc,
1136                                         fast_oop_ctrl, fast_oop_rawmem, fast_oop,
1137                                         klass_node, length, size_in_bytes);
1138 
1139     if (ExtendedDTraceProbes) {
1140       // Slow-path call
1141       int size = TypeFunc::Parms + 2;
1142       CallLeafNode *call = new (C, size) CallLeafNode(OptoRuntime::dtrace_object_alloc_Type(),
1143                                                       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_object_alloc_base),
1144                                                       "dtrace_object_alloc",
1145                                                       TypeRawPtr::BOTTOM);
1146 
1147       // Get base of thread-local storage area
1148       Node* thread = new (C, 1) ThreadLocalNode();
1149       transform_later(thread);
1150 
1151       call->init_req(TypeFunc::Parms+0, thread);
1152       call->init_req(TypeFunc::Parms+1, fast_oop);
1153       call->init_req( TypeFunc::Control, fast_oop_ctrl );
1154       call->init_req( TypeFunc::I_O    , top() )        ;   // does no i/o
1155       call->init_req( TypeFunc::Memory , fast_oop_rawmem );
1156       call->init_req( TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr) );
1157       call->init_req( TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr) );
1158       transform_later(call);
1159       fast_oop_ctrl = new (C, 1) ProjNode(call,TypeFunc::Control);
1160       transform_later(fast_oop_ctrl);
1161       fast_oop_rawmem = new (C, 1) ProjNode(call,TypeFunc::Memory);
1162       transform_later(fast_oop_rawmem);
1163     }
1164 
1165     // Plug in the successful fast-path into the result merge point
1166     result_region    ->init_req( fast_result_path, fast_oop_ctrl );
1167     result_phi_rawoop->init_req( fast_result_path, fast_oop );
1168     result_phi_i_o   ->init_req( fast_result_path, i_o );
1169     result_phi_rawmem->init_req( fast_result_path, fast_oop_rawmem );
1170   } else {
1171     slow_region = ctrl;
1172   }
1173 
1174   // Generate slow-path call
1175   CallNode *call = new (C, slow_call_type->domain()->cnt())
1176     CallStaticJavaNode(slow_call_type, slow_call_address,
1177                        OptoRuntime::stub_name(slow_call_address),
1178                        alloc->jvms()->bci(),
1179                        TypePtr::BOTTOM);
1180   call->init_req( TypeFunc::Control, slow_region );
1181   call->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
1182   call->init_req( TypeFunc::Memory , slow_mem ); // may gc ptrs
1183   call->init_req( TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr) );
1184   call->init_req( TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr) );
1185 
1186   call->init_req(TypeFunc::Parms+0, klass_node);
1187   if (length != NULL) {
1188     call->init_req(TypeFunc::Parms+1, length);
1189   }
1190 
1191   // Copy debug information and adjust JVMState information, then replace
1192   // allocate node with the call
1193   copy_call_debug_info((CallNode *) alloc,  call);
1194   if (!always_slow) {
1195     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1196   }
1197   _igvn.hash_delete(alloc);
1198   _igvn.subsume_node(alloc, call);
1199   transform_later(call);
1200 
1201   // Identify the output projections from the allocate node and
1202   // adjust any references to them.
1203   // The control and io projections look like:
1204   //
1205   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1206   //  Allocate                   Catch
1207   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1208   //
1209   //  We are interested in the CatchProj nodes.
1210   //
1211   extract_call_projections(call);
1212 
1213   // An allocate node has separate memory projections for the uses on the control and i_o paths
1214   // Replace uses of the control memory projection with result_phi_rawmem (unless we are only generating a slow call)
1215   if (!always_slow && _memproj_fallthrough != NULL) {
1216     for (DUIterator_Fast imax, i = _memproj_fallthrough->fast_outs(imax); i < imax; i++) {
1217       Node *use = _memproj_fallthrough->fast_out(i);
1218       _igvn.hash_delete(use);
1219       imax -= replace_input(use, _memproj_fallthrough, result_phi_rawmem);
1220       _igvn._worklist.push(use);
1221       // back up iterator
1222       --i;
1223     }
1224   }
1225   // Now change uses of _memproj_catchall to use _memproj_fallthrough and delete _memproj_catchall so
1226   // we end up with a call that has only 1 memory projection
1227   if (_memproj_catchall != NULL ) {
1228     if (_memproj_fallthrough == NULL) {
1229       _memproj_fallthrough = new (C, 1) ProjNode(call, TypeFunc::Memory);
1230       transform_later(_memproj_fallthrough);
1231     }
1232     for (DUIterator_Fast imax, i = _memproj_catchall->fast_outs(imax); i < imax; i++) {
1233       Node *use = _memproj_catchall->fast_out(i);
1234       _igvn.hash_delete(use);
1235       imax -= replace_input(use, _memproj_catchall, _memproj_fallthrough);
1236       _igvn._worklist.push(use);
1237       // back up iterator
1238       --i;
1239     }
1240   }
1241 
1242   mem = result_phi_rawmem;
1243 
1244   // An allocate node has separate i_o projections for the uses on the control and i_o paths
1245   // Replace uses of the control i_o projection with result_phi_i_o (unless we are only generating a slow call)
1246   if (_ioproj_fallthrough == NULL) {
1247     _ioproj_fallthrough = new (C, 1) ProjNode(call, TypeFunc::I_O);
1248     transform_later(_ioproj_fallthrough);
1249   } else if (!always_slow) {
1250     for (DUIterator_Fast imax, i = _ioproj_fallthrough->fast_outs(imax); i < imax; i++) {
1251       Node *use = _ioproj_fallthrough->fast_out(i);
1252 
1253       _igvn.hash_delete(use);
1254       imax -= replace_input(use, _ioproj_fallthrough, result_phi_i_o);
1255       _igvn._worklist.push(use);
1256       // back up iterator
1257       --i;
1258     }
1259   }
1260   // Now change uses of _ioproj_catchall to use _ioproj_fallthrough and delete _ioproj_catchall so
1261   // we end up with a call that has only 1 control projection
1262   if (_ioproj_catchall != NULL ) {
1263     for (DUIterator_Fast imax, i = _ioproj_catchall->fast_outs(imax); i < imax; i++) {
1264       Node *use = _ioproj_catchall->fast_out(i);
1265       _igvn.hash_delete(use);
1266       imax -= replace_input(use, _ioproj_catchall, _ioproj_fallthrough);
1267       _igvn._worklist.push(use);
1268       // back up iterator
1269       --i;
1270     }
1271   }
1272 
1273   // if we generated only a slow call, we are done
1274   if (always_slow)
1275     return;
1276 
1277 
1278   if (_fallthroughcatchproj != NULL) {
1279     ctrl = _fallthroughcatchproj->clone();
1280     transform_later(ctrl);
1281     _igvn.hash_delete(_fallthroughcatchproj);
1282     _igvn.subsume_node(_fallthroughcatchproj, result_region);
1283   } else {
1284     ctrl = top();
1285   }
1286   Node *slow_result;
1287   if (_resproj == NULL) {
1288     // no uses of the allocation result
1289     slow_result = top();
1290   } else {
1291     slow_result = _resproj->clone();
1292     transform_later(slow_result);
1293     _igvn.hash_delete(_resproj);
1294     _igvn.subsume_node(_resproj, result_phi_rawoop);
1295   }
1296 
1297   // Plug slow-path into result merge point
1298   result_region    ->init_req( slow_result_path, ctrl );
1299   result_phi_rawoop->init_req( slow_result_path, slow_result);
1300   result_phi_rawmem->init_req( slow_result_path, _memproj_fallthrough );
1301   transform_later(result_region);
1302   transform_later(result_phi_rawoop);
1303   transform_later(result_phi_rawmem);
1304   transform_later(result_phi_i_o);
1305   // This completes all paths into the result merge point
1306 }
1307 
1308 
1309 // Helper for PhaseMacroExpand::expand_allocate_common.
1310 // Initializes the newly-allocated storage.
1311 Node*
1312 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1313                                     Node* control, Node* rawmem, Node* object,
1314                                     Node* klass_node, Node* length,
1315                                     Node* size_in_bytes) {
1316   InitializeNode* init = alloc->initialization();
1317   // Store the klass & mark bits
1318   Node* mark_node = NULL;
1319   // For now only enable fast locking for non-array types
1320   if (UseBiasedLocking && (length == NULL)) {
1321     mark_node = make_load(NULL, rawmem, klass_node, Klass::prototype_header_offset_in_bytes() + sizeof(oopDesc), TypeRawPtr::BOTTOM, T_ADDRESS);
1322   } else {
1323     mark_node = makecon(TypeRawPtr::make((address)markOopDesc::prototype()));
1324   }
1325   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, T_ADDRESS);
1326 
1327   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_OBJECT);
1328   int header_size = alloc->minimum_header_size();  // conservatively small
1329 
1330   // Array length
1331   if (length != NULL) {         // Arrays need length field
1332     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1333     // conservatively small header size:
1334     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1335     ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1336     if (k->is_array_klass())    // we know the exact header size in most cases:
1337       header_size = Klass::layout_helper_header_size(k->layout_helper());
1338   }
1339 
1340   // Clear the object body, if necessary.
1341   if (init == NULL) {
1342     // The init has somehow disappeared; be cautious and clear everything.
1343     //
1344     // This can happen if a node is allocated but an uncommon trap occurs
1345     // immediately.  In this case, the Initialize gets associated with the
1346     // trap, and may be placed in a different (outer) loop, if the Allocate
1347     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1348     // there can be two Allocates to one Initialize.  The answer in all these
1349     // edge cases is safety first.  It is always safe to clear immediately
1350     // within an Allocate, and then (maybe or maybe not) clear some more later.
1351     if (!ZeroTLAB)
1352       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1353                                             header_size, size_in_bytes,
1354                                             &_igvn);
1355   } else {
1356     if (!init->is_complete()) {
1357       // Try to win by zeroing only what the init does not store.
1358       // We can also try to do some peephole optimizations,
1359       // such as combining some adjacent subword stores.
1360       rawmem = init->complete_stores(control, rawmem, object,
1361                                      header_size, size_in_bytes, &_igvn);
1362     }
1363     // We have no more use for this link, since the AllocateNode goes away:
1364     init->set_req(InitializeNode::RawAddress, top());
1365     // (If we keep the link, it just confuses the register allocator,
1366     // who thinks he sees a real use of the address by the membar.)
1367   }
1368 
1369   return rawmem;
1370 }
1371 
1372 // Generate prefetch instructions for next allocations.
1373 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
1374                                         Node*& contended_phi_rawmem,
1375                                         Node* old_eden_top, Node* new_eden_top,
1376                                         Node* length) {
1377    if( UseTLAB && AllocatePrefetchStyle == 2 ) {
1378       // Generate prefetch allocation with watermark check.
1379       // As an allocation hits the watermark, we will prefetch starting
1380       // at a "distance" away from watermark.
1381       enum { fall_in_path = 1, pf_path = 2 };
1382 
1383       Node *pf_region = new (C, 3) RegionNode(3);
1384       Node *pf_phi_rawmem = new (C, 3) PhiNode( pf_region, Type::MEMORY,
1385                                                 TypeRawPtr::BOTTOM );
1386       // I/O is used for Prefetch
1387       Node *pf_phi_abio = new (C, 3) PhiNode( pf_region, Type::ABIO );
1388 
1389       Node *thread = new (C, 1) ThreadLocalNode();
1390       transform_later(thread);
1391 
1392       Node *eden_pf_adr = new (C, 4) AddPNode( top()/*not oop*/, thread,
1393                    _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) );
1394       transform_later(eden_pf_adr);
1395 
1396       Node *old_pf_wm = new (C, 3) LoadPNode( needgc_false,
1397                                    contended_phi_rawmem, eden_pf_adr,
1398                                    TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM );
1399       transform_later(old_pf_wm);
1400 
1401       // check against new_eden_top
1402       Node *need_pf_cmp = new (C, 3) CmpPNode( new_eden_top, old_pf_wm );
1403       transform_later(need_pf_cmp);
1404       Node *need_pf_bol = new (C, 2) BoolNode( need_pf_cmp, BoolTest::ge );
1405       transform_later(need_pf_bol);
1406       IfNode *need_pf_iff = new (C, 2) IfNode( needgc_false, need_pf_bol,
1407                                        PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
1408       transform_later(need_pf_iff);
1409 
1410       // true node, add prefetchdistance
1411       Node *need_pf_true = new (C, 1) IfTrueNode( need_pf_iff );
1412       transform_later(need_pf_true);
1413 
1414       Node *need_pf_false = new (C, 1) IfFalseNode( need_pf_iff );
1415       transform_later(need_pf_false);
1416 
1417       Node *new_pf_wmt = new (C, 4) AddPNode( top(), old_pf_wm,
1418                                     _igvn.MakeConX(AllocatePrefetchDistance) );
1419       transform_later(new_pf_wmt );
1420       new_pf_wmt->set_req(0, need_pf_true);
1421 
1422       Node *store_new_wmt = new (C, 4) StorePNode( need_pf_true,
1423                                        contended_phi_rawmem, eden_pf_adr,
1424                                        TypeRawPtr::BOTTOM, new_pf_wmt );
1425       transform_later(store_new_wmt);
1426 
1427       // adding prefetches
1428       pf_phi_abio->init_req( fall_in_path, i_o );
1429 
1430       Node *prefetch_adr;
1431       Node *prefetch;
1432       uint lines = AllocatePrefetchDistance / AllocatePrefetchStepSize;
1433       uint step_size = AllocatePrefetchStepSize;
1434       uint distance = 0;
1435 
1436       for ( uint i = 0; i < lines; i++ ) {
1437         prefetch_adr = new (C, 4) AddPNode( old_pf_wm, new_pf_wmt,
1438                                             _igvn.MakeConX(distance) );
1439         transform_later(prefetch_adr);
1440         prefetch = new (C, 3) PrefetchWriteNode( i_o, prefetch_adr );
1441         transform_later(prefetch);
1442         distance += step_size;
1443         i_o = prefetch;
1444       }
1445       pf_phi_abio->set_req( pf_path, i_o );
1446 
1447       pf_region->init_req( fall_in_path, need_pf_false );
1448       pf_region->init_req( pf_path, need_pf_true );
1449 
1450       pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem );
1451       pf_phi_rawmem->init_req( pf_path, store_new_wmt );
1452 
1453       transform_later(pf_region);
1454       transform_later(pf_phi_rawmem);
1455       transform_later(pf_phi_abio);
1456 
1457       needgc_false = pf_region;
1458       contended_phi_rawmem = pf_phi_rawmem;
1459       i_o = pf_phi_abio;
1460    } else if( AllocatePrefetchStyle > 0 ) {
1461       // Insert a prefetch for each allocation only on the fast-path
1462       Node *prefetch_adr;
1463       Node *prefetch;
1464       // Generate several prefetch instructions only for arrays.
1465       uint lines = (length != NULL) ? AllocatePrefetchLines : 1;
1466       uint step_size = AllocatePrefetchStepSize;
1467       uint distance = AllocatePrefetchDistance;
1468       for ( uint i = 0; i < lines; i++ ) {
1469         prefetch_adr = new (C, 4) AddPNode( old_eden_top, new_eden_top,
1470                                             _igvn.MakeConX(distance) );
1471         transform_later(prefetch_adr);
1472         prefetch = new (C, 3) PrefetchWriteNode( i_o, prefetch_adr );
1473         // Do not let it float too high, since if eden_top == eden_end,
1474         // both might be null.
1475         if( i == 0 ) { // Set control for first prefetch, next follows it
1476           prefetch->init_req(0, needgc_false);
1477         }
1478         transform_later(prefetch);
1479         distance += step_size;
1480         i_o = prefetch;
1481       }
1482    }
1483    return i_o;
1484 }
1485 
1486 
1487 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
1488   expand_allocate_common(alloc, NULL,
1489                          OptoRuntime::new_instance_Type(),
1490                          OptoRuntime::new_instance_Java());
1491 }
1492 
1493 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
1494   Node* length = alloc->in(AllocateNode::ALength);
1495   expand_allocate_common(alloc, length,
1496                          OptoRuntime::new_array_Type(),
1497                          OptoRuntime::new_array_Java());
1498 }
1499 
1500 
1501 // we have determined that this lock/unlock can be eliminated, we simply
1502 // eliminate the node without expanding it.
1503 //
1504 // Note:  The membar's associated with the lock/unlock are currently not
1505 //        eliminated.  This should be investigated as a future enhancement.
1506 //
1507 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
1508 
1509   if (!alock->is_eliminated()) {
1510     return false;
1511   }
1512   if (alock->is_Lock() && !alock->is_coarsened()) {
1513       // Create new "eliminated" BoxLock node and use it
1514       // in monitor debug info for the same object.
1515       BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
1516       Node* obj = alock->obj_node();
1517       if (!oldbox->is_eliminated()) {
1518         BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
1519         newbox->set_eliminated();
1520         transform_later(newbox);
1521         // Replace old box node with new box for all users
1522         // of the same object.
1523         for (uint i = 0; i < oldbox->outcnt();) {
1524 
1525           bool next_edge = true;
1526           Node* u = oldbox->raw_out(i);
1527           if (u == alock) {
1528             i++;
1529             continue; // It will be removed below
1530           }
1531           if (u->is_Lock() &&
1532               u->as_Lock()->obj_node() == obj &&
1533               // oldbox could be referenced in debug info also
1534               u->as_Lock()->box_node() == oldbox) {
1535             assert(u->as_Lock()->is_eliminated(), "sanity");
1536             _igvn.hash_delete(u);
1537             u->set_req(TypeFunc::Parms + 1, newbox);
1538             next_edge = false;
1539 #ifdef ASSERT
1540           } else if (u->is_Unlock() && u->as_Unlock()->obj_node() == obj) {
1541             assert(u->as_Unlock()->is_eliminated(), "sanity");
1542 #endif
1543           }
1544           // Replace old box in monitor debug info.
1545           if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
1546             SafePointNode* sfn = u->as_SafePoint();
1547             JVMState* youngest_jvms = sfn->jvms();
1548             int max_depth = youngest_jvms->depth();
1549             for (int depth = 1; depth <= max_depth; depth++) {
1550               JVMState* jvms = youngest_jvms->of_depth(depth);
1551               int num_mon  = jvms->nof_monitors();
1552               // Loop over monitors
1553               for (int idx = 0; idx < num_mon; idx++) {
1554                 Node* obj_node = sfn->monitor_obj(jvms, idx);
1555                 Node* box_node = sfn->monitor_box(jvms, idx);
1556                 if (box_node == oldbox && obj_node == obj) {
1557                   int j = jvms->monitor_box_offset(idx);
1558                   _igvn.hash_delete(u);
1559                   u->set_req(j, newbox);
1560                   next_edge = false;
1561                 }
1562               } // for (int idx = 0;
1563             } // for (int depth = 1;
1564           } // if (u->is_SafePoint()
1565           if (next_edge) i++;
1566         } // for (uint i = 0; i < oldbox->outcnt();)
1567       } // if (!oldbox->is_eliminated())
1568   } // if (alock->is_Lock() && !lock->is_coarsened())
1569 
1570   #ifndef PRODUCT
1571   if (PrintEliminateLocks) {
1572     if (alock->is_Lock()) {
1573       tty->print_cr("++++ Eliminating: %d Lock", alock->_idx);
1574     } else {
1575       tty->print_cr("++++ Eliminating: %d Unlock", alock->_idx);
1576     }
1577   }
1578   #endif
1579 
1580   Node* mem  = alock->in(TypeFunc::Memory);
1581   Node* ctrl = alock->in(TypeFunc::Control);
1582 
1583   extract_call_projections(alock);
1584   // There are 2 projections from the lock.  The lock node will
1585   // be deleted when its last use is subsumed below.
1586   assert(alock->outcnt() == 2 &&
1587          _fallthroughproj != NULL &&
1588          _memproj_fallthrough != NULL,
1589          "Unexpected projections from Lock/Unlock");
1590 
1591   Node* fallthroughproj = _fallthroughproj;
1592   Node* memproj_fallthrough = _memproj_fallthrough;
1593 
1594   // The memory projection from a lock/unlock is RawMem
1595   // The input to a Lock is merged memory, so extract its RawMem input
1596   // (unless the MergeMem has been optimized away.)
1597   if (alock->is_Lock()) {
1598     // Seach for MemBarAcquire node and delete it also.
1599     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
1600     assert(membar != NULL && membar->Opcode() == Op_MemBarAcquire, "");
1601     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
1602     Node* memproj = membar->proj_out(TypeFunc::Memory);
1603     _igvn.hash_delete(ctrlproj);
1604     _igvn.subsume_node(ctrlproj, fallthroughproj);
1605     _igvn.hash_delete(memproj);
1606     _igvn.subsume_node(memproj, memproj_fallthrough);
1607 
1608     // Delete FastLock node also if this Lock node is unique user
1609     // (a loop peeling may clone a Lock node).
1610     Node* flock = alock->as_Lock()->fastlock_node();
1611     if (flock->outcnt() == 1) {
1612       assert(flock->unique_out() == alock, "sanity");
1613       _igvn.hash_delete(flock);
1614       _igvn.subsume_node(flock, top());
1615     }
1616   }
1617 
1618   // Seach for MemBarRelease node and delete it also.
1619   if (alock->is_Unlock() && ctrl != NULL && ctrl->is_Proj() &&
1620       ctrl->in(0)->is_MemBar()) {
1621     MemBarNode* membar = ctrl->in(0)->as_MemBar();
1622     assert(membar->Opcode() == Op_MemBarRelease &&
1623            mem->is_Proj() && membar == mem->in(0), "");
1624     _igvn.hash_delete(fallthroughproj);
1625     _igvn.subsume_node(fallthroughproj, ctrl);
1626     _igvn.hash_delete(memproj_fallthrough);
1627     _igvn.subsume_node(memproj_fallthrough, mem);
1628     fallthroughproj = ctrl;
1629     memproj_fallthrough = mem;
1630     ctrl = membar->in(TypeFunc::Control);
1631     mem  = membar->in(TypeFunc::Memory);
1632   }
1633 
1634   _igvn.hash_delete(fallthroughproj);
1635   _igvn.subsume_node(fallthroughproj, ctrl);
1636   _igvn.hash_delete(memproj_fallthrough);
1637   _igvn.subsume_node(memproj_fallthrough, mem);
1638   return true;
1639 }
1640 
1641 
1642 //------------------------------expand_lock_node----------------------
1643 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
1644 
1645   Node* ctrl = lock->in(TypeFunc::Control);
1646   Node* mem = lock->in(TypeFunc::Memory);
1647   Node* obj = lock->obj_node();
1648   Node* box = lock->box_node();
1649   Node* flock = lock->fastlock_node();
1650 
1651   // Make the merge point
1652   Node *region;
1653   Node *mem_phi;
1654   Node *slow_path;
1655 
1656   if (UseOptoBiasInlining) {
1657     /*
1658      *  See the full descrition in MacroAssembler::biased_locking_enter().
1659      *
1660      *  if( (mark_word & biased_lock_mask) == biased_lock_pattern ) {
1661      *    // The object is biased.
1662      *    proto_node = klass->prototype_header;
1663      *    o_node = thread | proto_node;
1664      *    x_node = o_node ^ mark_word;
1665      *    if( (x_node & ~age_mask) == 0 ) { // Biased to the current thread ?
1666      *      // Done.
1667      *    } else {
1668      *      if( (x_node & biased_lock_mask) != 0 ) {
1669      *        // The klass's prototype header is no longer biased.
1670      *        cas(&mark_word, mark_word, proto_node)
1671      *        goto cas_lock;
1672      *      } else {
1673      *        // The klass's prototype header is still biased.
1674      *        if( (x_node & epoch_mask) != 0 ) { // Expired epoch?
1675      *          old = mark_word;
1676      *          new = o_node;
1677      *        } else {
1678      *          // Different thread or anonymous biased.
1679      *          old = mark_word & (epoch_mask | age_mask | biased_lock_mask);
1680      *          new = thread | old;
1681      *        }
1682      *        // Try to rebias.
1683      *        if( cas(&mark_word, old, new) == 0 ) {
1684      *          // Done.
1685      *        } else {
1686      *          goto slow_path; // Failed.
1687      *        }
1688      *      }
1689      *    }
1690      *  } else {
1691      *    // The object is not biased.
1692      *    cas_lock:
1693      *    if( FastLock(obj) == 0 ) {
1694      *      // Done.
1695      *    } else {
1696      *      slow_path:
1697      *      OptoRuntime::complete_monitor_locking_Java(obj);
1698      *    }
1699      *  }
1700      */
1701 
1702     region  = new (C, 5) RegionNode(5);
1703     // create a Phi for the memory state
1704     mem_phi = new (C, 5) PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
1705 
1706     Node* fast_lock_region  = new (C, 3) RegionNode(3);
1707     Node* fast_lock_mem_phi = new (C, 3) PhiNode( fast_lock_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1708 
1709     // First, check mark word for the biased lock pattern.
1710     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
1711 
1712     // Get fast path - mark word has the biased lock pattern.
1713     ctrl = opt_bits_test(ctrl, fast_lock_region, 1, mark_node,
1714                          markOopDesc::biased_lock_mask_in_place,
1715                          markOopDesc::biased_lock_pattern, true);
1716     // fast_lock_region->in(1) is set to slow path.
1717     fast_lock_mem_phi->init_req(1, mem);
1718 
1719     // Now check that the lock is biased to the current thread and has
1720     // the same epoch and bias as Klass::_prototype_header.
1721 
1722     // Special-case a fresh allocation to avoid building nodes:
1723     Node* klass_node = AllocateNode::Ideal_klass(obj, &_igvn);
1724     if (klass_node == NULL) {
1725       Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1726       klass_node = transform_later( LoadKlassNode::make(_igvn, mem, k_adr, _igvn.type(k_adr)->is_ptr()) );
1727     }
1728     Node *proto_node = make_load(ctrl, mem, klass_node, Klass::prototype_header_offset_in_bytes() + sizeof(oopDesc), TypeX_X, TypeX_X->basic_type());
1729 
1730     Node* thread = transform_later(new (C, 1) ThreadLocalNode());
1731     Node* cast_thread = transform_later(new (C, 2) CastP2XNode(ctrl, thread));
1732     Node* o_node = transform_later(new (C, 3) OrXNode(cast_thread, proto_node));
1733     Node* x_node = transform_later(new (C, 3) XorXNode(o_node, mark_node));
1734 
1735     // Get slow path - mark word does NOT match the value.
1736     Node* not_biased_ctrl =  opt_bits_test(ctrl, region, 3, x_node,
1737                                       (~markOopDesc::age_mask_in_place), 0);
1738     // region->in(3) is set to fast path - the object is biased to the current thread.
1739     mem_phi->init_req(3, mem);
1740 
1741 
1742     // Mark word does NOT match the value (thread | Klass::_prototype_header).
1743 
1744 
1745     // First, check biased pattern.
1746     // Get fast path - _prototype_header has the same biased lock pattern.
1747     ctrl =  opt_bits_test(not_biased_ctrl, fast_lock_region, 2, x_node,
1748                           markOopDesc::biased_lock_mask_in_place, 0, true);
1749 
1750     not_biased_ctrl = fast_lock_region->in(2); // Slow path
1751     // fast_lock_region->in(2) - the prototype header is no longer biased
1752     // and we have to revoke the bias on this object.
1753     // We are going to try to reset the mark of this object to the prototype
1754     // value and fall through to the CAS-based locking scheme.
1755     Node* adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
1756     Node* cas = new (C, 5) StoreXConditionalNode(not_biased_ctrl, mem, adr,
1757                                                  proto_node, mark_node);
1758     transform_later(cas);
1759     Node* proj = transform_later( new (C, 1) SCMemProjNode(cas));
1760     fast_lock_mem_phi->init_req(2, proj);
1761 
1762 
1763     // Second, check epoch bits.
1764     Node* rebiased_region  = new (C, 3) RegionNode(3);
1765     Node* old_phi = new (C, 3) PhiNode( rebiased_region, TypeX_X);
1766     Node* new_phi = new (C, 3) PhiNode( rebiased_region, TypeX_X);
1767 
1768     // Get slow path - mark word does NOT match epoch bits.
1769     Node* epoch_ctrl =  opt_bits_test(ctrl, rebiased_region, 1, x_node,
1770                                       markOopDesc::epoch_mask_in_place, 0);
1771     // The epoch of the current bias is not valid, attempt to rebias the object
1772     // toward the current thread.
1773     rebiased_region->init_req(2, epoch_ctrl);
1774     old_phi->init_req(2, mark_node);
1775     new_phi->init_req(2, o_node);
1776 
1777     // rebiased_region->in(1) is set to fast path.
1778     // The epoch of the current bias is still valid but we know
1779     // nothing about the owner; it might be set or it might be clear.
1780     Node* cmask   = MakeConX(markOopDesc::biased_lock_mask_in_place |
1781                              markOopDesc::age_mask_in_place |
1782                              markOopDesc::epoch_mask_in_place);
1783     Node* old = transform_later(new (C, 3) AndXNode(mark_node, cmask));
1784     cast_thread = transform_later(new (C, 2) CastP2XNode(ctrl, thread));
1785     Node* new_mark = transform_later(new (C, 3) OrXNode(cast_thread, old));
1786     old_phi->init_req(1, old);
1787     new_phi->init_req(1, new_mark);
1788 
1789     transform_later(rebiased_region);
1790     transform_later(old_phi);
1791     transform_later(new_phi);
1792 
1793     // Try to acquire the bias of the object using an atomic operation.
1794     // If this fails we will go in to the runtime to revoke the object's bias.
1795     cas = new (C, 5) StoreXConditionalNode(rebiased_region, mem, adr,
1796                                            new_phi, old_phi);
1797     transform_later(cas);
1798     proj = transform_later( new (C, 1) SCMemProjNode(cas));
1799 
1800     // Get slow path - Failed to CAS.
1801     not_biased_ctrl = opt_bits_test(rebiased_region, region, 4, cas, 0, 0);
1802     mem_phi->init_req(4, proj);
1803     // region->in(4) is set to fast path - the object is rebiased to the current thread.
1804 
1805     // Failed to CAS.
1806     slow_path  = new (C, 3) RegionNode(3);
1807     Node *slow_mem = new (C, 3) PhiNode( slow_path, Type::MEMORY, TypeRawPtr::BOTTOM);
1808 
1809     slow_path->init_req(1, not_biased_ctrl); // Capture slow-control
1810     slow_mem->init_req(1, proj);
1811 
1812     // Call CAS-based locking scheme (FastLock node).
1813 
1814     transform_later(fast_lock_region);
1815     transform_later(fast_lock_mem_phi);
1816 
1817     // Get slow path - FastLock failed to lock the object.
1818     ctrl = opt_bits_test(fast_lock_region, region, 2, flock, 0, 0);
1819     mem_phi->init_req(2, fast_lock_mem_phi);
1820     // region->in(2) is set to fast path - the object is locked to the current thread.
1821 
1822     slow_path->init_req(2, ctrl); // Capture slow-control
1823     slow_mem->init_req(2, fast_lock_mem_phi);
1824 
1825     transform_later(slow_path);
1826     transform_later(slow_mem);
1827     // Reset lock's memory edge.
1828     lock->set_req(TypeFunc::Memory, slow_mem);
1829 
1830   } else {
1831     region  = new (C, 3) RegionNode(3);
1832     // create a Phi for the memory state
1833     mem_phi = new (C, 3) PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
1834 
1835     // Optimize test; set region slot 2
1836     slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
1837     mem_phi->init_req(2, mem);
1838   }
1839 
1840   // Make slow path call
1841   CallNode *call = make_slow_call( (CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(), OptoRuntime::complete_monitor_locking_Java(), NULL, slow_path, obj, box );
1842 
1843   extract_call_projections(call);
1844 
1845   // Slow path can only throw asynchronous exceptions, which are always
1846   // de-opted.  So the compiler thinks the slow-call can never throw an
1847   // exception.  If it DOES throw an exception we would need the debug
1848   // info removed first (since if it throws there is no monitor).
1849   assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
1850            _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
1851 
1852   // Capture slow path
1853   // disconnect fall-through projection from call and create a new one
1854   // hook up users of fall-through projection to region
1855   Node *slow_ctrl = _fallthroughproj->clone();
1856   transform_later(slow_ctrl);
1857   _igvn.hash_delete(_fallthroughproj);
1858   _fallthroughproj->disconnect_inputs(NULL);
1859   region->init_req(1, slow_ctrl);
1860   // region inputs are now complete
1861   transform_later(region);
1862   _igvn.subsume_node(_fallthroughproj, region);
1863 
1864   Node *memproj = transform_later( new(C, 1) ProjNode(call, TypeFunc::Memory) );
1865   mem_phi->init_req(1, memproj );
1866   transform_later(mem_phi);
1867   _igvn.hash_delete(_memproj_fallthrough);
1868   _igvn.subsume_node(_memproj_fallthrough, mem_phi);
1869 }
1870 
1871 //------------------------------expand_unlock_node----------------------
1872 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
1873 
1874   Node* ctrl = unlock->in(TypeFunc::Control);
1875   Node* mem = unlock->in(TypeFunc::Memory);
1876   Node* obj = unlock->obj_node();
1877   Node* box = unlock->box_node();
1878 
1879   // No need for a null check on unlock
1880 
1881   // Make the merge point
1882   Node *region;
1883   Node *mem_phi;
1884 
1885   if (UseOptoBiasInlining) {
1886     // Check for biased locking unlock case, which is a no-op.
1887     // See the full descrition in MacroAssembler::biased_locking_exit().
1888     region  = new (C, 4) RegionNode(4);
1889     // create a Phi for the memory state
1890     mem_phi = new (C, 4) PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
1891     mem_phi->init_req(3, mem);
1892 
1893     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
1894     ctrl = opt_bits_test(ctrl, region, 3, mark_node,
1895                          markOopDesc::biased_lock_mask_in_place,
1896                          markOopDesc::biased_lock_pattern);
1897   } else {
1898     region  = new (C, 3) RegionNode(3);
1899     // create a Phi for the memory state
1900     mem_phi = new (C, 3) PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
1901   }
1902 
1903   FastUnlockNode *funlock = new (C, 3) FastUnlockNode( ctrl, obj, box );
1904   funlock = transform_later( funlock )->as_FastUnlock();
1905   // Optimize test; set region slot 2
1906   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
1907 
1908   CallNode *call = make_slow_call( (CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C), "complete_monitor_unlocking_C", slow_path, obj, box );
1909 
1910   extract_call_projections(call);
1911 
1912   assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
1913            _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
1914 
1915   // No exceptions for unlocking
1916   // Capture slow path
1917   // disconnect fall-through projection from call and create a new one
1918   // hook up users of fall-through projection to region
1919   Node *slow_ctrl = _fallthroughproj->clone();
1920   transform_later(slow_ctrl);
1921   _igvn.hash_delete(_fallthroughproj);
1922   _fallthroughproj->disconnect_inputs(NULL);
1923   region->init_req(1, slow_ctrl);
1924   // region inputs are now complete
1925   transform_later(region);
1926   _igvn.subsume_node(_fallthroughproj, region);
1927 
1928   Node *memproj = transform_later( new(C, 1) ProjNode(call, TypeFunc::Memory) );
1929   mem_phi->init_req(1, memproj );
1930   mem_phi->init_req(2, mem);
1931   transform_later(mem_phi);
1932   _igvn.hash_delete(_memproj_fallthrough);
1933   _igvn.subsume_node(_memproj_fallthrough, mem_phi);
1934 }
1935 
1936 //------------------------------expand_macro_nodes----------------------
1937 //  Returns true if a failure occurred.
1938 bool PhaseMacroExpand::expand_macro_nodes() {
1939   if (C->macro_count() == 0)
1940     return false;
1941   // First, attempt to eliminate locks
1942   bool progress = true;
1943   while (progress) {
1944     progress = false;
1945     for (int i = C->macro_count(); i > 0; i--) {
1946       Node * n = C->macro_node(i-1);
1947       bool success = false;
1948       debug_only(int old_macro_count = C->macro_count(););
1949       if (n->is_AbstractLock()) {
1950         success = eliminate_locking_node(n->as_AbstractLock());
1951       } else if (n->Opcode() == Op_Opaque1 || n->Opcode() == Op_Opaque2) {
1952         _igvn.add_users_to_worklist(n);
1953         _igvn.hash_delete(n);
1954         _igvn.subsume_node(n, n->in(1));
1955         success = true;
1956       }
1957       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
1958       progress = progress || success;
1959     }
1960   }
1961   // Next, attempt to eliminate allocations
1962   progress = true;
1963   while (progress) {
1964     progress = false;
1965     for (int i = C->macro_count(); i > 0; i--) {
1966       Node * n = C->macro_node(i-1);
1967       bool success = false;
1968       debug_only(int old_macro_count = C->macro_count(););
1969       switch (n->class_id()) {
1970       case Node::Class_Allocate:
1971       case Node::Class_AllocateArray:
1972         success = eliminate_allocate_node(n->as_Allocate());
1973         break;
1974       case Node::Class_Lock:
1975       case Node::Class_Unlock:
1976         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
1977         break;
1978       default:
1979         assert(false, "unknown node type in macro list");
1980       }
1981       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
1982       progress = progress || success;
1983     }
1984   }
1985   // Make sure expansion will not cause node limit to be exceeded.
1986   // Worst case is a macro node gets expanded into about 50 nodes.
1987   // Allow 50% more for optimization.
1988   if (C->check_node_count(C->macro_count() * 75, "out of nodes before macro expansion" ) )
1989     return true;
1990 
1991   // expand "macro" nodes
1992   // nodes are removed from the macro list as they are processed
1993   while (C->macro_count() > 0) {
1994     int macro_count = C->macro_count();
1995     Node * n = C->macro_node(macro_count-1);
1996     assert(n->is_macro(), "only macro nodes expected here");
1997     if (_igvn.type(n) == Type::TOP || n->in(0)->is_top() ) {
1998       // node is unreachable, so don't try to expand it
1999       C->remove_macro_node(n);
2000       continue;
2001     }
2002     switch (n->class_id()) {
2003     case Node::Class_Allocate:
2004       expand_allocate(n->as_Allocate());
2005       break;
2006     case Node::Class_AllocateArray:
2007       expand_allocate_array(n->as_AllocateArray());
2008       break;
2009     case Node::Class_Lock:
2010       expand_lock_node(n->as_Lock());
2011       break;
2012     case Node::Class_Unlock:
2013       expand_unlock_node(n->as_Unlock());
2014       break;
2015     default:
2016       assert(false, "unknown node type in macro list");
2017     }
2018     assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2019     if (C->failing())  return true;
2020   }
2021 
2022   _igvn.set_delay_transform(false);
2023   _igvn.optimize();
2024   return false;
2025 }