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