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   }
1567 
1568   // Copy debug information and adjust JVMState information, then replace
1569   // allocate node with the call
1570   call->copy_call_debug_info(&_igvn, alloc);
1571   if (!always_slow) {
1572     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1573   } else {
1574     // Hook i_o projection to avoid its elimination during allocation
1575     // replacement (when only a slow call is generated).
1576     call->set_req(TypeFunc::I_O, result_phi_i_o);
1577   }
1578   _igvn.replace_node(alloc, call);
1579   transform_later(call);
1580 
1581   // Identify the output projections from the allocate node and
1582   // adjust any references to them.
1583   // The control and io projections look like:
1584   //
1585   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1586   //  Allocate                   Catch
1587   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1588   //
1589   //  We are interested in the CatchProj nodes.
1590   //
1591   extract_call_projections(call);
1592 
1593   // An allocate node has separate memory projections for the uses on
1594   // the control and i_o paths. Replace the control memory projection with
1595   // result_phi_rawmem (unless we are only generating a slow call when
1596   // both memory projections are combined)
1597   if (!always_slow && _memproj_fallthrough != NULL) {
1598     for (DUIterator_Fast imax, i = _memproj_fallthrough->fast_outs(imax); i < imax; i++) {
1599       Node *use = _memproj_fallthrough->fast_out(i);
1600       _igvn.rehash_node_delayed(use);
1601       imax -= replace_input(use, _memproj_fallthrough, result_phi_rawmem);
1602       // back up iterator
1603       --i;
1604     }
1605   }
1606   // Now change uses of _memproj_catchall to use _memproj_fallthrough and delete
1607   // _memproj_catchall so we end up with a call that has only 1 memory projection.
1608   if (_memproj_catchall != NULL ) {
1609     if (_memproj_fallthrough == NULL) {
1610       _memproj_fallthrough = new ProjNode(call, TypeFunc::Memory);
1611       transform_later(_memproj_fallthrough);
1612     }
1613     for (DUIterator_Fast imax, i = _memproj_catchall->fast_outs(imax); i < imax; i++) {
1614       Node *use = _memproj_catchall->fast_out(i);
1615       _igvn.rehash_node_delayed(use);
1616       imax -= replace_input(use, _memproj_catchall, _memproj_fallthrough);
1617       // back up iterator
1618       --i;
1619     }
1620     assert(_memproj_catchall->outcnt() == 0, "all uses must be deleted");
1621     _igvn.remove_dead_node(_memproj_catchall);
1622   }
1623 
1624   // An allocate node has separate i_o projections for the uses on the control
1625   // and i_o paths. Always replace the control i_o projection with result i_o
1626   // otherwise incoming i_o become dead when only a slow call is generated
1627   // (it is different from memory projections where both projections are
1628   // combined in such case).
1629   if (_ioproj_fallthrough != NULL) {
1630     for (DUIterator_Fast imax, i = _ioproj_fallthrough->fast_outs(imax); i < imax; i++) {
1631       Node *use = _ioproj_fallthrough->fast_out(i);
1632       _igvn.rehash_node_delayed(use);
1633       imax -= replace_input(use, _ioproj_fallthrough, result_phi_i_o);
1634       // back up iterator
1635       --i;
1636     }
1637   }
1638   // Now change uses of _ioproj_catchall to use _ioproj_fallthrough and delete
1639   // _ioproj_catchall so we end up with a call that has only 1 i_o projection.
1640   if (_ioproj_catchall != NULL ) {
1641     if (_ioproj_fallthrough == NULL) {
1642       _ioproj_fallthrough = new ProjNode(call, TypeFunc::I_O);
1643       transform_later(_ioproj_fallthrough);
1644     }
1645     for (DUIterator_Fast imax, i = _ioproj_catchall->fast_outs(imax); i < imax; i++) {
1646       Node *use = _ioproj_catchall->fast_out(i);
1647       _igvn.rehash_node_delayed(use);
1648       imax -= replace_input(use, _ioproj_catchall, _ioproj_fallthrough);
1649       // back up iterator
1650       --i;
1651     }
1652     assert(_ioproj_catchall->outcnt() == 0, "all uses must be deleted");
1653     _igvn.remove_dead_node(_ioproj_catchall);
1654   }
1655 
1656   // if we generated only a slow call, we are done
1657   if (always_slow) {
1658     // Now we can unhook i_o.
1659     if (result_phi_i_o->outcnt() > 1) {
1660       call->set_req(TypeFunc::I_O, top());
1661     } else {
1662       assert(result_phi_i_o->unique_ctrl_out() == call, "");
1663       // Case of new array with negative size known during compilation.
1664       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1665       // following code since call to runtime will throw exception.
1666       // As result there will be no users of i_o after the call.
1667       // Leave i_o attached to this call to avoid problems in preceding graph.
1668     }
1669     return;
1670   }
1671 
1672   if (_fallthroughcatchproj != NULL) {
1673     ctrl = _fallthroughcatchproj->clone();
1674     transform_later(ctrl);
1675     _igvn.replace_node(_fallthroughcatchproj, result_region);
1676   } else {
1677     ctrl = top();
1678   }
1679   Node *slow_result;
1680   if (_resproj == NULL) {
1681     // no uses of the allocation result
1682     slow_result = top();
1683   } else {
1684     slow_result = _resproj->clone();
1685     transform_later(slow_result);
1686     _igvn.replace_node(_resproj, result_phi_rawoop);
1687   }
1688 
1689   // Plug slow-path into result merge point
1690   result_region    ->init_req( slow_result_path, ctrl );
1691   result_phi_rawoop->init_req( slow_result_path, slow_result);
1692   result_phi_rawmem->init_req( slow_result_path, _memproj_fallthrough );
1693   transform_later(result_region);
1694   transform_later(result_phi_rawoop);
1695   transform_later(result_phi_rawmem);
1696   transform_later(result_phi_i_o);
1697   // This completes all paths into the result merge point
1698 }
1699 
1700 
1701 // Helper for PhaseMacroExpand::expand_allocate_common.
1702 // Initializes the newly-allocated storage.
1703 Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1704                                           Node* control, Node* rawmem, Node* object,
1705                                           Node* klass_node, Node* length,
1706                                           Node* size_in_bytes) {
1707   InitializeNode* init = alloc->initialization();
1708   // Store the klass & mark bits
1709   Node* mark_node = alloc->make_ideal_mark(&_igvn, object, control, rawmem);
1710   if (!mark_node->is_Con()) {
1711     transform_later(mark_node);
1712   }
1713   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1714 
1715   BasicType bt = T_METADATA;
1716   Node* metadata = klass_node;
1717   Node* properties = alloc->in(AllocateNode::StorageProperties);
1718   if (properties != NULL) {
1719     // Encode array storage properties into klass pointer
1720     assert(EnableValhalla, "array storage properties not supported");
1721     if (UseCompressedClassPointers) {
1722       // Compress the klass pointer before inserting the storage properties value
1723       metadata = transform_later(new EncodePKlassNode(metadata, metadata->bottom_type()->make_narrowklass()));
1724       metadata = transform_later(new CastN2INode(metadata));
1725       metadata = transform_later(new OrINode(metadata, transform_later(new ConvL2INode(properties))));
1726       bt = T_INT;
1727     } else {
1728       metadata = transform_later(new CastP2XNode(NULL, metadata));
1729       metadata = transform_later(new OrXNode(metadata, properties));
1730       bt = T_LONG;
1731     }
1732   }
1733   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), metadata, bt);
1734 
1735   int header_size = alloc->minimum_header_size();  // conservatively small
1736 
1737   // Array length
1738   if (length != NULL) {         // Arrays need length field
1739     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1740     // conservatively small header size:
1741     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1742     ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1743     if (k->is_array_klass())    // we know the exact header size in most cases:
1744       header_size = Klass::layout_helper_header_size(k->layout_helper());
1745   }
1746 
1747   // Clear the object body, if necessary.
1748   if (init == NULL) {
1749     // The init has somehow disappeared; be cautious and clear everything.
1750     //
1751     // This can happen if a node is allocated but an uncommon trap occurs
1752     // immediately.  In this case, the Initialize gets associated with the
1753     // trap, and may be placed in a different (outer) loop, if the Allocate
1754     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1755     // there can be two Allocates to one Initialize.  The answer in all these
1756     // edge cases is safety first.  It is always safe to clear immediately
1757     // within an Allocate, and then (maybe or maybe not) clear some more later.
1758     if (!(UseTLAB && ZeroTLAB)) {
1759       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1760                                             alloc->in(AllocateNode::DefaultValue),
1761                                             alloc->in(AllocateNode::RawDefaultValue),
1762                                             header_size, size_in_bytes,
1763                                             &_igvn);
1764     }
1765   } else {
1766     if (!init->is_complete()) {
1767       // Try to win by zeroing only what the init does not store.
1768       // We can also try to do some peephole optimizations,
1769       // such as combining some adjacent subword stores.
1770       rawmem = init->complete_stores(control, rawmem, object,
1771                                      header_size, size_in_bytes, &_igvn);
1772     }
1773     // We have no more use for this link, since the AllocateNode goes away:
1774     init->set_req(InitializeNode::RawAddress, top());
1775     // (If we keep the link, it just confuses the register allocator,
1776     // who thinks he sees a real use of the address by the membar.)
1777   }
1778 
1779   return rawmem;
1780 }
1781 
1782 // Generate prefetch instructions for next allocations.
1783 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
1784                                         Node*& contended_phi_rawmem,
1785                                         Node* old_eden_top, Node* new_eden_top,
1786                                         intx lines) {
1787    enum { fall_in_path = 1, pf_path = 2 };
1788    if( UseTLAB && AllocatePrefetchStyle == 2 ) {
1789       // Generate prefetch allocation with watermark check.
1790       // As an allocation hits the watermark, we will prefetch starting
1791       // at a "distance" away from watermark.
1792 
1793       Node *pf_region = new RegionNode(3);
1794       Node *pf_phi_rawmem = new PhiNode( pf_region, Type::MEMORY,
1795                                                 TypeRawPtr::BOTTOM );
1796       // I/O is used for Prefetch
1797       Node *pf_phi_abio = new PhiNode( pf_region, Type::ABIO );
1798 
1799       Node *thread = new ThreadLocalNode();
1800       transform_later(thread);
1801 
1802       Node *eden_pf_adr = new AddPNode( top()/*not oop*/, thread,
1803                    _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) );
1804       transform_later(eden_pf_adr);
1805 
1806       Node *old_pf_wm = new LoadPNode(needgc_false,
1807                                    contended_phi_rawmem, eden_pf_adr,
1808                                    TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM,
1809                                    MemNode::unordered);
1810       transform_later(old_pf_wm);
1811 
1812       // check against new_eden_top
1813       Node *need_pf_cmp = new CmpPNode( new_eden_top, old_pf_wm );
1814       transform_later(need_pf_cmp);
1815       Node *need_pf_bol = new BoolNode( need_pf_cmp, BoolTest::ge );
1816       transform_later(need_pf_bol);
1817       IfNode *need_pf_iff = new IfNode( needgc_false, need_pf_bol,
1818                                        PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
1819       transform_later(need_pf_iff);
1820 
1821       // true node, add prefetchdistance
1822       Node *need_pf_true = new IfTrueNode( need_pf_iff );
1823       transform_later(need_pf_true);
1824 
1825       Node *need_pf_false = new IfFalseNode( need_pf_iff );
1826       transform_later(need_pf_false);
1827 
1828       Node *new_pf_wmt = new AddPNode( top(), old_pf_wm,
1829                                     _igvn.MakeConX(AllocatePrefetchDistance) );
1830       transform_later(new_pf_wmt );
1831       new_pf_wmt->set_req(0, need_pf_true);
1832 
1833       Node *store_new_wmt = new StorePNode(need_pf_true,
1834                                        contended_phi_rawmem, eden_pf_adr,
1835                                        TypeRawPtr::BOTTOM, new_pf_wmt,
1836                                        MemNode::unordered);
1837       transform_later(store_new_wmt);
1838 
1839       // adding prefetches
1840       pf_phi_abio->init_req( fall_in_path, i_o );
1841 
1842       Node *prefetch_adr;
1843       Node *prefetch;
1844       uint step_size = AllocatePrefetchStepSize;
1845       uint distance = 0;
1846 
1847       for ( intx i = 0; i < lines; i++ ) {
1848         prefetch_adr = new AddPNode( old_pf_wm, new_pf_wmt,
1849                                             _igvn.MakeConX(distance) );
1850         transform_later(prefetch_adr);
1851         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1852         transform_later(prefetch);
1853         distance += step_size;
1854         i_o = prefetch;
1855       }
1856       pf_phi_abio->set_req( pf_path, i_o );
1857 
1858       pf_region->init_req( fall_in_path, need_pf_false );
1859       pf_region->init_req( pf_path, need_pf_true );
1860 
1861       pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem );
1862       pf_phi_rawmem->init_req( pf_path, store_new_wmt );
1863 
1864       transform_later(pf_region);
1865       transform_later(pf_phi_rawmem);
1866       transform_later(pf_phi_abio);
1867 
1868       needgc_false = pf_region;
1869       contended_phi_rawmem = pf_phi_rawmem;
1870       i_o = pf_phi_abio;
1871    } else if( UseTLAB && AllocatePrefetchStyle == 3 ) {
1872       // Insert a prefetch instruction for each allocation.
1873       // This code is used to generate 1 prefetch instruction per cache line.
1874 
1875       // Generate several prefetch instructions.
1876       uint step_size = AllocatePrefetchStepSize;
1877       uint distance = AllocatePrefetchDistance;
1878 
1879       // Next cache address.
1880       Node *cache_adr = new AddPNode(old_eden_top, old_eden_top,
1881                                      _igvn.MakeConX(step_size + distance));
1882       transform_later(cache_adr);
1883       cache_adr = new CastP2XNode(needgc_false, cache_adr);
1884       transform_later(cache_adr);
1885       // Address is aligned to execute prefetch to the beginning of cache line size
1886       // (it is important when BIS instruction is used on SPARC as prefetch).
1887       Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1));
1888       cache_adr = new AndXNode(cache_adr, mask);
1889       transform_later(cache_adr);
1890       cache_adr = new CastX2PNode(cache_adr);
1891       transform_later(cache_adr);
1892 
1893       // Prefetch
1894       Node *prefetch = new PrefetchAllocationNode( contended_phi_rawmem, cache_adr );
1895       prefetch->set_req(0, needgc_false);
1896       transform_later(prefetch);
1897       contended_phi_rawmem = prefetch;
1898       Node *prefetch_adr;
1899       distance = step_size;
1900       for ( intx i = 1; i < lines; i++ ) {
1901         prefetch_adr = new AddPNode( cache_adr, cache_adr,
1902                                             _igvn.MakeConX(distance) );
1903         transform_later(prefetch_adr);
1904         prefetch = new PrefetchAllocationNode( contended_phi_rawmem, prefetch_adr );
1905         transform_later(prefetch);
1906         distance += step_size;
1907         contended_phi_rawmem = prefetch;
1908       }
1909    } else if( AllocatePrefetchStyle > 0 ) {
1910       // Insert a prefetch for each allocation only on the fast-path
1911       Node *prefetch_adr;
1912       Node *prefetch;
1913       // Generate several prefetch instructions.
1914       uint step_size = AllocatePrefetchStepSize;
1915       uint distance = AllocatePrefetchDistance;
1916       for ( intx i = 0; i < lines; i++ ) {
1917         prefetch_adr = new AddPNode( old_eden_top, new_eden_top,
1918                                             _igvn.MakeConX(distance) );
1919         transform_later(prefetch_adr);
1920         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1921         // Do not let it float too high, since if eden_top == eden_end,
1922         // both might be null.
1923         if( i == 0 ) { // Set control for first prefetch, next follows it
1924           prefetch->init_req(0, needgc_false);
1925         }
1926         transform_later(prefetch);
1927         distance += step_size;
1928         i_o = prefetch;
1929       }
1930    }
1931    return i_o;
1932 }
1933 
1934 
1935 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
1936   expand_allocate_common(alloc, NULL,
1937                          OptoRuntime::new_instance_Type(),
1938                          OptoRuntime::new_instance_Java());
1939 }
1940 
1941 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
1942   Node* length = alloc->in(AllocateNode::ALength);
1943   InitializeNode* init = alloc->initialization();
1944   Node* klass_node = alloc->in(AllocateNode::KlassNode);
1945   ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1946   address slow_call_address;  // Address of slow call
1947   if (init != NULL && init->is_complete_with_arraycopy() &&
1948       k->is_type_array_klass()) {
1949     // Don't zero type array during slow allocation in VM since
1950     // it will be initialized later by arraycopy in compiled code.
1951     slow_call_address = OptoRuntime::new_array_nozero_Java();
1952   } else {
1953     slow_call_address = OptoRuntime::new_array_Java();
1954   }
1955   expand_allocate_common(alloc, length,
1956                          OptoRuntime::new_array_Type(),
1957                          slow_call_address);
1958 }
1959 
1960 //-------------------mark_eliminated_box----------------------------------
1961 //
1962 // During EA obj may point to several objects but after few ideal graph
1963 // transformations (CCP) it may point to only one non escaping object
1964 // (but still using phi), corresponding locks and unlocks will be marked
1965 // for elimination. Later obj could be replaced with a new node (new phi)
1966 // and which does not have escape information. And later after some graph
1967 // reshape other locks and unlocks (which were not marked for elimination
1968 // before) are connected to this new obj (phi) but they still will not be
1969 // marked for elimination since new obj has no escape information.
1970 // Mark all associated (same box and obj) lock and unlock nodes for
1971 // elimination if some of them marked already.
1972 void PhaseMacroExpand::mark_eliminated_box(Node* oldbox, Node* obj) {
1973   if (oldbox->as_BoxLock()->is_eliminated())
1974     return; // This BoxLock node was processed already.
1975 
1976   // New implementation (EliminateNestedLocks) has separate BoxLock
1977   // node for each locked region so mark all associated locks/unlocks as
1978   // eliminated even if different objects are referenced in one locked region
1979   // (for example, OSR compilation of nested loop inside locked scope).
1980   if (EliminateNestedLocks ||
1981       oldbox->as_BoxLock()->is_simple_lock_region(NULL, obj)) {
1982     // Box is used only in one lock region. Mark this box as eliminated.
1983     _igvn.hash_delete(oldbox);
1984     oldbox->as_BoxLock()->set_eliminated(); // This changes box's hash value
1985      _igvn.hash_insert(oldbox);
1986 
1987     for (uint i = 0; i < oldbox->outcnt(); i++) {
1988       Node* u = oldbox->raw_out(i);
1989       if (u->is_AbstractLock() && !u->as_AbstractLock()->is_non_esc_obj()) {
1990         AbstractLockNode* alock = u->as_AbstractLock();
1991         // Check lock's box since box could be referenced by Lock's debug info.
1992         if (alock->box_node() == oldbox) {
1993           // Mark eliminated all related locks and unlocks.
1994 #ifdef ASSERT
1995           alock->log_lock_optimization(C, "eliminate_lock_set_non_esc4");
1996 #endif
1997           alock->set_non_esc_obj();
1998         }
1999       }
2000     }
2001     return;
2002   }
2003 
2004   // Create new "eliminated" BoxLock node and use it in monitor debug info
2005   // instead of oldbox for the same object.
2006   BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
2007 
2008   // Note: BoxLock node is marked eliminated only here and it is used
2009   // to indicate that all associated lock and unlock nodes are marked
2010   // for elimination.
2011   newbox->set_eliminated();
2012   transform_later(newbox);
2013 
2014   // Replace old box node with new box for all users of the same object.
2015   for (uint i = 0; i < oldbox->outcnt();) {
2016     bool next_edge = true;
2017 
2018     Node* u = oldbox->raw_out(i);
2019     if (u->is_AbstractLock()) {
2020       AbstractLockNode* alock = u->as_AbstractLock();
2021       if (alock->box_node() == oldbox && alock->obj_node()->eqv_uncast(obj)) {
2022         // Replace Box and mark eliminated all related locks and unlocks.
2023 #ifdef ASSERT
2024         alock->log_lock_optimization(C, "eliminate_lock_set_non_esc5");
2025 #endif
2026         alock->set_non_esc_obj();
2027         _igvn.rehash_node_delayed(alock);
2028         alock->set_box_node(newbox);
2029         next_edge = false;
2030       }
2031     }
2032     if (u->is_FastLock() && u->as_FastLock()->obj_node()->eqv_uncast(obj)) {
2033       FastLockNode* flock = u->as_FastLock();
2034       assert(flock->box_node() == oldbox, "sanity");
2035       _igvn.rehash_node_delayed(flock);
2036       flock->set_box_node(newbox);
2037       next_edge = false;
2038     }
2039 
2040     // Replace old box in monitor debug info.
2041     if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
2042       SafePointNode* sfn = u->as_SafePoint();
2043       JVMState* youngest_jvms = sfn->jvms();
2044       int max_depth = youngest_jvms->depth();
2045       for (int depth = 1; depth <= max_depth; depth++) {
2046         JVMState* jvms = youngest_jvms->of_depth(depth);
2047         int num_mon  = jvms->nof_monitors();
2048         // Loop over monitors
2049         for (int idx = 0; idx < num_mon; idx++) {
2050           Node* obj_node = sfn->monitor_obj(jvms, idx);
2051           Node* box_node = sfn->monitor_box(jvms, idx);
2052           if (box_node == oldbox && obj_node->eqv_uncast(obj)) {
2053             int j = jvms->monitor_box_offset(idx);
2054             _igvn.replace_input_of(u, j, newbox);
2055             next_edge = false;
2056           }
2057         }
2058       }
2059     }
2060     if (next_edge) i++;
2061   }
2062 }
2063 
2064 //-----------------------mark_eliminated_locking_nodes-----------------------
2065 void PhaseMacroExpand::mark_eliminated_locking_nodes(AbstractLockNode *alock) {
2066   if (EliminateNestedLocks) {
2067     if (alock->is_nested()) {
2068        assert(alock->box_node()->as_BoxLock()->is_eliminated(), "sanity");
2069        return;
2070     } else if (!alock->is_non_esc_obj()) { // Not eliminated or coarsened
2071       // Only Lock node has JVMState needed here.
2072       // Not that preceding claim is documented anywhere else.
2073       if (alock->jvms() != NULL) {
2074         if (alock->as_Lock()->is_nested_lock_region()) {
2075           // Mark eliminated related nested locks and unlocks.
2076           Node* obj = alock->obj_node();
2077           BoxLockNode* box_node = alock->box_node()->as_BoxLock();
2078           assert(!box_node->is_eliminated(), "should not be marked yet");
2079           // Note: BoxLock node is marked eliminated only here
2080           // and it is used to indicate that all associated lock
2081           // and unlock nodes are marked for elimination.
2082           box_node->set_eliminated(); // Box's hash is always NO_HASH here
2083           for (uint i = 0; i < box_node->outcnt(); i++) {
2084             Node* u = box_node->raw_out(i);
2085             if (u->is_AbstractLock()) {
2086               alock = u->as_AbstractLock();
2087               if (alock->box_node() == box_node) {
2088                 // Verify that this Box is referenced only by related locks.
2089                 assert(alock->obj_node()->eqv_uncast(obj), "");
2090                 // Mark all related locks and unlocks.
2091 #ifdef ASSERT
2092                 alock->log_lock_optimization(C, "eliminate_lock_set_nested");
2093 #endif
2094                 alock->set_nested();
2095               }
2096             }
2097           }
2098         } else {
2099 #ifdef ASSERT
2100           alock->log_lock_optimization(C, "eliminate_lock_NOT_nested_lock_region");
2101           if (C->log() != NULL)
2102             alock->as_Lock()->is_nested_lock_region(C); // rerun for debugging output
2103 #endif
2104         }
2105       }
2106       return;
2107     }
2108     // Process locks for non escaping object
2109     assert(alock->is_non_esc_obj(), "");
2110   } // EliminateNestedLocks
2111 
2112   if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2113     // Look for all locks of this object and mark them and
2114     // corresponding BoxLock nodes as eliminated.
2115     Node* obj = alock->obj_node();
2116     for (uint j = 0; j < obj->outcnt(); j++) {
2117       Node* o = obj->raw_out(j);
2118       if (o->is_AbstractLock() &&
2119           o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2120         alock = o->as_AbstractLock();
2121         Node* box = alock->box_node();
2122         // Replace old box node with new eliminated box for all users
2123         // of the same object and mark related locks as eliminated.
2124         mark_eliminated_box(box, obj);
2125       }
2126     }
2127   }
2128 }
2129 
2130 // we have determined that this lock/unlock can be eliminated, we simply
2131 // eliminate the node without expanding it.
2132 //
2133 // Note:  The membar's associated with the lock/unlock are currently not
2134 //        eliminated.  This should be investigated as a future enhancement.
2135 //
2136 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2137 
2138   if (!alock->is_eliminated()) {
2139     return false;
2140   }
2141 #ifdef ASSERT
2142   const Type* obj_type = _igvn.type(alock->obj_node());
2143   assert(!obj_type->isa_valuetype() && !obj_type->is_valuetypeptr(), "Eliminating lock on value type");
2144   if (!alock->is_coarsened()) {
2145     // Check that new "eliminated" BoxLock node is created.
2146     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2147     assert(oldbox->is_eliminated(), "should be done already");
2148   }
2149 #endif
2150 
2151   alock->log_lock_optimization(C, "eliminate_lock");
2152 
2153 #ifndef PRODUCT
2154   if (PrintEliminateLocks) {
2155     if (alock->is_Lock()) {
2156       tty->print_cr("++++ Eliminated: %d Lock", alock->_idx);
2157     } else {
2158       tty->print_cr("++++ Eliminated: %d Unlock", alock->_idx);
2159     }
2160   }
2161 #endif
2162 
2163   Node* mem  = alock->in(TypeFunc::Memory);
2164   Node* ctrl = alock->in(TypeFunc::Control);
2165   guarantee(ctrl != NULL, "missing control projection, cannot replace_node() with NULL");
2166 
2167   extract_call_projections(alock);
2168   // There are 2 projections from the lock.  The lock node will
2169   // be deleted when its last use is subsumed below.
2170   assert(alock->outcnt() == 2 &&
2171          _fallthroughproj != NULL &&
2172          _memproj_fallthrough != NULL,
2173          "Unexpected projections from Lock/Unlock");
2174 
2175   Node* fallthroughproj = _fallthroughproj;
2176   Node* memproj_fallthrough = _memproj_fallthrough;
2177 
2178   // The memory projection from a lock/unlock is RawMem
2179   // The input to a Lock is merged memory, so extract its RawMem input
2180   // (unless the MergeMem has been optimized away.)
2181   if (alock->is_Lock()) {
2182     // Seach for MemBarAcquireLock node and delete it also.
2183     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2184     assert(membar != NULL && membar->Opcode() == Op_MemBarAcquireLock, "");
2185     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2186     Node* memproj = membar->proj_out(TypeFunc::Memory);
2187     _igvn.replace_node(ctrlproj, fallthroughproj);
2188     _igvn.replace_node(memproj, memproj_fallthrough);
2189 
2190     // Delete FastLock node also if this Lock node is unique user
2191     // (a loop peeling may clone a Lock node).
2192     Node* flock = alock->as_Lock()->fastlock_node();
2193     if (flock->outcnt() == 1) {
2194       assert(flock->unique_out() == alock, "sanity");
2195       _igvn.replace_node(flock, top());
2196     }
2197   }
2198 
2199   // Seach for MemBarReleaseLock node and delete it also.
2200   if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2201     MemBarNode* membar = ctrl->in(0)->as_MemBar();
2202     assert(membar->Opcode() == Op_MemBarReleaseLock &&
2203            mem->is_Proj() && membar == mem->in(0), "");
2204     _igvn.replace_node(fallthroughproj, ctrl);
2205     _igvn.replace_node(memproj_fallthrough, mem);
2206     fallthroughproj = ctrl;
2207     memproj_fallthrough = mem;
2208     ctrl = membar->in(TypeFunc::Control);
2209     mem  = membar->in(TypeFunc::Memory);
2210   }
2211 
2212   _igvn.replace_node(fallthroughproj, ctrl);
2213   _igvn.replace_node(memproj_fallthrough, mem);
2214   return true;
2215 }
2216 
2217 
2218 //------------------------------expand_lock_node----------------------
2219 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
2220 
2221   Node* ctrl = lock->in(TypeFunc::Control);
2222   Node* mem = lock->in(TypeFunc::Memory);
2223   Node* obj = lock->obj_node();
2224   Node* box = lock->box_node();
2225   Node* flock = lock->fastlock_node();
2226 
2227   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2228 
2229   // Make the merge point
2230   Node *region;
2231   Node *mem_phi;
2232   Node *slow_path;
2233 
2234   if (UseOptoBiasInlining) {
2235     /*
2236      *  See the full description in MacroAssembler::biased_locking_enter().
2237      *
2238      *  if( (mark_word & biased_lock_mask) == biased_lock_pattern ) {
2239      *    // The object is biased.
2240      *    proto_node = klass->prototype_header;
2241      *    o_node = thread | proto_node;
2242      *    x_node = o_node ^ mark_word;
2243      *    if( (x_node & ~age_mask) == 0 ) { // Biased to the current thread ?
2244      *      // Done.
2245      *    } else {
2246      *      if( (x_node & biased_lock_mask) != 0 ) {
2247      *        // The klass's prototype header is no longer biased.
2248      *        cas(&mark_word, mark_word, proto_node)
2249      *        goto cas_lock;
2250      *      } else {
2251      *        // The klass's prototype header is still biased.
2252      *        if( (x_node & epoch_mask) != 0 ) { // Expired epoch?
2253      *          old = mark_word;
2254      *          new = o_node;
2255      *        } else {
2256      *          // Different thread or anonymous biased.
2257      *          old = mark_word & (epoch_mask | age_mask | biased_lock_mask);
2258      *          new = thread | old;
2259      *        }
2260      *        // Try to rebias.
2261      *        if( cas(&mark_word, old, new) == 0 ) {
2262      *          // Done.
2263      *        } else {
2264      *          goto slow_path; // Failed.
2265      *        }
2266      *      }
2267      *    }
2268      *  } else {
2269      *    // The object is not biased.
2270      *    cas_lock:
2271      *    if( FastLock(obj) == 0 ) {
2272      *      // Done.
2273      *    } else {
2274      *      slow_path:
2275      *      OptoRuntime::complete_monitor_locking_Java(obj);
2276      *    }
2277      *  }
2278      */
2279 
2280     region  = new RegionNode(5);
2281     // create a Phi for the memory state
2282     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2283 
2284     Node* fast_lock_region  = new RegionNode(3);
2285     Node* fast_lock_mem_phi = new PhiNode( fast_lock_region, Type::MEMORY, TypeRawPtr::BOTTOM);
2286 
2287     // First, check mark word for the biased lock pattern.
2288     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2289 
2290     // Get fast path - mark word has the biased lock pattern.
2291     ctrl = opt_bits_test(ctrl, fast_lock_region, 1, mark_node,
2292                          markWord::biased_lock_mask_in_place,
2293                          markWord::biased_lock_pattern, true);
2294     // fast_lock_region->in(1) is set to slow path.
2295     fast_lock_mem_phi->init_req(1, mem);
2296 
2297     // Now check that the lock is biased to the current thread and has
2298     // the same epoch and bias as Klass::_prototype_header.
2299 
2300     // Special-case a fresh allocation to avoid building nodes:
2301     Node* klass_node = AllocateNode::Ideal_klass(obj, &_igvn);
2302     if (klass_node == NULL) {
2303       Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
2304       klass_node = transform_later(LoadKlassNode::make(_igvn, NULL, mem, k_adr, _igvn.type(k_adr)->is_ptr()));
2305 #ifdef _LP64
2306       if (UseCompressedClassPointers && klass_node->is_DecodeNKlass()) {
2307         assert(klass_node->in(1)->Opcode() == Op_LoadNKlass, "sanity");
2308         klass_node->in(1)->init_req(0, ctrl);
2309       } else
2310 #endif
2311       klass_node->init_req(0, ctrl);
2312     }
2313     Node *proto_node = make_load(ctrl, mem, klass_node, in_bytes(Klass::prototype_header_offset()), TypeX_X, TypeX_X->basic_type());
2314 
2315     Node* thread = transform_later(new ThreadLocalNode());
2316     Node* cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2317     Node* o_node = transform_later(new OrXNode(cast_thread, proto_node));
2318     Node* x_node = transform_later(new XorXNode(o_node, mark_node));
2319 
2320     // Get slow path - mark word does NOT match the value.
2321     STATIC_ASSERT(markWord::age_mask_in_place <= INT_MAX);
2322     Node* not_biased_ctrl =  opt_bits_test(ctrl, region, 3, x_node,
2323                                       (~(int)markWord::age_mask_in_place), 0);
2324     // region->in(3) is set to fast path - the object is biased to the current thread.
2325     mem_phi->init_req(3, mem);
2326 
2327 
2328     // Mark word does NOT match the value (thread | Klass::_prototype_header).
2329 
2330 
2331     // First, check biased pattern.
2332     // Get fast path - _prototype_header has the same biased lock pattern.
2333     ctrl =  opt_bits_test(not_biased_ctrl, fast_lock_region, 2, x_node,
2334                           markWord::biased_lock_mask_in_place, 0, true);
2335 
2336     not_biased_ctrl = fast_lock_region->in(2); // Slow path
2337     // fast_lock_region->in(2) - the prototype header is no longer biased
2338     // and we have to revoke the bias on this object.
2339     // We are going to try to reset the mark of this object to the prototype
2340     // value and fall through to the CAS-based locking scheme.
2341     Node* adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
2342     Node* cas = new StoreXConditionalNode(not_biased_ctrl, mem, adr,
2343                                           proto_node, mark_node);
2344     transform_later(cas);
2345     Node* proj = transform_later(new SCMemProjNode(cas));
2346     fast_lock_mem_phi->init_req(2, proj);
2347 
2348 
2349     // Second, check epoch bits.
2350     Node* rebiased_region  = new RegionNode(3);
2351     Node* old_phi = new PhiNode( rebiased_region, TypeX_X);
2352     Node* new_phi = new PhiNode( rebiased_region, TypeX_X);
2353 
2354     // Get slow path - mark word does NOT match epoch bits.
2355     Node* epoch_ctrl =  opt_bits_test(ctrl, rebiased_region, 1, x_node,
2356                                       markWord::epoch_mask_in_place, 0);
2357     // The epoch of the current bias is not valid, attempt to rebias the object
2358     // toward the current thread.
2359     rebiased_region->init_req(2, epoch_ctrl);
2360     old_phi->init_req(2, mark_node);
2361     new_phi->init_req(2, o_node);
2362 
2363     // rebiased_region->in(1) is set to fast path.
2364     // The epoch of the current bias is still valid but we know
2365     // nothing about the owner; it might be set or it might be clear.
2366     Node* cmask   = MakeConX(markWord::biased_lock_mask_in_place |
2367                              markWord::age_mask_in_place |
2368                              markWord::epoch_mask_in_place);
2369     Node* old = transform_later(new AndXNode(mark_node, cmask));
2370     cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2371     Node* new_mark = transform_later(new OrXNode(cast_thread, old));
2372     old_phi->init_req(1, old);
2373     new_phi->init_req(1, new_mark);
2374 
2375     transform_later(rebiased_region);
2376     transform_later(old_phi);
2377     transform_later(new_phi);
2378 
2379     // Try to acquire the bias of the object using an atomic operation.
2380     // If this fails we will go in to the runtime to revoke the object's bias.
2381     cas = new StoreXConditionalNode(rebiased_region, mem, adr, new_phi, old_phi);
2382     transform_later(cas);
2383     proj = transform_later(new SCMemProjNode(cas));
2384 
2385     // Get slow path - Failed to CAS.
2386     not_biased_ctrl = opt_bits_test(rebiased_region, region, 4, cas, 0, 0);
2387     mem_phi->init_req(4, proj);
2388     // region->in(4) is set to fast path - the object is rebiased to the current thread.
2389 
2390     // Failed to CAS.
2391     slow_path  = new RegionNode(3);
2392     Node *slow_mem = new PhiNode( slow_path, Type::MEMORY, TypeRawPtr::BOTTOM);
2393 
2394     slow_path->init_req(1, not_biased_ctrl); // Capture slow-control
2395     slow_mem->init_req(1, proj);
2396 
2397     // Call CAS-based locking scheme (FastLock node).
2398 
2399     transform_later(fast_lock_region);
2400     transform_later(fast_lock_mem_phi);
2401 
2402     // Get slow path - FastLock failed to lock the object.
2403     ctrl = opt_bits_test(fast_lock_region, region, 2, flock, 0, 0);
2404     mem_phi->init_req(2, fast_lock_mem_phi);
2405     // region->in(2) is set to fast path - the object is locked to the current thread.
2406 
2407     slow_path->init_req(2, ctrl); // Capture slow-control
2408     slow_mem->init_req(2, fast_lock_mem_phi);
2409 
2410     transform_later(slow_path);
2411     transform_later(slow_mem);
2412     // Reset lock's memory edge.
2413     lock->set_req(TypeFunc::Memory, slow_mem);
2414 
2415   } else {
2416     region  = new RegionNode(3);
2417     // create a Phi for the memory state
2418     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2419 
2420     // Optimize test; set region slot 2
2421     slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2422     mem_phi->init_req(2, mem);
2423   }
2424 
2425   const TypeOopPtr* objptr = _igvn.type(obj)->make_oopptr();
2426   if (objptr->can_be_value_type()) {
2427     // Deoptimize and re-execute if a value
2428     assert(EnableValhalla, "should only be used if value types are enabled");
2429     Node* mark = make_load(slow_path, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2430     Node* value_mask = _igvn.MakeConX(markWord::always_locked_pattern);
2431     Node* is_value = _igvn.transform(new AndXNode(mark, value_mask));
2432     Node* cmp = _igvn.transform(new CmpXNode(is_value, value_mask));
2433     Node* bol = _igvn.transform(new BoolNode(cmp, BoolTest::eq));
2434     Node* unc_ctrl = generate_slow_guard(&slow_path, bol, NULL);
2435 
2436     int trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_class_check, Deoptimization::Action_none);
2437     address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
2438     const TypePtr* no_memory_effects = NULL;
2439     JVMState* jvms = lock->jvms();
2440     CallNode* unc = new CallStaticJavaNode(OptoRuntime::uncommon_trap_Type(), call_addr, "uncommon_trap",
2441                                            jvms->bci(), no_memory_effects);
2442 
2443     unc->init_req(TypeFunc::Control, unc_ctrl);
2444     unc->init_req(TypeFunc::I_O, lock->i_o());
2445     unc->init_req(TypeFunc::Memory, mem); // may gc ptrs
2446     unc->init_req(TypeFunc::FramePtr,  lock->in(TypeFunc::FramePtr));
2447     unc->init_req(TypeFunc::ReturnAdr, lock->in(TypeFunc::ReturnAdr));
2448     unc->init_req(TypeFunc::Parms+0, _igvn.intcon(trap_request));
2449     unc->set_cnt(PROB_UNLIKELY_MAG(4));
2450     unc->copy_call_debug_info(&_igvn, lock);
2451 
2452     assert(unc->peek_monitor_box() == box, "wrong monitor");
2453     assert(unc->peek_monitor_obj() == obj, "wrong monitor");
2454 
2455     // pop monitor and push obj back on stack: we trap before the monitorenter
2456     unc->pop_monitor();
2457     unc->grow_stack(unc->jvms(), 1);
2458     unc->set_stack(unc->jvms(), unc->jvms()->stk_size()-1, obj);
2459 
2460     _igvn.register_new_node_with_optimizer(unc);
2461 
2462     Node* ctrl = _igvn.transform(new ProjNode(unc, TypeFunc::Control));
2463     Node* halt = _igvn.transform(new HaltNode(ctrl, lock->in(TypeFunc::FramePtr), "monitor enter on value-type"));
2464     C->root()->add_req(halt);
2465   }
2466 
2467   // Make slow path call
2468   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2469                                   OptoRuntime::complete_monitor_locking_Java(), NULL, slow_path,
2470                                   obj, box, NULL);
2471 
2472   extract_call_projections(call);
2473 
2474   // Slow path can only throw asynchronous exceptions, which are always
2475   // de-opted.  So the compiler thinks the slow-call can never throw an
2476   // exception.  If it DOES throw an exception we would need the debug
2477   // info removed first (since if it throws there is no monitor).
2478   assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
2479            _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
2480 
2481   // Capture slow path
2482   // disconnect fall-through projection from call and create a new one
2483   // hook up users of fall-through projection to region
2484   Node *slow_ctrl = _fallthroughproj->clone();
2485   transform_later(slow_ctrl);
2486   _igvn.hash_delete(_fallthroughproj);
2487   _fallthroughproj->disconnect_inputs(NULL, C);
2488   region->init_req(1, slow_ctrl);
2489   // region inputs are now complete
2490   transform_later(region);
2491   _igvn.replace_node(_fallthroughproj, region);
2492 
2493   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2494   mem_phi->init_req(1, memproj );
2495   transform_later(mem_phi);
2496   _igvn.replace_node(_memproj_fallthrough, mem_phi);
2497 }
2498 
2499 //------------------------------expand_unlock_node----------------------
2500 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2501 
2502   Node* ctrl = unlock->in(TypeFunc::Control);
2503   Node* mem = unlock->in(TypeFunc::Memory);
2504   Node* obj = unlock->obj_node();
2505   Node* box = unlock->box_node();
2506 
2507   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2508 
2509   // No need for a null check on unlock
2510 
2511   // Make the merge point
2512   Node *region;
2513   Node *mem_phi;
2514 
2515   if (UseOptoBiasInlining) {
2516     // Check for biased locking unlock case, which is a no-op.
2517     // See the full description in MacroAssembler::biased_locking_exit().
2518     region  = new RegionNode(4);
2519     // create a Phi for the memory state
2520     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2521     mem_phi->init_req(3, mem);
2522 
2523     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2524     ctrl = opt_bits_test(ctrl, region, 3, mark_node,
2525                          markWord::biased_lock_mask_in_place,
2526                          markWord::biased_lock_pattern);
2527   } else {
2528     region  = new RegionNode(3);
2529     // create a Phi for the memory state
2530     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2531   }
2532 
2533   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2534   funlock = transform_later( funlock )->as_FastUnlock();
2535   // Optimize test; set region slot 2
2536   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2537   Node *thread = transform_later(new ThreadLocalNode());
2538 
2539   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2540                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2541                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2542 
2543   extract_call_projections(call);
2544 
2545   assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
2546            _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
2547 
2548   // No exceptions for unlocking
2549   // Capture slow path
2550   // disconnect fall-through projection from call and create a new one
2551   // hook up users of fall-through projection to region
2552   Node *slow_ctrl = _fallthroughproj->clone();
2553   transform_later(slow_ctrl);
2554   _igvn.hash_delete(_fallthroughproj);
2555   _fallthroughproj->disconnect_inputs(NULL, C);
2556   region->init_req(1, slow_ctrl);
2557   // region inputs are now complete
2558   transform_later(region);
2559   _igvn.replace_node(_fallthroughproj, region);
2560 
2561   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2562   mem_phi->init_req(1, memproj );
2563   mem_phi->init_req(2, mem);
2564   transform_later(mem_phi);
2565   _igvn.replace_node(_memproj_fallthrough, mem_phi);
2566 }
2567 
2568 // A value type might be returned from the call but we don't know its
2569 // type. Either we get a buffered value (and nothing needs to be done)
2570 // or one of the values being returned is the klass of the value type
2571 // and we need to allocate a value type instance of that type and
2572 // initialize it with other values being returned. In that case, we
2573 // first try a fast path allocation and initialize the value with the
2574 // value klass's pack handler or we fall back to a runtime call.
2575 void PhaseMacroExpand::expand_mh_intrinsic_return(CallStaticJavaNode* call) {
2576   assert(call->method()->is_method_handle_intrinsic(), "must be a method handle intrinsic call");
2577   Node* ret = call->proj_out_or_null(TypeFunc::Parms);
2578   if (ret == NULL) {
2579     return;
2580   }
2581   const TypeFunc* tf = call->_tf;
2582   const TypeTuple* domain = OptoRuntime::store_value_type_fields_Type()->domain_cc();
2583   const TypeFunc* new_tf = TypeFunc::make(tf->domain_sig(), tf->domain_cc(), tf->range_sig(), domain);
2584   call->_tf = new_tf;
2585   // Make sure the change of type is applied before projections are processed by igvn
2586   _igvn.set_type(call, call->Value(&_igvn));
2587   _igvn.set_type(ret, ret->Value(&_igvn));
2588 
2589   // Before any new projection is added:
2590   CallProjections* projs = call->extract_projections(true, true);
2591 
2592   Node* ctl = new Node(1);
2593   Node* mem = new Node(1);
2594   Node* io = new Node(1);
2595   Node* ex_ctl = new Node(1);
2596   Node* ex_mem = new Node(1);
2597   Node* ex_io = new Node(1);
2598   Node* res = new Node(1);
2599 
2600   Node* cast = transform_later(new CastP2XNode(ctl, res));
2601   Node* mask = MakeConX(0x1);
2602   Node* masked = transform_later(new AndXNode(cast, mask));
2603   Node* cmp = transform_later(new CmpXNode(masked, mask));
2604   Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
2605   IfNode* allocation_iff = new IfNode(ctl, bol, PROB_MAX, COUNT_UNKNOWN);
2606   transform_later(allocation_iff);
2607   Node* allocation_ctl = transform_later(new IfTrueNode(allocation_iff));
2608   Node* no_allocation_ctl = transform_later(new IfFalseNode(allocation_iff));
2609 
2610   Node* no_allocation_res = transform_later(new CheckCastPPNode(no_allocation_ctl, res, TypeInstPtr::BOTTOM));
2611 
2612   Node* mask2 = MakeConX(-2);
2613   Node* masked2 = transform_later(new AndXNode(cast, mask2));
2614   Node* rawklassptr = transform_later(new CastX2PNode(masked2));
2615   Node* klass_node = transform_later(new CheckCastPPNode(allocation_ctl, rawklassptr, TypeKlassPtr::OBJECT_OR_NULL));
2616 
2617   Node* slowpath_bol = NULL;
2618   Node* top_adr = NULL;
2619   Node* old_top = NULL;
2620   Node* new_top = NULL;
2621   if (UseTLAB) {
2622     Node* end_adr = NULL;
2623     set_eden_pointers(top_adr, end_adr);
2624     Node* end = make_load(ctl, mem, end_adr, 0, TypeRawPtr::BOTTOM, T_ADDRESS);
2625     old_top = new LoadPNode(ctl, mem, top_adr, TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM, MemNode::unordered);
2626     transform_later(old_top);
2627     Node* layout_val = make_load(NULL, mem, klass_node, in_bytes(Klass::layout_helper_offset()), TypeInt::INT, T_INT);
2628     Node* size_in_bytes = ConvI2X(layout_val);
2629     new_top = new AddPNode(top(), old_top, size_in_bytes);
2630     transform_later(new_top);
2631     Node* slowpath_cmp = new CmpPNode(new_top, end);
2632     transform_later(slowpath_cmp);
2633     slowpath_bol = new BoolNode(slowpath_cmp, BoolTest::ge);
2634     transform_later(slowpath_bol);
2635   } else {
2636     slowpath_bol = intcon(1);
2637     top_adr = top();
2638     old_top = top();
2639     new_top = top();
2640   }
2641   IfNode* slowpath_iff = new IfNode(allocation_ctl, slowpath_bol, PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN);
2642   transform_later(slowpath_iff);
2643 
2644   Node* slowpath_true = new IfTrueNode(slowpath_iff);
2645   transform_later(slowpath_true);
2646 
2647   CallStaticJavaNode* slow_call = new CallStaticJavaNode(OptoRuntime::store_value_type_fields_Type(),
2648                                                          StubRoutines::store_value_type_fields_to_buf(),
2649                                                          "store_value_type_fields",
2650                                                          call->jvms()->bci(),
2651                                                          TypePtr::BOTTOM);
2652   slow_call->init_req(TypeFunc::Control, slowpath_true);
2653   slow_call->init_req(TypeFunc::Memory, mem);
2654   slow_call->init_req(TypeFunc::I_O, io);
2655   slow_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2656   slow_call->init_req(TypeFunc::ReturnAdr, call->in(TypeFunc::ReturnAdr));
2657   slow_call->init_req(TypeFunc::Parms, res);
2658 
2659   Node* slow_ctl = transform_later(new ProjNode(slow_call, TypeFunc::Control));
2660   Node* slow_mem = transform_later(new ProjNode(slow_call, TypeFunc::Memory));
2661   Node* slow_io = transform_later(new ProjNode(slow_call, TypeFunc::I_O));
2662   Node* slow_res = transform_later(new ProjNode(slow_call, TypeFunc::Parms));
2663   Node* slow_catc = transform_later(new CatchNode(slow_ctl, slow_io, 2));
2664   Node* slow_norm = transform_later(new CatchProjNode(slow_catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci));
2665   Node* slow_excp = transform_later(new CatchProjNode(slow_catc, CatchProjNode::catch_all_index,    CatchProjNode::no_handler_bci));
2666 
2667   Node* ex_r = new RegionNode(3);
2668   Node* ex_mem_phi = new PhiNode(ex_r, Type::MEMORY, TypePtr::BOTTOM);
2669   Node* ex_io_phi = new PhiNode(ex_r, Type::ABIO);
2670   ex_r->init_req(1, slow_excp);
2671   ex_mem_phi->init_req(1, slow_mem);
2672   ex_io_phi->init_req(1, slow_io);
2673   ex_r->init_req(2, ex_ctl);
2674   ex_mem_phi->init_req(2, ex_mem);
2675   ex_io_phi->init_req(2, ex_io);
2676 
2677   transform_later(ex_r);
2678   transform_later(ex_mem_phi);
2679   transform_later(ex_io_phi);
2680 
2681   Node* slowpath_false = new IfFalseNode(slowpath_iff);
2682   transform_later(slowpath_false);
2683   Node* rawmem = new StorePNode(slowpath_false, mem, top_adr, TypeRawPtr::BOTTOM, new_top, MemNode::unordered);
2684   transform_later(rawmem);
2685   Node* mark_node = makecon(TypeRawPtr::make((address)markWord::always_locked_prototype().value()));
2686   rawmem = make_store(slowpath_false, rawmem, old_top, oopDesc::mark_offset_in_bytes(), mark_node, T_ADDRESS);
2687   rawmem = make_store(slowpath_false, rawmem, old_top, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2688   if (UseCompressedClassPointers) {
2689     rawmem = make_store(slowpath_false, rawmem, old_top, oopDesc::klass_gap_offset_in_bytes(), intcon(0), T_INT);
2690   }
2691   Node* fixed_block  = make_load(slowpath_false, rawmem, klass_node, in_bytes(InstanceKlass::adr_valueklass_fixed_block_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2692   Node* pack_handler = make_load(slowpath_false, rawmem, fixed_block, in_bytes(ValueKlass::pack_handler_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2693 
2694   CallLeafNoFPNode* handler_call = new CallLeafNoFPNode(OptoRuntime::pack_value_type_Type(),
2695                                                         NULL,
2696                                                         "pack handler",
2697                                                         TypeRawPtr::BOTTOM);
2698   handler_call->init_req(TypeFunc::Control, slowpath_false);
2699   handler_call->init_req(TypeFunc::Memory, rawmem);
2700   handler_call->init_req(TypeFunc::I_O, top());
2701   handler_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2702   handler_call->init_req(TypeFunc::ReturnAdr, top());
2703   handler_call->init_req(TypeFunc::Parms, pack_handler);
2704   handler_call->init_req(TypeFunc::Parms+1, old_top);
2705 
2706   // We don't know how many values are returned. This assumes the
2707   // worst case, that all available registers are used.
2708   for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2709     if (domain->field_at(i) == Type::HALF) {
2710       slow_call->init_req(i, top());
2711       handler_call->init_req(i+1, top());
2712       continue;
2713     }
2714     Node* proj = transform_later(new ProjNode(call, i));
2715     slow_call->init_req(i, proj);
2716     handler_call->init_req(i+1, proj);
2717   }
2718 
2719   // We can safepoint at that new call
2720   slow_call->copy_call_debug_info(&_igvn, call);
2721   transform_later(slow_call);
2722   transform_later(handler_call);
2723 
2724   Node* handler_ctl = transform_later(new ProjNode(handler_call, TypeFunc::Control));
2725   rawmem = transform_later(new ProjNode(handler_call, TypeFunc::Memory));
2726   Node* slowpath_false_res = transform_later(new ProjNode(handler_call, TypeFunc::Parms));
2727 
2728   MergeMemNode* slowpath_false_mem = MergeMemNode::make(mem);
2729   slowpath_false_mem->set_memory_at(Compile::AliasIdxRaw, rawmem);
2730   transform_later(slowpath_false_mem);
2731 
2732   Node* r = new RegionNode(4);
2733   Node* mem_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM);
2734   Node* io_phi = new PhiNode(r, Type::ABIO);
2735   Node* res_phi = new PhiNode(r, TypeInstPtr::BOTTOM);
2736 
2737   r->init_req(1, no_allocation_ctl);
2738   mem_phi->init_req(1, mem);
2739   io_phi->init_req(1, io);
2740   res_phi->init_req(1, no_allocation_res);
2741   r->init_req(2, slow_norm);
2742   mem_phi->init_req(2, slow_mem);
2743   io_phi->init_req(2, slow_io);
2744   res_phi->init_req(2, slow_res);
2745   r->init_req(3, handler_ctl);
2746   mem_phi->init_req(3, slowpath_false_mem);
2747   io_phi->init_req(3, io);
2748   res_phi->init_req(3, slowpath_false_res);
2749 
2750   transform_later(r);
2751   transform_later(mem_phi);
2752   transform_later(io_phi);
2753   transform_later(res_phi);
2754 
2755   assert(projs->nb_resproj == 1, "unexpected number of results");
2756   _igvn.replace_in_uses(projs->fallthrough_catchproj, r);
2757   _igvn.replace_in_uses(projs->fallthrough_memproj, mem_phi);
2758   _igvn.replace_in_uses(projs->fallthrough_ioproj, io_phi);
2759   _igvn.replace_in_uses(projs->resproj[0], res_phi);
2760   _igvn.replace_in_uses(projs->catchall_catchproj, ex_r);
2761   _igvn.replace_in_uses(projs->catchall_memproj, ex_mem_phi);
2762   _igvn.replace_in_uses(projs->catchall_ioproj, ex_io_phi);
2763 
2764   _igvn.replace_node(ctl, projs->fallthrough_catchproj);
2765   _igvn.replace_node(mem, projs->fallthrough_memproj);
2766   _igvn.replace_node(io, projs->fallthrough_ioproj);
2767   _igvn.replace_node(res, projs->resproj[0]);
2768   _igvn.replace_node(ex_ctl, projs->catchall_catchproj);
2769   _igvn.replace_node(ex_mem, projs->catchall_memproj);
2770   _igvn.replace_node(ex_io, projs->catchall_ioproj);
2771  }
2772 
2773 //---------------------------eliminate_macro_nodes----------------------
2774 // Eliminate scalar replaced allocations and associated locks.
2775 void PhaseMacroExpand::eliminate_macro_nodes() {
2776   if (C->macro_count() == 0)
2777     return;
2778 
2779   // First, attempt to eliminate locks
2780   int cnt = C->macro_count();
2781   for (int i=0; i < cnt; i++) {
2782     Node *n = C->macro_node(i);
2783     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2784       // Before elimination mark all associated (same box and obj)
2785       // lock and unlock nodes.
2786       mark_eliminated_locking_nodes(n->as_AbstractLock());
2787     }
2788   }
2789   bool progress = true;
2790   while (progress) {
2791     progress = false;
2792     for (int i = C->macro_count(); i > 0; i--) {
2793       Node * n = C->macro_node(i-1);
2794       bool success = false;
2795       debug_only(int old_macro_count = C->macro_count(););
2796       if (n->is_AbstractLock()) {
2797         success = eliminate_locking_node(n->as_AbstractLock());
2798       }
2799       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2800       progress = progress || success;
2801     }
2802   }
2803   // Next, attempt to eliminate allocations
2804   _has_locks = false;
2805   progress = true;
2806   while (progress) {
2807     progress = false;
2808     for (int i = C->macro_count(); i > 0; i--) {
2809       Node * n = C->macro_node(i-1);
2810       bool success = false;
2811       debug_only(int old_macro_count = C->macro_count(););
2812       switch (n->class_id()) {
2813       case Node::Class_Allocate:
2814       case Node::Class_AllocateArray:
2815         success = eliminate_allocate_node(n->as_Allocate());
2816         break;
2817       case Node::Class_CallStaticJava: {
2818         CallStaticJavaNode* call = n->as_CallStaticJava();
2819         if (!call->method()->is_method_handle_intrinsic()) {
2820           success = eliminate_boxing_node(n->as_CallStaticJava());
2821         }
2822         break;
2823       }
2824       case Node::Class_Lock:
2825       case Node::Class_Unlock:
2826         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2827         _has_locks = true;
2828         break;
2829       case Node::Class_ArrayCopy:
2830         break;
2831       case Node::Class_OuterStripMinedLoop:
2832         break;
2833       default:
2834         assert(n->Opcode() == Op_LoopLimit ||
2835                n->Opcode() == Op_Opaque1   ||
2836                n->Opcode() == Op_Opaque2   ||
2837                n->Opcode() == Op_Opaque3   ||
2838                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2839                "unknown node type in macro list");
2840       }
2841       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2842       progress = progress || success;
2843     }
2844   }
2845 }
2846 
2847 //------------------------------expand_macro_nodes----------------------
2848 //  Returns true if a failure occurred.
2849 bool PhaseMacroExpand::expand_macro_nodes() {
2850   // Last attempt to eliminate macro nodes.
2851   eliminate_macro_nodes();
2852 
2853   // Make sure expansion will not cause node limit to be exceeded.
2854   // Worst case is a macro node gets expanded into about 200 nodes.
2855   // Allow 50% more for optimization.
2856   if (C->check_node_count(C->macro_count() * 300, "out of nodes before macro expansion" ) )
2857     return true;
2858 
2859   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2860   bool progress = true;
2861   while (progress) {
2862     progress = false;
2863     for (int i = C->macro_count(); i > 0; i--) {
2864       Node* n = C->macro_node(i-1);
2865       bool success = false;
2866       debug_only(int old_macro_count = C->macro_count(););
2867       if (n->Opcode() == Op_LoopLimit) {
2868         // Remove it from macro list and put on IGVN worklist to optimize.
2869         C->remove_macro_node(n);
2870         _igvn._worklist.push(n);
2871         success = true;
2872       } else if (n->Opcode() == Op_CallStaticJava) {
2873         CallStaticJavaNode* call = n->as_CallStaticJava();
2874         if (!call->method()->is_method_handle_intrinsic()) {
2875           // Remove it from macro list and put on IGVN worklist to optimize.
2876           C->remove_macro_node(n);
2877           _igvn._worklist.push(n);
2878           success = true;
2879         }
2880       } else if (n->Opcode() == Op_Opaque1 || n->Opcode() == Op_Opaque2) {
2881         _igvn.replace_node(n, n->in(1));
2882         success = true;
2883 #if INCLUDE_RTM_OPT
2884       } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2885         assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2886         assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2887         Node* cmp = n->unique_out();
2888 #ifdef ASSERT
2889         // Validate graph.
2890         assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2891         BoolNode* bol = cmp->unique_out()->as_Bool();
2892         assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2893                (bol->_test._test == BoolTest::ne), "");
2894         IfNode* ifn = bol->unique_out()->as_If();
2895         assert((ifn->outcnt() == 2) &&
2896                ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != NULL, "");
2897 #endif
2898         Node* repl = n->in(1);
2899         if (!_has_locks) {
2900           // Remove RTM state check if there are no locks in the code.
2901           // Replace input to compare the same value.
2902           repl = (cmp->in(1) == n) ? cmp->in(2) : cmp->in(1);
2903         }
2904         _igvn.replace_node(n, repl);
2905         success = true;
2906 #endif
2907       } else if (n->Opcode() == Op_OuterStripMinedLoop) {
2908         n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
2909         C->remove_macro_node(n);
2910         success = true;
2911       }
2912       assert(!success || (C->macro_count() == (old_macro_count - 1)), "elimination must have deleted one node from macro list");
2913       progress = progress || success;
2914     }
2915   }
2916 
2917   // expand arraycopy "macro" nodes first
2918   // For ReduceBulkZeroing, we must first process all arraycopy nodes
2919   // before the allocate nodes are expanded.
2920   for (int i = C->macro_count(); i > 0; i--) {
2921     Node* n = C->macro_node(i-1);
2922     assert(n->is_macro(), "only macro nodes expected here");
2923     if (_igvn.type(n) == Type::TOP || (n->in(0) != NULL && n->in(0)->is_top())) {
2924       // node is unreachable, so don't try to expand it
2925       C->remove_macro_node(n);
2926       continue;
2927     }
2928     debug_only(int old_macro_count = C->macro_count(););
2929     switch (n->class_id()) {
2930     case Node::Class_Lock:
2931       expand_lock_node(n->as_Lock());
2932       assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2933       break;
2934     case Node::Class_Unlock:
2935       expand_unlock_node(n->as_Unlock());
2936       assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2937       break;
2938     case Node::Class_ArrayCopy:
2939       expand_arraycopy_node(n->as_ArrayCopy());
2940       assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2941       break;
2942     }
2943     if (C->failing())  return true;
2944   }
2945 
2946   // All nodes except Allocate nodes are expanded now. There could be
2947   // new optimization opportunities (such as folding newly created
2948   // load from a just allocated object). Run IGVN.
2949   _igvn.set_delay_transform(false);
2950   _igvn.optimize();
2951   if (C->failing())  return true;
2952 
2953   _igvn.set_delay_transform(true);
2954 
2955   // expand "macro" nodes
2956   // nodes are removed from the macro list as they are processed
2957   while (C->macro_count() > 0) {
2958     int macro_count = C->macro_count();
2959     Node * n = C->macro_node(macro_count-1);
2960     assert(n->is_macro(), "only macro nodes expected here");
2961     if (_igvn.type(n) == Type::TOP || (n->in(0) != NULL && n->in(0)->is_top())) {
2962       // node is unreachable, so don't try to expand it
2963       C->remove_macro_node(n);
2964       continue;
2965     }
2966     switch (n->class_id()) {
2967     case Node::Class_Allocate:
2968       expand_allocate(n->as_Allocate());
2969       break;
2970     case Node::Class_AllocateArray:
2971       expand_allocate_array(n->as_AllocateArray());
2972       break;
2973     case Node::Class_CallStaticJava:
2974       expand_mh_intrinsic_return(n->as_CallStaticJava());
2975       C->remove_macro_node(n);
2976       break;
2977     default:
2978       assert(false, "unknown node type in macro list");
2979     }
2980     assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2981     if (C->failing())  return true;
2982   }
2983 
2984   _igvn.set_delay_transform(false);
2985   _igvn.optimize();
2986   if (C->failing())  return true;
2987   return false;
2988 }