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