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