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