1 /*
   2  * Copyright (c) 1997, 2023, 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 "classfile/javaClasses.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "gc/shared/barrierSet.hpp"
  29 #include "gc/shared/c2/barrierSetC2.hpp"
  30 #include "gc/shared/tlab_globals.hpp"
  31 #include "memory/allocation.inline.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "oops/objArrayKlass.hpp"
  34 #include "opto/addnode.hpp"
  35 #include "opto/arraycopynode.hpp"
  36 #include "opto/cfgnode.hpp"
  37 #include "opto/regalloc.hpp"
  38 #include "opto/compile.hpp"
  39 #include "opto/connode.hpp"
  40 #include "opto/convertnode.hpp"
  41 #include "opto/loopnode.hpp"
  42 #include "opto/machnode.hpp"
  43 #include "opto/matcher.hpp"
  44 #include "opto/memnode.hpp"
  45 #include "opto/mulnode.hpp"
  46 #include "opto/narrowptrnode.hpp"
  47 #include "opto/phaseX.hpp"
  48 #include "opto/regmask.hpp"
  49 #include "opto/rootnode.hpp"
  50 #include "opto/vectornode.hpp"
  51 #include "utilities/align.hpp"
  52 #include "utilities/copy.hpp"
  53 #include "utilities/macros.hpp"
  54 #include "utilities/powerOfTwo.hpp"
  55 #include "utilities/vmError.hpp"
  56 
  57 // Portions of code courtesy of Clifford Click
  58 
  59 // Optimization - Graph Style
  60 
  61 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
  62 
  63 //=============================================================================
  64 uint MemNode::size_of() const { return sizeof(*this); }
  65 
  66 const TypePtr *MemNode::adr_type() const {
  67   Node* adr = in(Address);
  68   if (adr == nullptr)  return nullptr; // node is dead
  69   const TypePtr* cross_check = nullptr;
  70   DEBUG_ONLY(cross_check = _adr_type);
  71   return calculate_adr_type(adr->bottom_type(), cross_check);
  72 }
  73 
  74 bool MemNode::check_if_adr_maybe_raw(Node* adr) {
  75   if (adr != nullptr) {
  76     if (adr->bottom_type()->base() == Type::RawPtr || adr->bottom_type()->base() == Type::AnyPtr) {
  77       return true;
  78     }
  79   }
  80   return false;
  81 }
  82 
  83 #ifndef PRODUCT
  84 void MemNode::dump_spec(outputStream *st) const {
  85   if (in(Address) == nullptr)  return; // node is dead
  86 #ifndef ASSERT
  87   // fake the missing field
  88   const TypePtr* _adr_type = nullptr;
  89   if (in(Address) != nullptr)
  90     _adr_type = in(Address)->bottom_type()->isa_ptr();
  91 #endif
  92   dump_adr_type(this, _adr_type, st);
  93 
  94   Compile* C = Compile::current();
  95   if (C->alias_type(_adr_type)->is_volatile()) {
  96     st->print(" Volatile!");
  97   }
  98   if (_unaligned_access) {
  99     st->print(" unaligned");
 100   }
 101   if (_mismatched_access) {
 102     st->print(" mismatched");
 103   }
 104   if (_unsafe_access) {
 105     st->print(" unsafe");
 106   }
 107 }
 108 
 109 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
 110   st->print(" @");
 111   if (adr_type == nullptr) {
 112     st->print("null");
 113   } else {
 114     adr_type->dump_on(st);
 115     Compile* C = Compile::current();
 116     Compile::AliasType* atp = nullptr;
 117     if (C->have_alias_type(adr_type))  atp = C->alias_type(adr_type);
 118     if (atp == nullptr)
 119       st->print(", idx=?\?;");
 120     else if (atp->index() == Compile::AliasIdxBot)
 121       st->print(", idx=Bot;");
 122     else if (atp->index() == Compile::AliasIdxTop)
 123       st->print(", idx=Top;");
 124     else if (atp->index() == Compile::AliasIdxRaw)
 125       st->print(", idx=Raw;");
 126     else {
 127       ciField* field = atp->field();
 128       if (field) {
 129         st->print(", name=");
 130         field->print_name_on(st);
 131       }
 132       st->print(", idx=%d;", atp->index());
 133     }
 134   }
 135 }
 136 
 137 extern void print_alias_types();
 138 
 139 #endif
 140 
 141 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) {
 142   assert((t_oop != nullptr), "sanity");
 143   bool is_instance = t_oop->is_known_instance_field();
 144   bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() &&
 145                              (load != nullptr) && load->is_Load() &&
 146                              (phase->is_IterGVN() != nullptr);
 147   if (!(is_instance || is_boxed_value_load))
 148     return mchain;  // don't try to optimize non-instance types
 149   uint instance_id = t_oop->instance_id();
 150   Node *start_mem = phase->C->start()->proj_out_or_null(TypeFunc::Memory);
 151   Node *prev = nullptr;
 152   Node *result = mchain;
 153   while (prev != result) {
 154     prev = result;
 155     if (result == start_mem)
 156       break;  // hit one of our sentinels
 157     // skip over a call which does not affect this memory slice
 158     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
 159       Node *proj_in = result->in(0);
 160       if (proj_in->is_Allocate() && proj_in->_idx == instance_id) {
 161         break;  // hit one of our sentinels
 162       } else if (proj_in->is_Call()) {
 163         // ArrayCopyNodes processed here as well
 164         CallNode *call = proj_in->as_Call();
 165         if (!call->may_modify(t_oop, phase)) { // returns false for instances
 166           result = call->in(TypeFunc::Memory);
 167         }
 168       } else if (proj_in->is_Initialize()) {
 169         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
 170         // Stop if this is the initialization for the object instance which
 171         // contains this memory slice, otherwise skip over it.
 172         if ((alloc == nullptr) || (alloc->_idx == instance_id)) {
 173           break;
 174         }
 175         if (is_instance) {
 176           result = proj_in->in(TypeFunc::Memory);
 177         } else if (is_boxed_value_load) {
 178           Node* klass = alloc->in(AllocateNode::KlassNode);
 179           const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr();
 180           if (tklass->klass_is_exact() && !tklass->exact_klass()->equals(t_oop->is_instptr()->exact_klass())) {
 181             result = proj_in->in(TypeFunc::Memory); // not related allocation
 182           }
 183         }
 184       } else if (proj_in->is_MemBar()) {
 185         ArrayCopyNode* ac = nullptr;
 186         if (ArrayCopyNode::may_modify(t_oop, proj_in->as_MemBar(), phase, ac)) {
 187           break;
 188         }
 189         result = proj_in->in(TypeFunc::Memory);
 190       } else if (proj_in->is_top()) {
 191         break; // dead code
 192       } else {
 193         assert(false, "unexpected projection");
 194       }
 195     } else if (result->is_ClearArray()) {
 196       if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) {
 197         // Can not bypass initialization of the instance
 198         // we are looking for.
 199         break;
 200       }
 201       // Otherwise skip it (the call updated 'result' value).
 202     } else if (result->is_MergeMem()) {
 203       result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, nullptr, tty);
 204     }
 205   }
 206   return result;
 207 }
 208 
 209 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) {
 210   const TypeOopPtr* t_oop = t_adr->isa_oopptr();
 211   if (t_oop == nullptr)
 212     return mchain;  // don't try to optimize non-oop types
 213   Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase);
 214   bool is_instance = t_oop->is_known_instance_field();
 215   PhaseIterGVN *igvn = phase->is_IterGVN();
 216   if (is_instance && igvn != nullptr && result->is_Phi()) {
 217     PhiNode *mphi = result->as_Phi();
 218     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
 219     const TypePtr *t = mphi->adr_type();
 220     bool do_split = false;
 221     // In the following cases, Load memory input can be further optimized based on
 222     // its precise address type
 223     if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ) {
 224       do_split = true;
 225     } else if (t->isa_oopptr() && !t->is_oopptr()->is_known_instance()) {
 226       const TypeOopPtr* mem_t =
 227         t->is_oopptr()->cast_to_exactness(true)
 228         ->is_oopptr()->cast_to_ptr_type(t_oop->ptr())
 229         ->is_oopptr()->cast_to_instance_id(t_oop->instance_id());
 230       if (t_oop->is_aryptr()) {
 231         mem_t = mem_t->is_aryptr()
 232                      ->cast_to_stable(t_oop->is_aryptr()->is_stable())
 233                      ->cast_to_size(t_oop->is_aryptr()->size())
 234                      ->with_offset(t_oop->is_aryptr()->offset())
 235                      ->is_aryptr();
 236       }
 237       do_split = mem_t == t_oop;
 238     }
 239     if (do_split) {
 240       // clone the Phi with our address type
 241       result = mphi->split_out_instance(t_adr, igvn);
 242     } else {
 243       assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
 244     }
 245   }
 246   return result;
 247 }
 248 
 249 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
 250   uint alias_idx = phase->C->get_alias_index(tp);
 251   Node *mem = mmem;
 252 #ifdef ASSERT
 253   {
 254     // Check that current type is consistent with the alias index used during graph construction
 255     assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
 256     bool consistent =  adr_check == nullptr || adr_check->empty() ||
 257                        phase->C->must_alias(adr_check, alias_idx );
 258     // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
 259     if( !consistent && adr_check != nullptr && !adr_check->empty() &&
 260                tp->isa_aryptr() &&        tp->offset() == Type::OffsetBot &&
 261         adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
 262         ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
 263           adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
 264           adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
 265       // don't assert if it is dead code.
 266       consistent = true;
 267     }
 268     if( !consistent ) {
 269       st->print("alias_idx==%d, adr_check==", alias_idx);
 270       if( adr_check == nullptr ) {
 271         st->print("null");
 272       } else {
 273         adr_check->dump();
 274       }
 275       st->cr();
 276       print_alias_types();
 277       assert(consistent, "adr_check must match alias idx");
 278     }
 279   }
 280 #endif
 281   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
 282   // means an array I have not precisely typed yet.  Do not do any
 283   // alias stuff with it any time soon.
 284   const TypeOopPtr *toop = tp->isa_oopptr();
 285   if (tp->base() != Type::AnyPtr &&
 286       !(toop &&
 287         toop->isa_instptr() &&
 288         toop->is_instptr()->instance_klass()->is_java_lang_Object() &&
 289         toop->offset() == Type::OffsetBot)) {
 290     // compress paths and change unreachable cycles to TOP
 291     // If not, we can update the input infinitely along a MergeMem cycle
 292     // Equivalent code in PhiNode::Ideal
 293     Node* m  = phase->transform(mmem);
 294     // If transformed to a MergeMem, get the desired slice
 295     // Otherwise the returned node represents memory for every slice
 296     mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
 297     // Update input if it is progress over what we have now
 298   }
 299   return mem;
 300 }
 301 
 302 //--------------------------Ideal_common---------------------------------------
 303 // Look for degenerate control and memory inputs.  Bypass MergeMem inputs.
 304 // Unhook non-raw memories from complete (macro-expanded) initializations.
 305 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
 306   // If our control input is a dead region, kill all below the region
 307   Node *ctl = in(MemNode::Control);
 308   if (ctl && remove_dead_region(phase, can_reshape))
 309     return this;
 310   ctl = in(MemNode::Control);
 311   // Don't bother trying to transform a dead node
 312   if (ctl && ctl->is_top())  return NodeSentinel;
 313 
 314   PhaseIterGVN *igvn = phase->is_IterGVN();
 315   // Wait if control on the worklist.
 316   if (ctl && can_reshape && igvn != nullptr) {
 317     Node* bol = nullptr;
 318     Node* cmp = nullptr;
 319     if (ctl->in(0)->is_If()) {
 320       assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity");
 321       bol = ctl->in(0)->in(1);
 322       if (bol->is_Bool())
 323         cmp = ctl->in(0)->in(1)->in(1);
 324     }
 325     if (igvn->_worklist.member(ctl) ||
 326         (bol != nullptr && igvn->_worklist.member(bol)) ||
 327         (cmp != nullptr && igvn->_worklist.member(cmp)) ) {
 328       // This control path may be dead.
 329       // Delay this memory node transformation until the control is processed.
 330       igvn->_worklist.push(this);
 331       return NodeSentinel; // caller will return null
 332     }
 333   }
 334   // Ignore if memory is dead, or self-loop
 335   Node *mem = in(MemNode::Memory);
 336   if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return null
 337   assert(mem != this, "dead loop in MemNode::Ideal");
 338 
 339   if (can_reshape && igvn != nullptr && igvn->_worklist.member(mem)) {
 340     // This memory slice may be dead.
 341     // Delay this mem node transformation until the memory is processed.
 342     igvn->_worklist.push(this);
 343     return NodeSentinel; // caller will return null
 344   }
 345 
 346   Node *address = in(MemNode::Address);
 347   const Type *t_adr = phase->type(address);
 348   if (t_adr == Type::TOP)              return NodeSentinel; // caller will return null
 349 
 350   if (can_reshape && is_unsafe_access() && (t_adr == TypePtr::NULL_PTR)) {
 351     // Unsafe off-heap access with zero address. Remove access and other control users
 352     // to not confuse optimizations and add a HaltNode to fail if this is ever executed.
 353     assert(ctl != nullptr, "unsafe accesses should be control dependent");
 354     for (DUIterator_Fast imax, i = ctl->fast_outs(imax); i < imax; i++) {
 355       Node* u = ctl->fast_out(i);
 356       if (u != ctl) {
 357         igvn->rehash_node_delayed(u);
 358         int nb = u->replace_edge(ctl, phase->C->top(), igvn);
 359         --i, imax -= nb;
 360       }
 361     }
 362     Node* frame = igvn->transform(new ParmNode(phase->C->start(), TypeFunc::FramePtr));
 363     Node* halt = igvn->transform(new HaltNode(ctl, frame, "unsafe off-heap access with zero address"));
 364     phase->C->root()->add_req(halt);
 365     return this;
 366   }
 367 
 368   if (can_reshape && igvn != nullptr &&
 369       (igvn->_worklist.member(address) ||
 370        (igvn->_worklist.size() > 0 && t_adr != adr_type())) ) {
 371     // The address's base and type may change when the address is processed.
 372     // Delay this mem node transformation until the address is processed.
 373     igvn->_worklist.push(this);
 374     return NodeSentinel; // caller will return null
 375   }
 376 
 377   // Do NOT remove or optimize the next lines: ensure a new alias index
 378   // is allocated for an oop pointer type before Escape Analysis.
 379   // Note: C++ will not remove it since the call has side effect.
 380   if (t_adr->isa_oopptr()) {
 381     int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
 382   }
 383 
 384   Node* base = nullptr;
 385   if (address->is_AddP()) {
 386     base = address->in(AddPNode::Base);
 387   }
 388   if (base != nullptr && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
 389       !t_adr->isa_rawptr()) {
 390     // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
 391     // Skip this node optimization if its address has TOP base.
 392     return NodeSentinel; // caller will return null
 393   }
 394 
 395   // Avoid independent memory operations
 396   Node* old_mem = mem;
 397 
 398   // The code which unhooks non-raw memories from complete (macro-expanded)
 399   // initializations was removed. After macro-expansion all stores caught
 400   // by Initialize node became raw stores and there is no information
 401   // which memory slices they modify. So it is unsafe to move any memory
 402   // operation above these stores. Also in most cases hooked non-raw memories
 403   // were already unhooked by using information from detect_ptr_independence()
 404   // and find_previous_store().
 405 
 406   if (mem->is_MergeMem()) {
 407     MergeMemNode* mmem = mem->as_MergeMem();
 408     const TypePtr *tp = t_adr->is_ptr();
 409 
 410     mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
 411   }
 412 
 413   if (mem != old_mem) {
 414     set_req_X(MemNode::Memory, mem, phase);
 415     if (phase->type(mem) == Type::TOP) return NodeSentinel;
 416     return this;
 417   }
 418 
 419   // let the subclass continue analyzing...
 420   return nullptr;
 421 }
 422 
 423 // Helper function for proving some simple control dominations.
 424 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
 425 // Already assumes that 'dom' is available at 'sub', and that 'sub'
 426 // is not a constant (dominated by the method's StartNode).
 427 // Used by MemNode::find_previous_store to prove that the
 428 // control input of a memory operation predates (dominates)
 429 // an allocation it wants to look past.
 430 bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
 431   if (dom == nullptr || dom->is_top() || sub == nullptr || sub->is_top())
 432     return false; // Conservative answer for dead code
 433 
 434   // Check 'dom'. Skip Proj and CatchProj nodes.
 435   dom = dom->find_exact_control(dom);
 436   if (dom == nullptr || dom->is_top())
 437     return false; // Conservative answer for dead code
 438 
 439   if (dom == sub) {
 440     // For the case when, for example, 'sub' is Initialize and the original
 441     // 'dom' is Proj node of the 'sub'.
 442     return false;
 443   }
 444 
 445   if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub)
 446     return true;
 447 
 448   // 'dom' dominates 'sub' if its control edge and control edges
 449   // of all its inputs dominate or equal to sub's control edge.
 450 
 451   // Currently 'sub' is either Allocate, Initialize or Start nodes.
 452   // Or Region for the check in LoadNode::Ideal();
 453   // 'sub' should have sub->in(0) != nullptr.
 454   assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() ||
 455          sub->is_Region() || sub->is_Call(), "expecting only these nodes");
 456 
 457   // Get control edge of 'sub'.
 458   Node* orig_sub = sub;
 459   sub = sub->find_exact_control(sub->in(0));
 460   if (sub == nullptr || sub->is_top())
 461     return false; // Conservative answer for dead code
 462 
 463   assert(sub->is_CFG(), "expecting control");
 464 
 465   if (sub == dom)
 466     return true;
 467 
 468   if (sub->is_Start() || sub->is_Root())
 469     return false;
 470 
 471   {
 472     // Check all control edges of 'dom'.
 473 
 474     ResourceMark rm;
 475     Node_List nlist;
 476     Unique_Node_List dom_list;
 477 
 478     dom_list.push(dom);
 479     bool only_dominating_controls = false;
 480 
 481     for (uint next = 0; next < dom_list.size(); next++) {
 482       Node* n = dom_list.at(next);
 483       if (n == orig_sub)
 484         return false; // One of dom's inputs dominated by sub.
 485       if (!n->is_CFG() && n->pinned()) {
 486         // Check only own control edge for pinned non-control nodes.
 487         n = n->find_exact_control(n->in(0));
 488         if (n == nullptr || n->is_top())
 489           return false; // Conservative answer for dead code
 490         assert(n->is_CFG(), "expecting control");
 491         dom_list.push(n);
 492       } else if (n->is_Con() || n->is_Start() || n->is_Root()) {
 493         only_dominating_controls = true;
 494       } else if (n->is_CFG()) {
 495         if (n->dominates(sub, nlist))
 496           only_dominating_controls = true;
 497         else
 498           return false;
 499       } else {
 500         // First, own control edge.
 501         Node* m = n->find_exact_control(n->in(0));
 502         if (m != nullptr) {
 503           if (m->is_top())
 504             return false; // Conservative answer for dead code
 505           dom_list.push(m);
 506         }
 507         // Now, the rest of edges.
 508         uint cnt = n->req();
 509         for (uint i = 1; i < cnt; i++) {
 510           m = n->find_exact_control(n->in(i));
 511           if (m == nullptr || m->is_top())
 512             continue;
 513           dom_list.push(m);
 514         }
 515       }
 516     }
 517     return only_dominating_controls;
 518   }
 519 }
 520 
 521 //---------------------detect_ptr_independence---------------------------------
 522 // Used by MemNode::find_previous_store to prove that two base
 523 // pointers are never equal.
 524 // The pointers are accompanied by their associated allocations,
 525 // if any, which have been previously discovered by the caller.
 526 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
 527                                       Node* p2, AllocateNode* a2,
 528                                       PhaseTransform* phase) {
 529   // Attempt to prove that these two pointers cannot be aliased.
 530   // They may both manifestly be allocations, and they should differ.
 531   // Or, if they are not both allocations, they can be distinct constants.
 532   // Otherwise, one is an allocation and the other a pre-existing value.
 533   if (a1 == nullptr && a2 == nullptr) {           // neither an allocation
 534     return (p1 != p2) && p1->is_Con() && p2->is_Con();
 535   } else if (a1 != nullptr && a2 != nullptr) {    // both allocations
 536     return (a1 != a2);
 537   } else if (a1 != nullptr) {                  // one allocation a1
 538     // (Note:  p2->is_Con implies p2->in(0)->is_Root, which dominates.)
 539     return all_controls_dominate(p2, a1);
 540   } else { //(a2 != null)                   // one allocation a2
 541     return all_controls_dominate(p1, a2);
 542   }
 543   return false;
 544 }
 545 
 546 
 547 // Find an arraycopy ac that produces the memory state represented by parameter mem.
 548 // Return ac if
 549 // (a) can_see_stored_value=true  and ac must have set the value for this load or if
 550 // (b) can_see_stored_value=false and ac could have set the value for this load or if
 551 // (c) can_see_stored_value=false and ac cannot have set the value for this load.
 552 // In case (c) change the parameter mem to the memory input of ac to skip it
 553 // when searching stored value.
 554 // Otherwise return null.
 555 Node* LoadNode::find_previous_arraycopy(PhaseTransform* phase, Node* ld_alloc, Node*& mem, bool can_see_stored_value) const {
 556   ArrayCopyNode* ac = find_array_copy_clone(phase, ld_alloc, mem);
 557   if (ac != nullptr) {
 558     Node* ld_addp = in(MemNode::Address);
 559     Node* src = ac->in(ArrayCopyNode::Src);
 560     const TypeAryPtr* ary_t = phase->type(src)->isa_aryptr();
 561 
 562     // This is a load from a cloned array. The corresponding arraycopy ac must
 563     // have set the value for the load and we can return ac but only if the load
 564     // is known to be within bounds. This is checked below.
 565     if (ary_t != nullptr && ld_addp->is_AddP()) {
 566       Node* ld_offs = ld_addp->in(AddPNode::Offset);
 567       BasicType ary_elem = ary_t->elem()->array_element_basic_type();
 568       jlong header = arrayOopDesc::base_offset_in_bytes(ary_elem);
 569       jlong elemsize = type2aelembytes(ary_elem);
 570 
 571       const TypeX*   ld_offs_t = phase->type(ld_offs)->isa_intptr_t();
 572       const TypeInt* sizetype  = ary_t->size();
 573 
 574       if (ld_offs_t->_lo >= header && ld_offs_t->_hi < (sizetype->_lo * elemsize + header)) {
 575         // The load is known to be within bounds. It receives its value from ac.
 576         return ac;
 577       }
 578       // The load is known to be out-of-bounds.
 579     }
 580     // The load could be out-of-bounds. It must not be hoisted but must remain
 581     // dependent on the runtime range check. This is achieved by returning null.
 582   } else if (mem->is_Proj() && mem->in(0) != nullptr && mem->in(0)->is_ArrayCopy()) {
 583     ArrayCopyNode* ac = mem->in(0)->as_ArrayCopy();
 584 
 585     if (ac->is_arraycopy_validated() ||
 586         ac->is_copyof_validated() ||
 587         ac->is_copyofrange_validated()) {
 588       Node* ld_addp = in(MemNode::Address);
 589       if (ld_addp->is_AddP()) {
 590         Node* ld_base = ld_addp->in(AddPNode::Address);
 591         Node* ld_offs = ld_addp->in(AddPNode::Offset);
 592 
 593         Node* dest = ac->in(ArrayCopyNode::Dest);
 594 
 595         if (dest == ld_base) {
 596           const TypeX *ld_offs_t = phase->type(ld_offs)->isa_intptr_t();
 597           if (ac->modifies(ld_offs_t->_lo, ld_offs_t->_hi, phase, can_see_stored_value)) {
 598             return ac;
 599           }
 600           if (!can_see_stored_value) {
 601             mem = ac->in(TypeFunc::Memory);
 602             return ac;
 603           }
 604         }
 605       }
 606     }
 607   }
 608   return nullptr;
 609 }
 610 
 611 ArrayCopyNode* MemNode::find_array_copy_clone(PhaseTransform* phase, Node* ld_alloc, Node* mem) const {
 612   if (mem->is_Proj() && mem->in(0) != nullptr && (mem->in(0)->Opcode() == Op_MemBarStoreStore ||
 613                                                mem->in(0)->Opcode() == Op_MemBarCPUOrder)) {
 614     if (ld_alloc != nullptr) {
 615       // Check if there is an array copy for a clone
 616       Node* mb = mem->in(0);
 617       ArrayCopyNode* ac = nullptr;
 618       if (mb->in(0) != nullptr && mb->in(0)->is_Proj() &&
 619           mb->in(0)->in(0) != nullptr && mb->in(0)->in(0)->is_ArrayCopy()) {
 620         ac = mb->in(0)->in(0)->as_ArrayCopy();
 621       } else {
 622         // Step over GC barrier when ReduceInitialCardMarks is disabled
 623         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 624         Node* control_proj_ac = bs->step_over_gc_barrier(mb->in(0));
 625 
 626         if (control_proj_ac->is_Proj() && control_proj_ac->in(0)->is_ArrayCopy()) {
 627           ac = control_proj_ac->in(0)->as_ArrayCopy();
 628         }
 629       }
 630 
 631       if (ac != nullptr && ac->is_clonebasic()) {
 632         AllocateNode* alloc = AllocateNode::Ideal_allocation(ac->in(ArrayCopyNode::Dest), phase);
 633         if (alloc != nullptr && alloc == ld_alloc) {
 634           return ac;
 635         }
 636       }
 637     }
 638   }
 639   return nullptr;
 640 }
 641 
 642 // The logic for reordering loads and stores uses four steps:
 643 // (a) Walk carefully past stores and initializations which we
 644 //     can prove are independent of this load.
 645 // (b) Observe that the next memory state makes an exact match
 646 //     with self (load or store), and locate the relevant store.
 647 // (c) Ensure that, if we were to wire self directly to the store,
 648 //     the optimizer would fold it up somehow.
 649 // (d) Do the rewiring, and return, depending on some other part of
 650 //     the optimizer to fold up the load.
 651 // This routine handles steps (a) and (b).  Steps (c) and (d) are
 652 // specific to loads and stores, so they are handled by the callers.
 653 // (Currently, only LoadNode::Ideal has steps (c), (d).  More later.)
 654 //
 655 Node* MemNode::find_previous_store(PhaseTransform* phase) {
 656   Node*         ctrl   = in(MemNode::Control);
 657   Node*         adr    = in(MemNode::Address);
 658   intptr_t      offset = 0;
 659   Node*         base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
 660   AllocateNode* alloc  = AllocateNode::Ideal_allocation(base, phase);
 661 
 662   if (offset == Type::OffsetBot)
 663     return nullptr;            // cannot unalias unless there are precise offsets
 664 
 665   const bool adr_maybe_raw = check_if_adr_maybe_raw(adr);
 666   const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
 667 
 668   intptr_t size_in_bytes = memory_size();
 669 
 670   Node* mem = in(MemNode::Memory);   // start searching here...
 671 
 672   int cnt = 50;             // Cycle limiter
 673   for (;;) {                // While we can dance past unrelated stores...
 674     if (--cnt < 0)  break;  // Caught in cycle or a complicated dance?
 675 
 676     Node* prev = mem;
 677     if (mem->is_Store()) {
 678       Node* st_adr = mem->in(MemNode::Address);
 679       intptr_t st_offset = 0;
 680       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
 681       if (st_base == nullptr)
 682         break;              // inscrutable pointer
 683 
 684       // For raw accesses it's not enough to prove that constant offsets don't intersect.
 685       // We need the bases to be the equal in order for the offset check to make sense.
 686       if ((adr_maybe_raw || check_if_adr_maybe_raw(st_adr)) && st_base != base) {
 687         break;
 688       }
 689 
 690       if (st_offset != offset && st_offset != Type::OffsetBot) {
 691         const int MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize);
 692         assert(mem->as_Store()->memory_size() <= MAX_STORE, "");
 693         if (st_offset >= offset + size_in_bytes ||
 694             st_offset <= offset - MAX_STORE ||
 695             st_offset <= offset - mem->as_Store()->memory_size()) {
 696           // Success:  The offsets are provably independent.
 697           // (You may ask, why not just test st_offset != offset and be done?
 698           // The answer is that stores of different sizes can co-exist
 699           // in the same sequence of RawMem effects.  We sometimes initialize
 700           // a whole 'tile' of array elements with a single jint or jlong.)
 701           mem = mem->in(MemNode::Memory);
 702           continue;           // (a) advance through independent store memory
 703         }
 704       }
 705       if (st_base != base &&
 706           detect_ptr_independence(base, alloc,
 707                                   st_base,
 708                                   AllocateNode::Ideal_allocation(st_base, phase),
 709                                   phase)) {
 710         // Success:  The bases are provably independent.
 711         mem = mem->in(MemNode::Memory);
 712         continue;           // (a) advance through independent store memory
 713       }
 714 
 715       // (b) At this point, if the bases or offsets do not agree, we lose,
 716       // since we have not managed to prove 'this' and 'mem' independent.
 717       if (st_base == base && st_offset == offset) {
 718         return mem;         // let caller handle steps (c), (d)
 719       }
 720 
 721     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
 722       InitializeNode* st_init = mem->in(0)->as_Initialize();
 723       AllocateNode*  st_alloc = st_init->allocation();
 724       if (st_alloc == nullptr)
 725         break;              // something degenerated
 726       bool known_identical = false;
 727       bool known_independent = false;
 728       if (alloc == st_alloc)
 729         known_identical = true;
 730       else if (alloc != nullptr)
 731         known_independent = true;
 732       else if (all_controls_dominate(this, st_alloc))
 733         known_independent = true;
 734 
 735       if (known_independent) {
 736         // The bases are provably independent: Either they are
 737         // manifestly distinct allocations, or else the control
 738         // of this load dominates the store's allocation.
 739         int alias_idx = phase->C->get_alias_index(adr_type());
 740         if (alias_idx == Compile::AliasIdxRaw) {
 741           mem = st_alloc->in(TypeFunc::Memory);
 742         } else {
 743           mem = st_init->memory(alias_idx);
 744         }
 745         continue;           // (a) advance through independent store memory
 746       }
 747 
 748       // (b) at this point, if we are not looking at a store initializing
 749       // the same allocation we are loading from, we lose.
 750       if (known_identical) {
 751         // From caller, can_see_stored_value will consult find_captured_store.
 752         return mem;         // let caller handle steps (c), (d)
 753       }
 754 
 755     } else if (find_previous_arraycopy(phase, alloc, mem, false) != nullptr) {
 756       if (prev != mem) {
 757         // Found an arraycopy but it doesn't affect that load
 758         continue;
 759       }
 760       // Found an arraycopy that may affect that load
 761       return mem;
 762     } else if (addr_t != nullptr && addr_t->is_known_instance_field()) {
 763       // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
 764       if (mem->is_Proj() && mem->in(0)->is_Call()) {
 765         // ArrayCopyNodes processed here as well.
 766         CallNode *call = mem->in(0)->as_Call();
 767         if (!call->may_modify(addr_t, phase)) {
 768           mem = call->in(TypeFunc::Memory);
 769           continue;         // (a) advance through independent call memory
 770         }
 771       } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
 772         ArrayCopyNode* ac = nullptr;
 773         if (ArrayCopyNode::may_modify(addr_t, mem->in(0)->as_MemBar(), phase, ac)) {
 774           break;
 775         }
 776         mem = mem->in(0)->in(TypeFunc::Memory);
 777         continue;           // (a) advance through independent MemBar memory
 778       } else if (mem->is_ClearArray()) {
 779         if (ClearArrayNode::step_through(&mem, (uint)addr_t->instance_id(), phase)) {
 780           // (the call updated 'mem' value)
 781           continue;         // (a) advance through independent allocation memory
 782         } else {
 783           // Can not bypass initialization of the instance
 784           // we are looking for.
 785           return mem;
 786         }
 787       } else if (mem->is_MergeMem()) {
 788         int alias_idx = phase->C->get_alias_index(adr_type());
 789         mem = mem->as_MergeMem()->memory_at(alias_idx);
 790         continue;           // (a) advance through independent MergeMem memory
 791       }
 792     }
 793 
 794     // Unless there is an explicit 'continue', we must bail out here,
 795     // because 'mem' is an inscrutable memory state (e.g., a call).
 796     break;
 797   }
 798 
 799   return nullptr;              // bail out
 800 }
 801 
 802 //----------------------calculate_adr_type-------------------------------------
 803 // Helper function.  Notices when the given type of address hits top or bottom.
 804 // Also, asserts a cross-check of the type against the expected address type.
 805 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
 806   if (t == Type::TOP)  return nullptr; // does not touch memory any more?
 807   #ifdef ASSERT
 808   if (!VerifyAliases || VMError::is_error_reported() || Node::in_dump())  cross_check = nullptr;
 809   #endif
 810   const TypePtr* tp = t->isa_ptr();
 811   if (tp == nullptr) {
 812     assert(cross_check == nullptr || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
 813     return TypePtr::BOTTOM;           // touches lots of memory
 814   } else {
 815     #ifdef ASSERT
 816     // %%%% [phh] We don't check the alias index if cross_check is
 817     //            TypeRawPtr::BOTTOM.  Needs to be investigated.
 818     if (cross_check != nullptr &&
 819         cross_check != TypePtr::BOTTOM &&
 820         cross_check != TypeRawPtr::BOTTOM) {
 821       // Recheck the alias index, to see if it has changed (due to a bug).
 822       Compile* C = Compile::current();
 823       assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
 824              "must stay in the original alias category");
 825       // The type of the address must be contained in the adr_type,
 826       // disregarding "null"-ness.
 827       // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
 828       const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
 829       assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(),
 830              "real address must not escape from expected memory type");
 831     }
 832     #endif
 833     return tp;
 834   }
 835 }
 836 
 837 //=============================================================================
 838 // Should LoadNode::Ideal() attempt to remove control edges?
 839 bool LoadNode::can_remove_control() const {
 840   return !has_pinned_control_dependency();
 841 }
 842 uint LoadNode::size_of() const { return sizeof(*this); }
 843 bool LoadNode::cmp( const Node &n ) const
 844 { return !Type::cmp( _type, ((LoadNode&)n)._type ); }
 845 const Type *LoadNode::bottom_type() const { return _type; }
 846 uint LoadNode::ideal_reg() const {
 847   return _type->ideal_reg();
 848 }
 849 
 850 #ifndef PRODUCT
 851 void LoadNode::dump_spec(outputStream *st) const {
 852   MemNode::dump_spec(st);
 853   if( !Verbose && !WizardMode ) {
 854     // standard dump does this in Verbose and WizardMode
 855     st->print(" #"); _type->dump_on(st);
 856   }
 857   if (!depends_only_on_test()) {
 858     st->print(" (does not depend only on test, ");
 859     if (control_dependency() == UnknownControl) {
 860       st->print("unknown control");
 861     } else if (control_dependency() == Pinned) {
 862       st->print("pinned");
 863     } else if (adr_type() == TypeRawPtr::BOTTOM) {
 864       st->print("raw access");
 865     } else {
 866       st->print("unknown reason");
 867     }
 868     st->print(")");
 869   }
 870 }
 871 #endif
 872 
 873 #ifdef ASSERT
 874 //----------------------------is_immutable_value-------------------------------
 875 // Helper function to allow a raw load without control edge for some cases
 876 bool LoadNode::is_immutable_value(Node* adr) {
 877   if (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() &&
 878       adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal) {
 879 
 880     jlong offset = adr->in(AddPNode::Offset)->find_intptr_t_con(-1);
 881     int offsets[] = {
 882       in_bytes(JavaThread::osthread_offset()),
 883       in_bytes(JavaThread::threadObj_offset()),
 884       in_bytes(JavaThread::vthread_offset()),
 885       in_bytes(JavaThread::scopedValueCache_offset()),
 886     };
 887 
 888     for (size_t i = 0; i < sizeof offsets / sizeof offsets[0]; i++) {
 889       if (offset == offsets[i]) {
 890         return true;
 891       }
 892     }
 893   }
 894 
 895   return false;
 896 }
 897 #endif
 898 
 899 //----------------------------LoadNode::make-----------------------------------
 900 // Polymorphic factory method:
 901 Node* LoadNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, BasicType bt, MemOrd mo,
 902                      ControlDependency control_dependency, bool require_atomic_access, bool unaligned, bool mismatched, bool unsafe, uint8_t barrier_data) {
 903   Compile* C = gvn.C;
 904 
 905   // sanity check the alias category against the created node type
 906   assert(!(adr_type->isa_oopptr() &&
 907            adr_type->offset() == oopDesc::klass_offset_in_bytes()),
 908          "use LoadKlassNode instead");
 909   assert(!(adr_type->isa_aryptr() &&
 910            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
 911          "use LoadRangeNode instead");
 912   // Check control edge of raw loads
 913   assert( ctl != nullptr || C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
 914           // oop will be recorded in oop map if load crosses safepoint
 915           rt->isa_oopptr() || is_immutable_value(adr),
 916           "raw memory operations should have control edge");
 917   LoadNode* load = nullptr;
 918   switch (bt) {
 919   case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 920   case T_BYTE:    load = new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 921   case T_INT:     load = new LoadINode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 922   case T_CHAR:    load = new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 923   case T_SHORT:   load = new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 924   case T_LONG:    load = new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic_access); break;
 925   case T_FLOAT:   load = new LoadFNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency); break;
 926   case T_DOUBLE:  load = new LoadDNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency, require_atomic_access); break;
 927   case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(),  mo, control_dependency); break;
 928   case T_OBJECT:
 929 #ifdef _LP64
 930     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 931       load = new LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency);
 932     } else
 933 #endif
 934     {
 935       assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop");
 936       load = new LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency);
 937     }
 938     break;
 939   default:
 940     ShouldNotReachHere();
 941     break;
 942   }
 943   assert(load != nullptr, "LoadNode should have been created");
 944   if (unaligned) {
 945     load->set_unaligned_access();
 946   }
 947   if (mismatched) {
 948     load->set_mismatched_access();
 949   }
 950   if (unsafe) {
 951     load->set_unsafe_access();
 952   }
 953   load->set_barrier_data(barrier_data);
 954   if (load->Opcode() == Op_LoadN) {
 955     Node* ld = gvn.transform(load);
 956     return new DecodeNNode(ld, ld->bottom_type()->make_ptr());
 957   }
 958 
 959   return load;
 960 }
 961 
 962 //------------------------------hash-------------------------------------------
 963 uint LoadNode::hash() const {
 964   // unroll addition of interesting fields
 965   return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
 966 }
 967 
 968 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) {
 969   if ((atp != nullptr) && (atp->index() >= Compile::AliasIdxRaw)) {
 970     bool non_volatile = (atp->field() != nullptr) && !atp->field()->is_volatile();
 971     bool is_stable_ary = FoldStableValues &&
 972                          (tp != nullptr) && (tp->isa_aryptr() != nullptr) &&
 973                          tp->isa_aryptr()->is_stable();
 974 
 975     return (eliminate_boxing && non_volatile) || is_stable_ary;
 976   }
 977 
 978   return false;
 979 }
 980 
 981 // Is the value loaded previously stored by an arraycopy? If so return
 982 // a load node that reads from the source array so we may be able to
 983 // optimize out the ArrayCopy node later.
 984 Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseGVN* phase) const {
 985   Node* ld_adr = in(MemNode::Address);
 986   intptr_t ld_off = 0;
 987   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
 988   Node* ac = find_previous_arraycopy(phase, ld_alloc, st, true);
 989   if (ac != nullptr) {
 990     assert(ac->is_ArrayCopy(), "what kind of node can this be?");
 991 
 992     Node* mem = ac->in(TypeFunc::Memory);
 993     Node* ctl = ac->in(0);
 994     Node* src = ac->in(ArrayCopyNode::Src);
 995 
 996     if (!ac->as_ArrayCopy()->is_clonebasic() && !phase->type(src)->isa_aryptr()) {
 997       return nullptr;
 998     }
 999 
1000     LoadNode* ld = clone()->as_Load();
1001     Node* addp = in(MemNode::Address)->clone();
1002     if (ac->as_ArrayCopy()->is_clonebasic()) {
1003       assert(ld_alloc != nullptr, "need an alloc");
1004       assert(addp->is_AddP(), "address must be addp");
1005       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1006       assert(bs->step_over_gc_barrier(addp->in(AddPNode::Base)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern");
1007       assert(bs->step_over_gc_barrier(addp->in(AddPNode::Address)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern");
1008       addp->set_req(AddPNode::Base, src);
1009       addp->set_req(AddPNode::Address, src);
1010     } else {
1011       assert(ac->as_ArrayCopy()->is_arraycopy_validated() ||
1012              ac->as_ArrayCopy()->is_copyof_validated() ||
1013              ac->as_ArrayCopy()->is_copyofrange_validated(), "only supported cases");
1014       assert(addp->in(AddPNode::Base) == addp->in(AddPNode::Address), "should be");
1015       addp->set_req(AddPNode::Base, src);
1016       addp->set_req(AddPNode::Address, src);
1017 
1018       const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr();
1019       BasicType ary_elem = ary_t->isa_aryptr()->elem()->array_element_basic_type();
1020       if (is_reference_type(ary_elem, true)) ary_elem = T_OBJECT;
1021 
1022       uint header = arrayOopDesc::base_offset_in_bytes(ary_elem);
1023       uint shift  = exact_log2(type2aelembytes(ary_elem));
1024 
1025       Node* diff = phase->transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
1026 #ifdef _LP64
1027       diff = phase->transform(new ConvI2LNode(diff));
1028 #endif
1029       diff = phase->transform(new LShiftXNode(diff, phase->intcon(shift)));
1030 
1031       Node* offset = phase->transform(new AddXNode(addp->in(AddPNode::Offset), diff));
1032       addp->set_req(AddPNode::Offset, offset);
1033     }
1034     addp = phase->transform(addp);
1035 #ifdef ASSERT
1036     const TypePtr* adr_type = phase->type(addp)->is_ptr();
1037     ld->_adr_type = adr_type;
1038 #endif
1039     ld->set_req(MemNode::Address, addp);
1040     ld->set_req(0, ctl);
1041     ld->set_req(MemNode::Memory, mem);
1042     // load depends on the tests that validate the arraycopy
1043     ld->_control_dependency = UnknownControl;
1044     return ld;
1045   }
1046   return nullptr;
1047 }
1048 
1049 
1050 //---------------------------can_see_stored_value------------------------------
1051 // This routine exists to make sure this set of tests is done the same
1052 // everywhere.  We need to make a coordinated change: first LoadNode::Ideal
1053 // will change the graph shape in a way which makes memory alive twice at the
1054 // same time (uses the Oracle model of aliasing), then some
1055 // LoadXNode::Identity will fold things back to the equivalence-class model
1056 // of aliasing.
1057 Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
1058   Node* ld_adr = in(MemNode::Address);
1059   intptr_t ld_off = 0;
1060   Node* ld_base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ld_off);
1061   Node* ld_alloc = AllocateNode::Ideal_allocation(ld_base, phase);
1062   const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
1063   Compile::AliasType* atp = (tp != nullptr) ? phase->C->alias_type(tp) : nullptr;
1064   // This is more general than load from boxing objects.
1065   if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) {
1066     uint alias_idx = atp->index();
1067     Node* result = nullptr;
1068     Node* current = st;
1069     // Skip through chains of MemBarNodes checking the MergeMems for
1070     // new states for the slice of this load.  Stop once any other
1071     // kind of node is encountered.  Loads from final memory can skip
1072     // through any kind of MemBar but normal loads shouldn't skip
1073     // through MemBarAcquire since the could allow them to move out of
1074     // a synchronized region. It is not safe to step over MemBarCPUOrder,
1075     // because alias info above them may be inaccurate (e.g., due to
1076     // mixed/mismatched unsafe accesses).
1077     bool is_final_mem = !atp->is_rewritable();
1078     while (current->is_Proj()) {
1079       int opc = current->in(0)->Opcode();
1080       if ((is_final_mem && (opc == Op_MemBarAcquire ||
1081                             opc == Op_MemBarAcquireLock ||
1082                             opc == Op_LoadFence)) ||
1083           opc == Op_MemBarRelease ||
1084           opc == Op_StoreFence ||
1085           opc == Op_MemBarReleaseLock ||
1086           opc == Op_MemBarStoreStore ||
1087           opc == Op_StoreStoreFence) {
1088         Node* mem = current->in(0)->in(TypeFunc::Memory);
1089         if (mem->is_MergeMem()) {
1090           MergeMemNode* merge = mem->as_MergeMem();
1091           Node* new_st = merge->memory_at(alias_idx);
1092           if (new_st == merge->base_memory()) {
1093             // Keep searching
1094             current = new_st;
1095             continue;
1096           }
1097           // Save the new memory state for the slice and fall through
1098           // to exit.
1099           result = new_st;
1100         }
1101       }
1102       break;
1103     }
1104     if (result != nullptr) {
1105       st = result;
1106     }
1107   }
1108 
1109   // Loop around twice in the case Load -> Initialize -> Store.
1110   // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
1111   for (int trip = 0; trip <= 1; trip++) {
1112 
1113     if (st->is_Store()) {
1114       Node* st_adr = st->in(MemNode::Address);
1115       if (st_adr != ld_adr) {
1116         // Try harder before giving up. Unify base pointers with casts (e.g., raw/non-raw pointers).
1117         intptr_t st_off = 0;
1118         Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_off);
1119         if (ld_base == nullptr)                                return nullptr;
1120         if (st_base == nullptr)                                return nullptr;
1121         if (!ld_base->eqv_uncast(st_base, /*keep_deps=*/true)) return nullptr;
1122         if (ld_off != st_off)                                  return nullptr;
1123         if (ld_off == Type::OffsetBot)                         return nullptr;
1124         // Same base, same offset.
1125         // Possible improvement for arrays: check index value instead of absolute offset.
1126 
1127         // At this point we have proven something like this setup:
1128         //   B = << base >>
1129         //   L =  LoadQ(AddP(Check/CastPP(B), #Off))
1130         //   S = StoreQ(AddP(             B , #Off), V)
1131         // (Actually, we haven't yet proven the Q's are the same.)
1132         // In other words, we are loading from a casted version of
1133         // the same pointer-and-offset that we stored to.
1134         // Casted version may carry a dependency and it is respected.
1135         // Thus, we are able to replace L by V.
1136       }
1137       // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
1138       if (store_Opcode() != st->Opcode()) {
1139         return nullptr;
1140       }
1141       // LoadVector/StoreVector needs additional check to ensure the types match.
1142       if (st->is_StoreVector()) {
1143         const TypeVect*  in_vt = st->as_StoreVector()->vect_type();
1144         const TypeVect* out_vt = as_LoadVector()->vect_type();
1145         if (in_vt != out_vt) {
1146           return nullptr;
1147         }
1148       }
1149       return st->in(MemNode::ValueIn);
1150     }
1151 
1152     // A load from a freshly-created object always returns zero.
1153     // (This can happen after LoadNode::Ideal resets the load's memory input
1154     // to find_captured_store, which returned InitializeNode::zero_memory.)
1155     if (st->is_Proj() && st->in(0)->is_Allocate() &&
1156         (st->in(0) == ld_alloc) &&
1157         (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) {
1158       // return a zero value for the load's basic type
1159       // (This is one of the few places where a generic PhaseTransform
1160       // can create new nodes.  Think of it as lazily manifesting
1161       // virtually pre-existing constants.)
1162       if (memory_type() != T_VOID) {
1163         if (ReduceBulkZeroing || find_array_copy_clone(phase, ld_alloc, in(MemNode::Memory)) == nullptr) {
1164           // If ReduceBulkZeroing is disabled, we need to check if the allocation does not belong to an
1165           // ArrayCopyNode clone. If it does, then we cannot assume zero since the initialization is done
1166           // by the ArrayCopyNode.
1167           return phase->zerocon(memory_type());
1168         }
1169       } else {
1170         // TODO: materialize all-zero vector constant
1171         assert(!isa_Load() || as_Load()->type()->isa_vect(), "");
1172       }
1173     }
1174 
1175     // A load from an initialization barrier can match a captured store.
1176     if (st->is_Proj() && st->in(0)->is_Initialize()) {
1177       InitializeNode* init = st->in(0)->as_Initialize();
1178       AllocateNode* alloc = init->allocation();
1179       if ((alloc != nullptr) && (alloc == ld_alloc)) {
1180         // examine a captured store value
1181         st = init->find_captured_store(ld_off, memory_size(), phase);
1182         if (st != nullptr) {
1183           continue;             // take one more trip around
1184         }
1185       }
1186     }
1187 
1188     // Load boxed value from result of valueOf() call is input parameter.
1189     if (this->is_Load() && ld_adr->is_AddP() &&
1190         (tp != nullptr) && tp->is_ptr_to_boxed_value()) {
1191       intptr_t ignore = 0;
1192       Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore);
1193       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1194       base = bs->step_over_gc_barrier(base);
1195       if (base != nullptr && base->is_Proj() &&
1196           base->as_Proj()->_con == TypeFunc::Parms &&
1197           base->in(0)->is_CallStaticJava() &&
1198           base->in(0)->as_CallStaticJava()->is_boxing_method()) {
1199         return base->in(0)->in(TypeFunc::Parms);
1200       }
1201     }
1202 
1203     break;
1204   }
1205 
1206   return nullptr;
1207 }
1208 
1209 //----------------------is_instance_field_load_with_local_phi------------------
1210 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
1211   if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl &&
1212       in(Address)->is_AddP() ) {
1213     const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr();
1214     // Only instances and boxed values.
1215     if( t_oop != nullptr &&
1216         (t_oop->is_ptr_to_boxed_value() ||
1217          t_oop->is_known_instance_field()) &&
1218         t_oop->offset() != Type::OffsetBot &&
1219         t_oop->offset() != Type::OffsetTop) {
1220       return true;
1221     }
1222   }
1223   return false;
1224 }
1225 
1226 //------------------------------Identity---------------------------------------
1227 // Loads are identity if previous store is to same address
1228 Node* LoadNode::Identity(PhaseGVN* phase) {
1229   // If the previous store-maker is the right kind of Store, and the store is
1230   // to the same address, then we are equal to the value stored.
1231   Node* mem = in(Memory);
1232   Node* value = can_see_stored_value(mem, phase);
1233   if( value ) {
1234     // byte, short & char stores truncate naturally.
1235     // A load has to load the truncated value which requires
1236     // some sort of masking operation and that requires an
1237     // Ideal call instead of an Identity call.
1238     if (memory_size() < BytesPerInt) {
1239       // If the input to the store does not fit with the load's result type,
1240       // it must be truncated via an Ideal call.
1241       if (!phase->type(value)->higher_equal(phase->type(this)))
1242         return this;
1243     }
1244     // (This works even when value is a Con, but LoadNode::Value
1245     // usually runs first, producing the singleton type of the Con.)
1246     if (!has_pinned_control_dependency() || value->is_Con()) {
1247       return value;
1248     } else {
1249       return this;
1250     }
1251   }
1252 
1253   if (has_pinned_control_dependency()) {
1254     return this;
1255   }
1256   // Search for an existing data phi which was generated before for the same
1257   // instance's field to avoid infinite generation of phis in a loop.
1258   Node *region = mem->in(0);
1259   if (is_instance_field_load_with_local_phi(region)) {
1260     const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr();
1261     int this_index  = phase->C->get_alias_index(addr_t);
1262     int this_offset = addr_t->offset();
1263     int this_iid    = addr_t->instance_id();
1264     if (!addr_t->is_known_instance() &&
1265          addr_t->is_ptr_to_boxed_value()) {
1266       // Use _idx of address base (could be Phi node) for boxed values.
1267       intptr_t   ignore = 0;
1268       Node*      base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1269       if (base == nullptr) {
1270         return this;
1271       }
1272       this_iid = base->_idx;
1273     }
1274     const Type* this_type = bottom_type();
1275     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1276       Node* phi = region->fast_out(i);
1277       if (phi->is_Phi() && phi != mem &&
1278           phi->as_Phi()->is_same_inst_field(this_type, (int)mem->_idx, this_iid, this_index, this_offset)) {
1279         return phi;
1280       }
1281     }
1282   }
1283 
1284   return this;
1285 }
1286 
1287 // Construct an equivalent unsigned load.
1288 Node* LoadNode::convert_to_unsigned_load(PhaseGVN& gvn) {
1289   BasicType bt = T_ILLEGAL;
1290   const Type* rt = nullptr;
1291   switch (Opcode()) {
1292     case Op_LoadUB: return this;
1293     case Op_LoadUS: return this;
1294     case Op_LoadB: bt = T_BOOLEAN; rt = TypeInt::UBYTE; break;
1295     case Op_LoadS: bt = T_CHAR;    rt = TypeInt::CHAR;  break;
1296     default:
1297       assert(false, "no unsigned variant: %s", Name());
1298       return nullptr;
1299   }
1300   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1301                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1302                         false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access());
1303 }
1304 
1305 // Construct an equivalent signed load.
1306 Node* LoadNode::convert_to_signed_load(PhaseGVN& gvn) {
1307   BasicType bt = T_ILLEGAL;
1308   const Type* rt = nullptr;
1309   switch (Opcode()) {
1310     case Op_LoadUB: bt = T_BYTE;  rt = TypeInt::BYTE;  break;
1311     case Op_LoadUS: bt = T_SHORT; rt = TypeInt::SHORT; break;
1312     case Op_LoadB: // fall through
1313     case Op_LoadS: // fall through
1314     case Op_LoadI: // fall through
1315     case Op_LoadL: return this;
1316     default:
1317       assert(false, "no signed variant: %s", Name());
1318       return nullptr;
1319   }
1320   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1321                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1322                         false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access());
1323 }
1324 
1325 bool LoadNode::has_reinterpret_variant(const Type* rt) {
1326   BasicType bt = rt->basic_type();
1327   switch (Opcode()) {
1328     case Op_LoadI: return (bt == T_FLOAT);
1329     case Op_LoadL: return (bt == T_DOUBLE);
1330     case Op_LoadF: return (bt == T_INT);
1331     case Op_LoadD: return (bt == T_LONG);
1332 
1333     default: return false;
1334   }
1335 }
1336 
1337 Node* LoadNode::convert_to_reinterpret_load(PhaseGVN& gvn, const Type* rt) {
1338   BasicType bt = rt->basic_type();
1339   assert(has_reinterpret_variant(rt), "no reinterpret variant: %s %s", Name(), type2name(bt));
1340   bool is_mismatched = is_mismatched_access();
1341   const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr();
1342   if (raw_type == nullptr) {
1343     is_mismatched = true; // conservatively match all non-raw accesses as mismatched
1344   }
1345   const int op = Opcode();
1346   bool require_atomic_access = (op == Op_LoadL && ((LoadLNode*)this)->require_atomic_access()) ||
1347                                (op == Op_LoadD && ((LoadDNode*)this)->require_atomic_access());
1348   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1349                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1350                         require_atomic_access, is_unaligned_access(), is_mismatched);
1351 }
1352 
1353 bool StoreNode::has_reinterpret_variant(const Type* vt) {
1354   BasicType bt = vt->basic_type();
1355   switch (Opcode()) {
1356     case Op_StoreI: return (bt == T_FLOAT);
1357     case Op_StoreL: return (bt == T_DOUBLE);
1358     case Op_StoreF: return (bt == T_INT);
1359     case Op_StoreD: return (bt == T_LONG);
1360 
1361     default: return false;
1362   }
1363 }
1364 
1365 Node* StoreNode::convert_to_reinterpret_store(PhaseGVN& gvn, Node* val, const Type* vt) {
1366   BasicType bt = vt->basic_type();
1367   assert(has_reinterpret_variant(vt), "no reinterpret variant: %s %s", Name(), type2name(bt));
1368   const int op = Opcode();
1369   bool require_atomic_access = (op == Op_StoreL && ((StoreLNode*)this)->require_atomic_access()) ||
1370                                (op == Op_StoreD && ((StoreDNode*)this)->require_atomic_access());
1371   StoreNode* st = StoreNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1372                                   raw_adr_type(), val, bt, _mo, require_atomic_access);
1373 
1374   bool is_mismatched = is_mismatched_access();
1375   const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr();
1376   if (raw_type == nullptr) {
1377     is_mismatched = true; // conservatively match all non-raw accesses as mismatched
1378   }
1379   if (is_mismatched) {
1380     st->set_mismatched_access();
1381   }
1382   return st;
1383 }
1384 
1385 // We're loading from an object which has autobox behaviour.
1386 // If this object is result of a valueOf call we'll have a phi
1387 // merging a newly allocated object and a load from the cache.
1388 // We want to replace this load with the original incoming
1389 // argument to the valueOf call.
1390 Node* LoadNode::eliminate_autobox(PhaseIterGVN* igvn) {
1391   assert(igvn->C->eliminate_boxing(), "sanity");
1392   intptr_t ignore = 0;
1393   Node* base = AddPNode::Ideal_base_and_offset(in(Address), igvn, ignore);
1394   if ((base == nullptr) || base->is_Phi()) {
1395     // Push the loads from the phi that comes from valueOf up
1396     // through it to allow elimination of the loads and the recovery
1397     // of the original value. It is done in split_through_phi().
1398     return nullptr;
1399   } else if (base->is_Load() ||
1400              (base->is_DecodeN() && base->in(1)->is_Load())) {
1401     // Eliminate the load of boxed value for integer types from the cache
1402     // array by deriving the value from the index into the array.
1403     // Capture the offset of the load and then reverse the computation.
1404 
1405     // Get LoadN node which loads a boxing object from 'cache' array.
1406     if (base->is_DecodeN()) {
1407       base = base->in(1);
1408     }
1409     if (!base->in(Address)->is_AddP()) {
1410       return nullptr; // Complex address
1411     }
1412     AddPNode* address = base->in(Address)->as_AddP();
1413     Node* cache_base = address->in(AddPNode::Base);
1414     if ((cache_base != nullptr) && cache_base->is_DecodeN()) {
1415       // Get ConP node which is static 'cache' field.
1416       cache_base = cache_base->in(1);
1417     }
1418     if ((cache_base != nullptr) && cache_base->is_Con()) {
1419       const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr();
1420       if ((base_type != nullptr) && base_type->is_autobox_cache()) {
1421         Node* elements[4];
1422         int shift = exact_log2(type2aelembytes(T_OBJECT));
1423         int count = address->unpack_offsets(elements, ARRAY_SIZE(elements));
1424         if (count > 0 && elements[0]->is_Con() &&
1425             (count == 1 ||
1426              (count == 2 && elements[1]->Opcode() == Op_LShiftX &&
1427                             elements[1]->in(2) == igvn->intcon(shift)))) {
1428           ciObjArray* array = base_type->const_oop()->as_obj_array();
1429           // Fetch the box object cache[0] at the base of the array and get its value
1430           ciInstance* box = array->obj_at(0)->as_instance();
1431           ciInstanceKlass* ik = box->klass()->as_instance_klass();
1432           assert(ik->is_box_klass(), "sanity");
1433           assert(ik->nof_nonstatic_fields() == 1, "change following code");
1434           if (ik->nof_nonstatic_fields() == 1) {
1435             // This should be true nonstatic_field_at requires calling
1436             // nof_nonstatic_fields so check it anyway
1437             ciConstant c = box->field_value(ik->nonstatic_field_at(0));
1438             BasicType bt = c.basic_type();
1439             // Only integer types have boxing cache.
1440             assert(bt == T_BOOLEAN || bt == T_CHAR  ||
1441                    bt == T_BYTE    || bt == T_SHORT ||
1442                    bt == T_INT     || bt == T_LONG, "wrong type = %s", type2name(bt));
1443             jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int();
1444             if (cache_low != (int)cache_low) {
1445               return nullptr; // should not happen since cache is array indexed by value
1446             }
1447             jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift);
1448             if (offset != (int)offset) {
1449               return nullptr; // should not happen since cache is array indexed by value
1450             }
1451            // Add up all the offsets making of the address of the load
1452             Node* result = elements[0];
1453             for (int i = 1; i < count; i++) {
1454               result = igvn->transform(new AddXNode(result, elements[i]));
1455             }
1456             // Remove the constant offset from the address and then
1457             result = igvn->transform(new AddXNode(result, igvn->MakeConX(-(int)offset)));
1458             // remove the scaling of the offset to recover the original index.
1459             if (result->Opcode() == Op_LShiftX && result->in(2) == igvn->intcon(shift)) {
1460               // Peel the shift off directly but wrap it in a dummy node
1461               // since Ideal can't return existing nodes
1462               igvn->_worklist.push(result); // remove dead node later
1463               result = new RShiftXNode(result->in(1), igvn->intcon(0));
1464             } else if (result->is_Add() && result->in(2)->is_Con() &&
1465                        result->in(1)->Opcode() == Op_LShiftX &&
1466                        result->in(1)->in(2) == igvn->intcon(shift)) {
1467               // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z)
1468               // but for boxing cache access we know that X<<Z will not overflow
1469               // (there is range check) so we do this optimizatrion by hand here.
1470               igvn->_worklist.push(result); // remove dead node later
1471               Node* add_con = new RShiftXNode(result->in(2), igvn->intcon(shift));
1472               result = new AddXNode(result->in(1)->in(1), igvn->transform(add_con));
1473             } else {
1474               result = new RShiftXNode(result, igvn->intcon(shift));
1475             }
1476 #ifdef _LP64
1477             if (bt != T_LONG) {
1478               result = new ConvL2INode(igvn->transform(result));
1479             }
1480 #else
1481             if (bt == T_LONG) {
1482               result = new ConvI2LNode(igvn->transform(result));
1483             }
1484 #endif
1485             // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
1486             // Need to preserve unboxing load type if it is unsigned.
1487             switch(this->Opcode()) {
1488               case Op_LoadUB:
1489                 result = new AndINode(igvn->transform(result), igvn->intcon(0xFF));
1490                 break;
1491               case Op_LoadUS:
1492                 result = new AndINode(igvn->transform(result), igvn->intcon(0xFFFF));
1493                 break;
1494             }
1495             return result;
1496           }
1497         }
1498       }
1499     }
1500   }
1501   return nullptr;
1502 }
1503 
1504 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) {
1505   Node* region = phi->in(0);
1506   if (region == nullptr) {
1507     return false; // Wait stable graph
1508   }
1509   uint cnt = phi->req();
1510   for (uint i = 1; i < cnt; i++) {
1511     Node* rc = region->in(i);
1512     if (rc == nullptr || phase->type(rc) == Type::TOP)
1513       return false; // Wait stable graph
1514     Node* in = phi->in(i);
1515     if (in == nullptr || phase->type(in) == Type::TOP)
1516       return false; // Wait stable graph
1517   }
1518   return true;
1519 }
1520 //------------------------------split_through_phi------------------------------
1521 // Split instance or boxed field load through Phi.
1522 Node* LoadNode::split_through_phi(PhaseGVN* phase) {
1523   if (req() > 3) {
1524     assert(is_LoadVector() && Opcode() != Op_LoadVector, "load has too many inputs");
1525     // LoadVector subclasses such as LoadVectorMasked have extra inputs that the logic below doesn't take into account
1526     return nullptr;
1527   }
1528   Node* mem     = in(Memory);
1529   Node* address = in(Address);
1530   const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr();
1531 
1532   assert((t_oop != nullptr) &&
1533          (t_oop->is_known_instance_field() ||
1534           t_oop->is_ptr_to_boxed_value()), "invalid conditions");
1535 
1536   Compile* C = phase->C;
1537   intptr_t ignore = 0;
1538   Node*    base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1539   bool base_is_phi = (base != nullptr) && base->is_Phi();
1540   bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() &&
1541                            (base != nullptr) && (base == address->in(AddPNode::Base)) &&
1542                            phase->type(base)->higher_equal(TypePtr::NOTNULL);
1543 
1544   if (!((mem->is_Phi() || base_is_phi) &&
1545         (load_boxed_values || t_oop->is_known_instance_field()))) {
1546     return nullptr; // memory is not Phi
1547   }
1548 
1549   if (mem->is_Phi()) {
1550     if (!stable_phi(mem->as_Phi(), phase)) {
1551       return nullptr; // Wait stable graph
1552     }
1553     uint cnt = mem->req();
1554     // Check for loop invariant memory.
1555     if (cnt == 3) {
1556       for (uint i = 1; i < cnt; i++) {
1557         Node* in = mem->in(i);
1558         Node*  m = optimize_memory_chain(in, t_oop, this, phase);
1559         if (m == mem) {
1560           if (i == 1) {
1561             // if the first edge was a loop, check second edge too.
1562             // If both are replaceable - we are in an infinite loop
1563             Node *n = optimize_memory_chain(mem->in(2), t_oop, this, phase);
1564             if (n == mem) {
1565               break;
1566             }
1567           }
1568           set_req(Memory, mem->in(cnt - i));
1569           return this; // made change
1570         }
1571       }
1572     }
1573   }
1574   if (base_is_phi) {
1575     if (!stable_phi(base->as_Phi(), phase)) {
1576       return nullptr; // Wait stable graph
1577     }
1578     uint cnt = base->req();
1579     // Check for loop invariant memory.
1580     if (cnt == 3) {
1581       for (uint i = 1; i < cnt; i++) {
1582         if (base->in(i) == base) {
1583           return nullptr; // Wait stable graph
1584         }
1585       }
1586     }
1587   }
1588 
1589   // Split through Phi (see original code in loopopts.cpp).
1590   assert(C->have_alias_type(t_oop), "instance should have alias type");
1591 
1592   // Do nothing here if Identity will find a value
1593   // (to avoid infinite chain of value phis generation).
1594   if (this != Identity(phase)) {
1595     return nullptr;
1596   }
1597 
1598   // Select Region to split through.
1599   Node* region;
1600   if (!base_is_phi) {
1601     assert(mem->is_Phi(), "sanity");
1602     region = mem->in(0);
1603     // Skip if the region dominates some control edge of the address.
1604     if (!MemNode::all_controls_dominate(address, region))
1605       return nullptr;
1606   } else if (!mem->is_Phi()) {
1607     assert(base_is_phi, "sanity");
1608     region = base->in(0);
1609     // Skip if the region dominates some control edge of the memory.
1610     if (!MemNode::all_controls_dominate(mem, region))
1611       return nullptr;
1612   } else if (base->in(0) != mem->in(0)) {
1613     assert(base_is_phi && mem->is_Phi(), "sanity");
1614     if (MemNode::all_controls_dominate(mem, base->in(0))) {
1615       region = base->in(0);
1616     } else if (MemNode::all_controls_dominate(address, mem->in(0))) {
1617       region = mem->in(0);
1618     } else {
1619       return nullptr; // complex graph
1620     }
1621   } else {
1622     assert(base->in(0) == mem->in(0), "sanity");
1623     region = mem->in(0);
1624   }
1625 
1626   const Type* this_type = this->bottom_type();
1627   int this_index  = C->get_alias_index(t_oop);
1628   int this_offset = t_oop->offset();
1629   int this_iid    = t_oop->instance_id();
1630   if (!t_oop->is_known_instance() && load_boxed_values) {
1631     // Use _idx of address base for boxed values.
1632     this_iid = base->_idx;
1633   }
1634   PhaseIterGVN* igvn = phase->is_IterGVN();
1635   Node* phi = new PhiNode(region, this_type, nullptr, mem->_idx, this_iid, this_index, this_offset);
1636   for (uint i = 1; i < region->req(); i++) {
1637     Node* x;
1638     Node* the_clone = nullptr;
1639     Node* in = region->in(i);
1640     if (region->is_CountedLoop() && region->as_Loop()->is_strip_mined() && i == LoopNode::EntryControl &&
1641         in != nullptr && in->is_OuterStripMinedLoop()) {
1642       // No node should go in the outer strip mined loop
1643       in = in->in(LoopNode::EntryControl);
1644     }
1645     if (in == nullptr || in == C->top()) {
1646       x = C->top();      // Dead path?  Use a dead data op
1647     } else {
1648       x = this->clone();        // Else clone up the data op
1649       the_clone = x;            // Remember for possible deletion.
1650       // Alter data node to use pre-phi inputs
1651       if (this->in(0) == region) {
1652         x->set_req(0, in);
1653       } else {
1654         x->set_req(0, nullptr);
1655       }
1656       if (mem->is_Phi() && (mem->in(0) == region)) {
1657         x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone.
1658       }
1659       if (address->is_Phi() && address->in(0) == region) {
1660         x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone
1661       }
1662       if (base_is_phi && (base->in(0) == region)) {
1663         Node* base_x = base->in(i); // Clone address for loads from boxed objects.
1664         Node* adr_x = phase->transform(new AddPNode(base_x,base_x,address->in(AddPNode::Offset)));
1665         x->set_req(Address, adr_x);
1666       }
1667     }
1668     // Check for a 'win' on some paths
1669     const Type *t = x->Value(igvn);
1670 
1671     bool singleton = t->singleton();
1672 
1673     // See comments in PhaseIdealLoop::split_thru_phi().
1674     if (singleton && t == Type::TOP) {
1675       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
1676     }
1677 
1678     if (singleton) {
1679       x = igvn->makecon(t);
1680     } else {
1681       // We now call Identity to try to simplify the cloned node.
1682       // Note that some Identity methods call phase->type(this).
1683       // Make sure that the type array is big enough for
1684       // our new node, even though we may throw the node away.
1685       // (This tweaking with igvn only works because x is a new node.)
1686       igvn->set_type(x, t);
1687       // If x is a TypeNode, capture any more-precise type permanently into Node
1688       // otherwise it will be not updated during igvn->transform since
1689       // igvn->type(x) is set to x->Value() already.
1690       x->raise_bottom_type(t);
1691       Node* y = x->Identity(igvn);
1692       if (y != x) {
1693         x = y;
1694       } else {
1695         y = igvn->hash_find_insert(x);
1696         if (y) {
1697           x = y;
1698         } else {
1699           // Else x is a new node we are keeping
1700           // We do not need register_new_node_with_optimizer
1701           // because set_type has already been called.
1702           igvn->_worklist.push(x);
1703         }
1704       }
1705     }
1706     if (x != the_clone && the_clone != nullptr) {
1707       igvn->remove_dead_node(the_clone);
1708     }
1709     phi->set_req(i, x);
1710   }
1711   // Record Phi
1712   igvn->register_new_node_with_optimizer(phi);
1713   return phi;
1714 }
1715 
1716 AllocateNode* LoadNode::is_new_object_mark_load(PhaseGVN *phase) const {
1717   if (Opcode() == Op_LoadX) {
1718     Node* address = in(MemNode::Address);
1719     AllocateNode* alloc = AllocateNode::Ideal_allocation(address, phase);
1720     Node* mem = in(MemNode::Memory);
1721     if (alloc != nullptr && mem->is_Proj() &&
1722         mem->in(0) != nullptr &&
1723         mem->in(0) == alloc->initialization() &&
1724         alloc->initialization()->proj_out_or_null(0) != nullptr) {
1725       return alloc;
1726     }
1727   }
1728   return nullptr;
1729 }
1730 
1731 
1732 //------------------------------Ideal------------------------------------------
1733 // If the load is from Field memory and the pointer is non-null, it might be possible to
1734 // zero out the control input.
1735 // If the offset is constant and the base is an object allocation,
1736 // try to hook me up to the exact initializing store.
1737 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1738   if (has_pinned_control_dependency()) {
1739     return nullptr;
1740   }
1741   Node* p = MemNode::Ideal_common(phase, can_reshape);
1742   if (p)  return (p == NodeSentinel) ? nullptr : p;
1743 
1744   Node* ctrl    = in(MemNode::Control);
1745   Node* address = in(MemNode::Address);
1746   bool progress = false;
1747 
1748   bool addr_mark = ((phase->type(address)->isa_oopptr() || phase->type(address)->isa_narrowoop()) &&
1749          phase->type(address)->is_ptr()->offset() == oopDesc::mark_offset_in_bytes());
1750 
1751   // Skip up past a SafePoint control.  Cannot do this for Stores because
1752   // pointer stores & cardmarks must stay on the same side of a SafePoint.
1753   if( ctrl != nullptr && ctrl->Opcode() == Op_SafePoint &&
1754       phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw  &&
1755       !addr_mark &&
1756       (depends_only_on_test() || has_unknown_control_dependency())) {
1757     ctrl = ctrl->in(0);
1758     set_req(MemNode::Control,ctrl);
1759     progress = true;
1760   }
1761 
1762   intptr_t ignore = 0;
1763   Node*    base   = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1764   if (base != nullptr
1765       && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) {
1766     // Check for useless control edge in some common special cases
1767     if (in(MemNode::Control) != nullptr
1768         && can_remove_control()
1769         && phase->type(base)->higher_equal(TypePtr::NOTNULL)
1770         && all_controls_dominate(base, phase->C->start())) {
1771       // A method-invariant, non-null address (constant or 'this' argument).
1772       set_req(MemNode::Control, nullptr);
1773       progress = true;
1774     }
1775   }
1776 
1777   Node* mem = in(MemNode::Memory);
1778   const TypePtr *addr_t = phase->type(address)->isa_ptr();
1779 
1780   if (can_reshape && (addr_t != nullptr)) {
1781     // try to optimize our memory input
1782     Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase);
1783     if (opt_mem != mem) {
1784       set_req_X(MemNode::Memory, opt_mem, phase);
1785       if (phase->type( opt_mem ) == Type::TOP) return nullptr;
1786       return this;
1787     }
1788     const TypeOopPtr *t_oop = addr_t->isa_oopptr();
1789     if ((t_oop != nullptr) &&
1790         (t_oop->is_known_instance_field() ||
1791          t_oop->is_ptr_to_boxed_value())) {
1792       PhaseIterGVN *igvn = phase->is_IterGVN();
1793       assert(igvn != nullptr, "must be PhaseIterGVN when can_reshape is true");
1794       if (igvn->_worklist.member(opt_mem)) {
1795         // Delay this transformation until memory Phi is processed.
1796         igvn->_worklist.push(this);
1797         return nullptr;
1798       }
1799       // Split instance field load through Phi.
1800       Node* result = split_through_phi(phase);
1801       if (result != nullptr) return result;
1802 
1803       if (t_oop->is_ptr_to_boxed_value()) {
1804         Node* result = eliminate_autobox(igvn);
1805         if (result != nullptr) return result;
1806       }
1807     }
1808   }
1809 
1810   // Is there a dominating load that loads the same value?  Leave
1811   // anything that is not a load of a field/array element (like
1812   // barriers etc.) alone
1813   if (in(0) != nullptr && !adr_type()->isa_rawptr() && can_reshape) {
1814     for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
1815       Node *use = mem->fast_out(i);
1816       if (use != this &&
1817           use->Opcode() == Opcode() &&
1818           use->in(0) != nullptr &&
1819           use->in(0) != in(0) &&
1820           use->in(Address) == in(Address)) {
1821         Node* ctl = in(0);
1822         for (int i = 0; i < 10 && ctl != nullptr; i++) {
1823           ctl = IfNode::up_one_dom(ctl);
1824           if (ctl == use->in(0)) {
1825             set_req(0, use->in(0));
1826             return this;
1827           }
1828         }
1829       }
1830     }
1831   }
1832 
1833   // Check for prior store with a different base or offset; make Load
1834   // independent.  Skip through any number of them.  Bail out if the stores
1835   // are in an endless dead cycle and report no progress.  This is a key
1836   // transform for Reflection.  However, if after skipping through the Stores
1837   // we can't then fold up against a prior store do NOT do the transform as
1838   // this amounts to using the 'Oracle' model of aliasing.  It leaves the same
1839   // array memory alive twice: once for the hoisted Load and again after the
1840   // bypassed Store.  This situation only works if EVERYBODY who does
1841   // anti-dependence work knows how to bypass.  I.e. we need all
1842   // anti-dependence checks to ask the same Oracle.  Right now, that Oracle is
1843   // the alias index stuff.  So instead, peek through Stores and IFF we can
1844   // fold up, do so.
1845   Node* prev_mem = find_previous_store(phase);
1846   if (prev_mem != nullptr) {
1847     Node* value = can_see_arraycopy_value(prev_mem, phase);
1848     if (value != nullptr) {
1849       return value;
1850     }
1851   }
1852   // Steps (a), (b):  Walk past independent stores to find an exact match.
1853   if (prev_mem != nullptr && prev_mem != in(MemNode::Memory)) {
1854     // (c) See if we can fold up on the spot, but don't fold up here.
1855     // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or
1856     // just return a prior value, which is done by Identity calls.
1857     if (can_see_stored_value(prev_mem, phase)) {
1858       // Make ready for step (d):
1859       set_req_X(MemNode::Memory, prev_mem, phase);
1860       return this;
1861     }
1862   }
1863 
1864   return progress ? this : nullptr;
1865 }
1866 
1867 // Helper to recognize certain Klass fields which are invariant across
1868 // some group of array types (e.g., int[] or all T[] where T < Object).
1869 const Type*
1870 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
1871                                  ciKlass* klass) const {
1872   if (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) {
1873     // The field is Klass::_modifier_flags.  Return its (constant) value.
1874     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
1875     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
1876     return TypeInt::make(klass->modifier_flags());
1877   }
1878   if (tkls->offset() == in_bytes(Klass::access_flags_offset())) {
1879     // The field is Klass::_access_flags.  Return its (constant) value.
1880     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
1881     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
1882     return TypeInt::make(klass->access_flags());
1883   }
1884   if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
1885     // The field is Klass::_layout_helper.  Return its constant value if known.
1886     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
1887     return TypeInt::make(klass->layout_helper());
1888   }
1889 
1890   // No match.
1891   return nullptr;
1892 }
1893 
1894 //------------------------------Value-----------------------------------------
1895 const Type* LoadNode::Value(PhaseGVN* phase) const {
1896   // Either input is TOP ==> the result is TOP
1897   Node* mem = in(MemNode::Memory);
1898   const Type *t1 = phase->type(mem);
1899   if (t1 == Type::TOP)  return Type::TOP;
1900   Node* adr = in(MemNode::Address);
1901   const TypePtr* tp = phase->type(adr)->isa_ptr();
1902   if (tp == nullptr || tp->empty())  return Type::TOP;
1903   int off = tp->offset();
1904   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
1905   Compile* C = phase->C;
1906 
1907   // Try to guess loaded type from pointer type
1908   if (tp->isa_aryptr()) {
1909     const TypeAryPtr* ary = tp->is_aryptr();
1910     const Type* t = ary->elem();
1911 
1912     // Determine whether the reference is beyond the header or not, by comparing
1913     // the offset against the offset of the start of the array's data.
1914     // Different array types begin at slightly different offsets (12 vs. 16).
1915     // We choose T_BYTE as an example base type that is least restrictive
1916     // as to alignment, which will therefore produce the smallest
1917     // possible base offset.
1918     const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1919     const bool off_beyond_header = (off >= min_base_off);
1920 
1921     // Try to constant-fold a stable array element.
1922     if (FoldStableValues && !is_mismatched_access() && ary->is_stable()) {
1923       // Make sure the reference is not into the header and the offset is constant
1924       ciObject* aobj = ary->const_oop();
1925       if (aobj != nullptr && off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
1926         int stable_dimension = (ary->stable_dimension() > 0 ? ary->stable_dimension() - 1 : 0);
1927         const Type* con_type = Type::make_constant_from_array_element(aobj->as_array(), off,
1928                                                                       stable_dimension,
1929                                                                       memory_type(), is_unsigned());
1930         if (con_type != nullptr) {
1931           return con_type;
1932         }
1933       }
1934     }
1935 
1936     // Don't do this for integer types. There is only potential profit if
1937     // the element type t is lower than _type; that is, for int types, if _type is
1938     // more restrictive than t.  This only happens here if one is short and the other
1939     // char (both 16 bits), and in those cases we've made an intentional decision
1940     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
1941     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
1942     //
1943     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
1944     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
1945     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
1946     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
1947     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
1948     // In fact, that could have been the original type of p1, and p1 could have
1949     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
1950     // expression (LShiftL quux 3) independently optimized to the constant 8.
1951     if ((t->isa_int() == nullptr) && (t->isa_long() == nullptr)
1952         && (_type->isa_vect() == nullptr)
1953         && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
1954       // t might actually be lower than _type, if _type is a unique
1955       // concrete subclass of abstract class t.
1956       if (off_beyond_header || off == Type::OffsetBot) {  // is the offset beyond the header?
1957         const Type* jt = t->join_speculative(_type);
1958         // In any case, do not allow the join, per se, to empty out the type.
1959         if (jt->empty() && !t->empty()) {
1960           // This can happen if a interface-typed array narrows to a class type.
1961           jt = _type;
1962         }
1963 #ifdef ASSERT
1964         if (phase->C->eliminate_boxing() && adr->is_AddP()) {
1965           // The pointers in the autobox arrays are always non-null
1966           Node* base = adr->in(AddPNode::Base);
1967           if ((base != nullptr) && base->is_DecodeN()) {
1968             // Get LoadN node which loads IntegerCache.cache field
1969             base = base->in(1);
1970           }
1971           if ((base != nullptr) && base->is_Con()) {
1972             const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
1973             if ((base_type != nullptr) && base_type->is_autobox_cache()) {
1974               // It could be narrow oop
1975               assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
1976             }
1977           }
1978         }
1979 #endif
1980         return jt;
1981       }
1982     }
1983   } else if (tp->base() == Type::InstPtr) {
1984     assert( off != Type::OffsetBot ||
1985             // arrays can be cast to Objects
1986             !tp->isa_instptr() ||
1987             tp->is_instptr()->instance_klass()->is_java_lang_Object() ||
1988             // unsafe field access may not have a constant offset
1989             C->has_unsafe_access(),
1990             "Field accesses must be precise" );
1991     // For oop loads, we expect the _type to be precise.
1992 
1993     // Optimize loads from constant fields.
1994     const TypeInstPtr* tinst = tp->is_instptr();
1995     ciObject* const_oop = tinst->const_oop();
1996     if (!is_mismatched_access() && off != Type::OffsetBot && const_oop != nullptr && const_oop->is_instance()) {
1997       const Type* con_type = Type::make_constant_from_field(const_oop->as_instance(), off, is_unsigned(), memory_type());
1998       if (con_type != nullptr) {
1999         return con_type;
2000       }
2001     }
2002   } else if (tp->base() == Type::KlassPtr || tp->base() == Type::InstKlassPtr || tp->base() == Type::AryKlassPtr) {
2003     assert(off != Type::OffsetBot ||
2004             !tp->isa_instklassptr() ||
2005            // arrays can be cast to Objects
2006            tp->isa_instklassptr()->instance_klass()->is_java_lang_Object() ||
2007            // also allow array-loading from the primary supertype
2008            // array during subtype checks
2009            Opcode() == Op_LoadKlass,
2010            "Field accesses must be precise");
2011     // For klass/static loads, we expect the _type to be precise
2012   } else if (tp->base() == Type::RawPtr && adr->is_Load() && off == 0) {
2013     /* With mirrors being an indirect in the Klass*
2014      * the VM is now using two loads. LoadKlass(LoadP(LoadP(Klass, mirror_offset), zero_offset))
2015      * The LoadP from the Klass has a RawPtr type (see LibraryCallKit::load_mirror_from_klass).
2016      *
2017      * So check the type and klass of the node before the LoadP.
2018      */
2019     Node* adr2 = adr->in(MemNode::Address);
2020     const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2021     if (tkls != nullptr && !StressReflectiveCode) {
2022       if (tkls->is_loaded() && tkls->klass_is_exact() && tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
2023         ciKlass* klass = tkls->exact_klass();
2024         assert(adr->Opcode() == Op_LoadP, "must load an oop from _java_mirror");
2025         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
2026         return TypeInstPtr::make(klass->java_mirror());
2027       }
2028     }
2029   }
2030 
2031   const TypeKlassPtr *tkls = tp->isa_klassptr();
2032   if (tkls != nullptr) {
2033     if (tkls->is_loaded() && tkls->klass_is_exact()) {
2034       ciKlass* klass = tkls->exact_klass();
2035       // We are loading a field from a Klass metaobject whose identity
2036       // is known at compile time (the type is "exact" or "precise").
2037       // Check for fields we know are maintained as constants by the VM.
2038       if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
2039         // The field is Klass::_super_check_offset.  Return its (constant) value.
2040         // (Folds up type checking code.)
2041         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
2042         return TypeInt::make(klass->super_check_offset());
2043       }
2044       // Compute index into primary_supers array
2045       juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
2046       // Check for overflowing; use unsigned compare to handle the negative case.
2047       if( depth < ciKlass::primary_super_limit() ) {
2048         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
2049         // (Folds up type checking code.)
2050         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
2051         ciKlass *ss = klass->super_of_depth(depth);
2052         return ss ? TypeKlassPtr::make(ss, Type::trust_interfaces) : TypePtr::NULL_PTR;
2053       }
2054       const Type* aift = load_array_final_field(tkls, klass);
2055       if (aift != nullptr)  return aift;
2056     }
2057 
2058     // We can still check if we are loading from the primary_supers array at a
2059     // shallow enough depth.  Even though the klass is not exact, entries less
2060     // than or equal to its super depth are correct.
2061     if (tkls->is_loaded()) {
2062       ciKlass* klass = nullptr;
2063       if (tkls->isa_instklassptr()) {
2064         klass = tkls->is_instklassptr()->instance_klass();
2065       } else {
2066         int dims;
2067         const Type* inner = tkls->is_aryklassptr()->base_element_type(dims);
2068         if (inner->isa_instklassptr()) {
2069           klass = inner->is_instklassptr()->instance_klass();
2070           klass = ciObjArrayKlass::make(klass, dims);
2071         }
2072       }
2073       if (klass != nullptr) {
2074         // Compute index into primary_supers array
2075         juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
2076         // Check for overflowing; use unsigned compare to handle the negative case.
2077         if (depth < ciKlass::primary_super_limit() &&
2078             depth <= klass->super_depth()) { // allow self-depth checks to handle self-check case
2079           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
2080           // (Folds up type checking code.)
2081           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
2082           ciKlass *ss = klass->super_of_depth(depth);
2083           return ss ? TypeKlassPtr::make(ss, Type::trust_interfaces) : TypePtr::NULL_PTR;
2084         }
2085       }
2086     }
2087 
2088     // If the type is enough to determine that the thing is not an array,
2089     // we can give the layout_helper a positive interval type.
2090     // This will help short-circuit some reflective code.
2091     if (tkls->offset() == in_bytes(Klass::layout_helper_offset()) &&
2092         tkls->isa_instklassptr() && // not directly typed as an array
2093         !tkls->is_instklassptr()->instance_klass()->is_java_lang_Object() // not the supertype of all T[] and specifically not Serializable & Cloneable
2094         ) {
2095       // Note:  When interfaces are reliable, we can narrow the interface
2096       // test to (klass != Serializable && klass != Cloneable).
2097       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
2098       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
2099       // The key property of this type is that it folds up tests
2100       // for array-ness, since it proves that the layout_helper is positive.
2101       // Thus, a generic value like the basic object layout helper works fine.
2102       return TypeInt::make(min_size, max_jint, Type::WidenMin);
2103     }
2104   }
2105 
2106   // If we are loading from a freshly-allocated object, produce a zero,
2107   // if the load is provably beyond the header of the object.
2108   // (Also allow a variable load from a fresh array to produce zero.)
2109   const TypeOopPtr *tinst = tp->isa_oopptr();
2110   bool is_instance = (tinst != nullptr) && tinst->is_known_instance_field();
2111   bool is_boxed_value = (tinst != nullptr) && tinst->is_ptr_to_boxed_value();
2112   if (ReduceFieldZeroing || is_instance || is_boxed_value) {
2113     Node* value = can_see_stored_value(mem,phase);
2114     if (value != nullptr && value->is_Con()) {
2115       assert(value->bottom_type()->higher_equal(_type),"sanity");
2116       return value->bottom_type();
2117     }
2118   }
2119 
2120   bool is_vect = (_type->isa_vect() != nullptr);
2121   if (is_instance && !is_vect) {
2122     // If we have an instance type and our memory input is the
2123     // programs's initial memory state, there is no matching store,
2124     // so just return a zero of the appropriate type -
2125     // except if it is vectorized - then we have no zero constant.
2126     Node *mem = in(MemNode::Memory);
2127     if (mem->is_Parm() && mem->in(0)->is_Start()) {
2128       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
2129       return Type::get_zero_type(_type->basic_type());
2130     }
2131   }
2132 
2133   Node* alloc = is_new_object_mark_load(phase);
2134   if (alloc != nullptr) {
2135     return TypeX::make(markWord::prototype().value());
2136   }
2137 
2138   return _type;
2139 }
2140 
2141 //------------------------------match_edge-------------------------------------
2142 // Do we Match on this edge index or not?  Match only the address.
2143 uint LoadNode::match_edge(uint idx) const {
2144   return idx == MemNode::Address;
2145 }
2146 
2147 //--------------------------LoadBNode::Ideal--------------------------------------
2148 //
2149 //  If the previous store is to the same address as this load,
2150 //  and the value stored was larger than a byte, replace this load
2151 //  with the value stored truncated to a byte.  If no truncation is
2152 //  needed, the replacement is done in LoadNode::Identity().
2153 //
2154 Node* LoadBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2155   Node* mem = in(MemNode::Memory);
2156   Node* value = can_see_stored_value(mem,phase);
2157   if (value != nullptr) {
2158     Node* narrow = Compile::narrow_value(T_BYTE, value, _type, phase, false);
2159     if (narrow != value) {
2160       return narrow;
2161     }
2162   }
2163   // Identity call will handle the case where truncation is not needed.
2164   return LoadNode::Ideal(phase, can_reshape);
2165 }
2166 
2167 const Type* LoadBNode::Value(PhaseGVN* phase) const {
2168   Node* mem = in(MemNode::Memory);
2169   Node* value = can_see_stored_value(mem,phase);
2170   if (value != nullptr && value->is_Con() &&
2171       !value->bottom_type()->higher_equal(_type)) {
2172     // If the input to the store does not fit with the load's result type,
2173     // it must be truncated. We can't delay until Ideal call since
2174     // a singleton Value is needed for split_thru_phi optimization.
2175     int con = value->get_int();
2176     return TypeInt::make((con << 24) >> 24);
2177   }
2178   return LoadNode::Value(phase);
2179 }
2180 
2181 //--------------------------LoadUBNode::Ideal-------------------------------------
2182 //
2183 //  If the previous store is to the same address as this load,
2184 //  and the value stored was larger than a byte, replace this load
2185 //  with the value stored truncated to a byte.  If no truncation is
2186 //  needed, the replacement is done in LoadNode::Identity().
2187 //
2188 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2189   Node* mem = in(MemNode::Memory);
2190   Node* value = can_see_stored_value(mem, phase);
2191   if (value != nullptr) {
2192     Node* narrow = Compile::narrow_value(T_BOOLEAN, value, _type, phase, false);
2193     if (narrow != value) {
2194       return narrow;
2195     }
2196   }
2197   // Identity call will handle the case where truncation is not needed.
2198   return LoadNode::Ideal(phase, can_reshape);
2199 }
2200 
2201 const Type* LoadUBNode::Value(PhaseGVN* phase) const {
2202   Node* mem = in(MemNode::Memory);
2203   Node* value = can_see_stored_value(mem,phase);
2204   if (value != nullptr && value->is_Con() &&
2205       !value->bottom_type()->higher_equal(_type)) {
2206     // If the input to the store does not fit with the load's result type,
2207     // it must be truncated. We can't delay until Ideal call since
2208     // a singleton Value is needed for split_thru_phi optimization.
2209     int con = value->get_int();
2210     return TypeInt::make(con & 0xFF);
2211   }
2212   return LoadNode::Value(phase);
2213 }
2214 
2215 //--------------------------LoadUSNode::Ideal-------------------------------------
2216 //
2217 //  If the previous store is to the same address as this load,
2218 //  and the value stored was larger than a char, replace this load
2219 //  with the value stored truncated to a char.  If no truncation is
2220 //  needed, the replacement is done in LoadNode::Identity().
2221 //
2222 Node* LoadUSNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2223   Node* mem = in(MemNode::Memory);
2224   Node* value = can_see_stored_value(mem,phase);
2225   if (value != nullptr) {
2226     Node* narrow = Compile::narrow_value(T_CHAR, value, _type, phase, false);
2227     if (narrow != value) {
2228       return narrow;
2229     }
2230   }
2231   // Identity call will handle the case where truncation is not needed.
2232   return LoadNode::Ideal(phase, can_reshape);
2233 }
2234 
2235 const Type* LoadUSNode::Value(PhaseGVN* phase) const {
2236   Node* mem = in(MemNode::Memory);
2237   Node* value = can_see_stored_value(mem,phase);
2238   if (value != nullptr && value->is_Con() &&
2239       !value->bottom_type()->higher_equal(_type)) {
2240     // If the input to the store does not fit with the load's result type,
2241     // it must be truncated. We can't delay until Ideal call since
2242     // a singleton Value is needed for split_thru_phi optimization.
2243     int con = value->get_int();
2244     return TypeInt::make(con & 0xFFFF);
2245   }
2246   return LoadNode::Value(phase);
2247 }
2248 
2249 //--------------------------LoadSNode::Ideal--------------------------------------
2250 //
2251 //  If the previous store is to the same address as this load,
2252 //  and the value stored was larger than a short, replace this load
2253 //  with the value stored truncated to a short.  If no truncation is
2254 //  needed, the replacement is done in LoadNode::Identity().
2255 //
2256 Node* LoadSNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2257   Node* mem = in(MemNode::Memory);
2258   Node* value = can_see_stored_value(mem,phase);
2259   if (value != nullptr) {
2260     Node* narrow = Compile::narrow_value(T_SHORT, value, _type, phase, false);
2261     if (narrow != value) {
2262       return narrow;
2263     }
2264   }
2265   // Identity call will handle the case where truncation is not needed.
2266   return LoadNode::Ideal(phase, can_reshape);
2267 }
2268 
2269 const Type* LoadSNode::Value(PhaseGVN* phase) const {
2270   Node* mem = in(MemNode::Memory);
2271   Node* value = can_see_stored_value(mem,phase);
2272   if (value != nullptr && value->is_Con() &&
2273       !value->bottom_type()->higher_equal(_type)) {
2274     // If the input to the store does not fit with the load's result type,
2275     // it must be truncated. We can't delay until Ideal call since
2276     // a singleton Value is needed for split_thru_phi optimization.
2277     int con = value->get_int();
2278     return TypeInt::make((con << 16) >> 16);
2279   }
2280   return LoadNode::Value(phase);
2281 }
2282 
2283 //=============================================================================
2284 //----------------------------LoadKlassNode::make------------------------------
2285 // Polymorphic factory method:
2286 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) {
2287   // sanity check the alias category against the created node type
2288   const TypePtr *adr_type = adr->bottom_type()->isa_ptr();
2289   assert(adr_type != nullptr, "expecting TypeKlassPtr");
2290 #ifdef _LP64
2291   if (adr_type->is_ptr_to_narrowklass()) {
2292     assert(UseCompressedClassPointers, "no compressed klasses");
2293     Node* load_klass = gvn.transform(new LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
2294     return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
2295   }
2296 #endif
2297   assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
2298   return new LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered);
2299 }
2300 
2301 //------------------------------Value------------------------------------------
2302 const Type* LoadKlassNode::Value(PhaseGVN* phase) const {
2303   return klass_value_common(phase);
2304 }
2305 
2306 // In most cases, LoadKlassNode does not have the control input set. If the control
2307 // input is set, it must not be removed (by LoadNode::Ideal()).
2308 bool LoadKlassNode::can_remove_control() const {
2309   return false;
2310 }
2311 
2312 const Type* LoadNode::klass_value_common(PhaseGVN* phase) const {
2313   // Either input is TOP ==> the result is TOP
2314   const Type *t1 = phase->type( in(MemNode::Memory) );
2315   if (t1 == Type::TOP)  return Type::TOP;
2316   Node *adr = in(MemNode::Address);
2317   const Type *t2 = phase->type( adr );
2318   if (t2 == Type::TOP)  return Type::TOP;
2319   const TypePtr *tp = t2->is_ptr();
2320   if (TypePtr::above_centerline(tp->ptr()) ||
2321       tp->ptr() == TypePtr::Null)  return Type::TOP;
2322 
2323   // Return a more precise klass, if possible
2324   const TypeInstPtr *tinst = tp->isa_instptr();
2325   if (tinst != nullptr) {
2326     ciInstanceKlass* ik = tinst->instance_klass();
2327     int offset = tinst->offset();
2328     if (ik == phase->C->env()->Class_klass()
2329         && (offset == java_lang_Class::klass_offset() ||
2330             offset == java_lang_Class::array_klass_offset())) {
2331       // We are loading a special hidden field from a Class mirror object,
2332       // the field which points to the VM's Klass metaobject.
2333       ciType* t = tinst->java_mirror_type();
2334       // java_mirror_type returns non-null for compile-time Class constants.
2335       if (t != nullptr) {
2336         // constant oop => constant klass
2337         if (offset == java_lang_Class::array_klass_offset()) {
2338           if (t->is_void()) {
2339             // We cannot create a void array.  Since void is a primitive type return null
2340             // klass.  Users of this result need to do a null check on the returned klass.
2341             return TypePtr::NULL_PTR;
2342           }
2343           return TypeKlassPtr::make(ciArrayKlass::make(t), Type::trust_interfaces);
2344         }
2345         if (!t->is_klass()) {
2346           // a primitive Class (e.g., int.class) has null for a klass field
2347           return TypePtr::NULL_PTR;
2348         }
2349         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
2350         return TypeKlassPtr::make(t->as_klass(), Type::trust_interfaces);
2351       }
2352       // non-constant mirror, so we can't tell what's going on
2353     }
2354     if (!tinst->is_loaded())
2355       return _type;             // Bail out if not loaded
2356     if (offset == oopDesc::klass_offset_in_bytes()) {
2357       return tinst->as_klass_type(true);
2358     }
2359   }
2360 
2361   // Check for loading klass from an array
2362   const TypeAryPtr *tary = tp->isa_aryptr();
2363   if (tary != nullptr && tary->elem() != Type::BOTTOM &&
2364       tary->offset() == oopDesc::klass_offset_in_bytes()) {
2365     return tary->as_klass_type(true);
2366   }
2367 
2368   // Check for loading klass from an array klass
2369   const TypeKlassPtr *tkls = tp->isa_klassptr();
2370   if (tkls != nullptr && !StressReflectiveCode) {
2371     if (!tkls->is_loaded())
2372      return _type;             // Bail out if not loaded
2373     if (tkls->isa_aryklassptr() && tkls->is_aryklassptr()->elem()->isa_klassptr() &&
2374         tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
2375       // // Always returning precise element type is incorrect,
2376       // // e.g., element type could be object and array may contain strings
2377       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
2378 
2379       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
2380       // according to the element type's subclassing.
2381       return tkls->is_aryklassptr()->elem();
2382     }
2383     if (tkls->isa_instklassptr() != nullptr && tkls->klass_is_exact() &&
2384         tkls->offset() == in_bytes(Klass::super_offset())) {
2385       ciKlass* sup = tkls->is_instklassptr()->instance_klass()->super();
2386       // The field is Klass::_super.  Return its (constant) value.
2387       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
2388       return sup ? TypeKlassPtr::make(sup, Type::trust_interfaces) : TypePtr::NULL_PTR;
2389     }
2390   }
2391 
2392   // Bailout case
2393   return LoadNode::Value(phase);
2394 }
2395 
2396 //------------------------------Identity---------------------------------------
2397 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
2398 // Also feed through the klass in Allocate(...klass...)._klass.
2399 Node* LoadKlassNode::Identity(PhaseGVN* phase) {
2400   return klass_identity_common(phase);
2401 }
2402 
2403 Node* LoadNode::klass_identity_common(PhaseGVN* phase) {
2404   Node* x = LoadNode::Identity(phase);
2405   if (x != this)  return x;
2406 
2407   // Take apart the address into an oop and offset.
2408   // Return 'this' if we cannot.
2409   Node*    adr    = in(MemNode::Address);
2410   intptr_t offset = 0;
2411   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2412   if (base == nullptr)     return this;
2413   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
2414   if (toop == nullptr)     return this;
2415 
2416   // Step over potential GC barrier for OopHandle resolve
2417   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2418   if (bs->is_gc_barrier_node(base)) {
2419     base = bs->step_over_gc_barrier(base);
2420   }
2421 
2422   // We can fetch the klass directly through an AllocateNode.
2423   // This works even if the klass is not constant (clone or newArray).
2424   if (offset == oopDesc::klass_offset_in_bytes()) {
2425     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
2426     if (allocated_klass != nullptr) {
2427       return allocated_klass;
2428     }
2429   }
2430 
2431   // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
2432   // See inline_native_Class_query for occurrences of these patterns.
2433   // Java Example:  x.getClass().isAssignableFrom(y)
2434   //
2435   // This improves reflective code, often making the Class
2436   // mirror go completely dead.  (Current exception:  Class
2437   // mirrors may appear in debug info, but we could clean them out by
2438   // introducing a new debug info operator for Klass.java_mirror).
2439 
2440   if (toop->isa_instptr() && toop->is_instptr()->instance_klass() == phase->C->env()->Class_klass()
2441       && offset == java_lang_Class::klass_offset()) {
2442     if (base->is_Load()) {
2443       Node* base2 = base->in(MemNode::Address);
2444       if (base2->is_Load()) { /* direct load of a load which is the OopHandle */
2445         Node* adr2 = base2->in(MemNode::Address);
2446         const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2447         if (tkls != nullptr && !tkls->empty()
2448             && (tkls->isa_instklassptr() || tkls->isa_aryklassptr())
2449             && adr2->is_AddP()
2450            ) {
2451           int mirror_field = in_bytes(Klass::java_mirror_offset());
2452           if (tkls->offset() == mirror_field) {
2453             return adr2->in(AddPNode::Base);
2454           }
2455         }
2456       }
2457     }
2458   }
2459 
2460   return this;
2461 }
2462 
2463 
2464 //------------------------------Value------------------------------------------
2465 const Type* LoadNKlassNode::Value(PhaseGVN* phase) const {
2466   const Type *t = klass_value_common(phase);
2467   if (t == Type::TOP)
2468     return t;
2469 
2470   return t->make_narrowklass();
2471 }
2472 
2473 //------------------------------Identity---------------------------------------
2474 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
2475 // Also feed through the klass in Allocate(...klass...)._klass.
2476 Node* LoadNKlassNode::Identity(PhaseGVN* phase) {
2477   Node *x = klass_identity_common(phase);
2478 
2479   const Type *t = phase->type( x );
2480   if( t == Type::TOP ) return x;
2481   if( t->isa_narrowklass()) return x;
2482   assert (!t->isa_narrowoop(), "no narrow oop here");
2483 
2484   return phase->transform(new EncodePKlassNode(x, t->make_narrowklass()));
2485 }
2486 
2487 //------------------------------Value-----------------------------------------
2488 const Type* LoadRangeNode::Value(PhaseGVN* phase) const {
2489   // Either input is TOP ==> the result is TOP
2490   const Type *t1 = phase->type( in(MemNode::Memory) );
2491   if( t1 == Type::TOP ) return Type::TOP;
2492   Node *adr = in(MemNode::Address);
2493   const Type *t2 = phase->type( adr );
2494   if( t2 == Type::TOP ) return Type::TOP;
2495   const TypePtr *tp = t2->is_ptr();
2496   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
2497   const TypeAryPtr *tap = tp->isa_aryptr();
2498   if( !tap ) return _type;
2499   return tap->size();
2500 }
2501 
2502 //-------------------------------Ideal---------------------------------------
2503 // Feed through the length in AllocateArray(...length...)._length.
2504 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2505   Node* p = MemNode::Ideal_common(phase, can_reshape);
2506   if (p)  return (p == NodeSentinel) ? nullptr : p;
2507 
2508   // Take apart the address into an oop and offset.
2509   // Return 'this' if we cannot.
2510   Node*    adr    = in(MemNode::Address);
2511   intptr_t offset = 0;
2512   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase,  offset);
2513   if (base == nullptr)     return nullptr;
2514   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2515   if (tary == nullptr)     return nullptr;
2516 
2517   // We can fetch the length directly through an AllocateArrayNode.
2518   // This works even if the length is not constant (clone or newArray).
2519   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2520     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2521     if (alloc != nullptr) {
2522       Node* allocated_length = alloc->Ideal_length();
2523       Node* len = alloc->make_ideal_length(tary, phase);
2524       if (allocated_length != len) {
2525         // New CastII improves on this.
2526         return len;
2527       }
2528     }
2529   }
2530 
2531   return nullptr;
2532 }
2533 
2534 //------------------------------Identity---------------------------------------
2535 // Feed through the length in AllocateArray(...length...)._length.
2536 Node* LoadRangeNode::Identity(PhaseGVN* phase) {
2537   Node* x = LoadINode::Identity(phase);
2538   if (x != this)  return x;
2539 
2540   // Take apart the address into an oop and offset.
2541   // Return 'this' if we cannot.
2542   Node*    adr    = in(MemNode::Address);
2543   intptr_t offset = 0;
2544   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2545   if (base == nullptr)     return this;
2546   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2547   if (tary == nullptr)     return this;
2548 
2549   // We can fetch the length directly through an AllocateArrayNode.
2550   // This works even if the length is not constant (clone or newArray).
2551   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2552     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2553     if (alloc != nullptr) {
2554       Node* allocated_length = alloc->Ideal_length();
2555       // Do not allow make_ideal_length to allocate a CastII node.
2556       Node* len = alloc->make_ideal_length(tary, phase, false);
2557       if (allocated_length == len) {
2558         // Return allocated_length only if it would not be improved by a CastII.
2559         return allocated_length;
2560       }
2561     }
2562   }
2563 
2564   return this;
2565 
2566 }
2567 
2568 //=============================================================================
2569 //---------------------------StoreNode::make-----------------------------------
2570 // Polymorphic factory method:
2571 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo, bool require_atomic_access) {
2572   assert((mo == unordered || mo == release), "unexpected");
2573   Compile* C = gvn.C;
2574   assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
2575          ctl != nullptr, "raw memory operations should have control edge");
2576 
2577   switch (bt) {
2578   case T_BOOLEAN: val = gvn.transform(new AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case
2579   case T_BYTE:    return new StoreBNode(ctl, mem, adr, adr_type, val, mo);
2580   case T_INT:     return new StoreINode(ctl, mem, adr, adr_type, val, mo);
2581   case T_CHAR:
2582   case T_SHORT:   return new StoreCNode(ctl, mem, adr, adr_type, val, mo);
2583   case T_LONG:    return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access);
2584   case T_FLOAT:   return new StoreFNode(ctl, mem, adr, adr_type, val, mo);
2585   case T_DOUBLE:  return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access);
2586   case T_METADATA:
2587   case T_ADDRESS:
2588   case T_OBJECT:
2589 #ifdef _LP64
2590     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2591       val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop()));
2592       return new StoreNNode(ctl, mem, adr, adr_type, val, mo);
2593     } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
2594                (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
2595                 adr->bottom_type()->isa_rawptr())) {
2596       val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
2597       return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
2598     }
2599 #endif
2600     {
2601       return new StorePNode(ctl, mem, adr, adr_type, val, mo);
2602     }
2603   default:
2604     ShouldNotReachHere();
2605     return (StoreNode*)nullptr;
2606   }
2607 }
2608 
2609 //--------------------------bottom_type----------------------------------------
2610 const Type *StoreNode::bottom_type() const {
2611   return Type::MEMORY;
2612 }
2613 
2614 //------------------------------hash-------------------------------------------
2615 uint StoreNode::hash() const {
2616   // unroll addition of interesting fields
2617   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
2618 
2619   // Since they are not commoned, do not hash them:
2620   return NO_HASH;
2621 }
2622 
2623 //------------------------------Ideal------------------------------------------
2624 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
2625 // When a store immediately follows a relevant allocation/initialization,
2626 // try to capture it into the initialization, or hoist it above.
2627 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2628   Node* p = MemNode::Ideal_common(phase, can_reshape);
2629   if (p)  return (p == NodeSentinel) ? nullptr : p;
2630 
2631   Node* mem     = in(MemNode::Memory);
2632   Node* address = in(MemNode::Address);
2633   Node* value   = in(MemNode::ValueIn);
2634   // Back-to-back stores to same address?  Fold em up.  Generally
2635   // unsafe if I have intervening uses...  Also disallowed for StoreCM
2636   // since they must follow each StoreP operation.  Redundant StoreCMs
2637   // are eliminated just before matching in final_graph_reshape.
2638   {
2639     Node* st = mem;
2640     // If Store 'st' has more than one use, we cannot fold 'st' away.
2641     // For example, 'st' might be the final state at a conditional
2642     // return.  Or, 'st' might be used by some node which is live at
2643     // the same time 'st' is live, which might be unschedulable.  So,
2644     // require exactly ONE user until such time as we clone 'mem' for
2645     // each of 'mem's uses (thus making the exactly-1-user-rule hold
2646     // true).
2647     while (st->is_Store() && st->outcnt() == 1 && st->Opcode() != Op_StoreCM) {
2648       // Looking at a dead closed cycle of memory?
2649       assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
2650       assert(Opcode() == st->Opcode() ||
2651              st->Opcode() == Op_StoreVector ||
2652              Opcode() == Op_StoreVector ||
2653              st->Opcode() == Op_StoreVectorScatter ||
2654              Opcode() == Op_StoreVectorScatter ||
2655              phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw ||
2656              (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode
2657              (Opcode() == Op_StoreI && st->Opcode() == Op_StoreL) || // initialization by arraycopy
2658              (is_mismatched_access() || st->as_Store()->is_mismatched_access()),
2659              "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]);
2660 
2661       if (st->in(MemNode::Address)->eqv_uncast(address) &&
2662           st->as_Store()->memory_size() <= this->memory_size()) {
2663         Node* use = st->raw_out(0);
2664         if (phase->is_IterGVN()) {
2665           phase->is_IterGVN()->rehash_node_delayed(use);
2666         }
2667         // It's OK to do this in the parser, since DU info is always accurate,
2668         // and the parser always refers to nodes via SafePointNode maps.
2669         use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase);
2670         return this;
2671       }
2672       st = st->in(MemNode::Memory);
2673     }
2674   }
2675 
2676 
2677   // Capture an unaliased, unconditional, simple store into an initializer.
2678   // Or, if it is independent of the allocation, hoist it above the allocation.
2679   if (ReduceFieldZeroing && /*can_reshape &&*/
2680       mem->is_Proj() && mem->in(0)->is_Initialize()) {
2681     InitializeNode* init = mem->in(0)->as_Initialize();
2682     intptr_t offset = init->can_capture_store(this, phase, can_reshape);
2683     if (offset > 0) {
2684       Node* moved = init->capture_store(this, offset, phase, can_reshape);
2685       // If the InitializeNode captured me, it made a raw copy of me,
2686       // and I need to disappear.
2687       if (moved != nullptr) {
2688         // %%% hack to ensure that Ideal returns a new node:
2689         mem = MergeMemNode::make(mem);
2690         return mem;             // fold me away
2691       }
2692     }
2693   }
2694 
2695   // Fold reinterpret cast into memory operation:
2696   //    StoreX mem (MoveY2X v) => StoreY mem v
2697   if (value->is_Move()) {
2698     const Type* vt = value->in(1)->bottom_type();
2699     if (has_reinterpret_variant(vt)) {
2700       if (phase->C->post_loop_opts_phase()) {
2701         return convert_to_reinterpret_store(*phase, value->in(1), vt);
2702       } else {
2703         phase->C->record_for_post_loop_opts_igvn(this); // attempt the transformation once loop opts are over
2704       }
2705     }
2706   }
2707 
2708   return nullptr;                  // No further progress
2709 }
2710 
2711 //------------------------------Value-----------------------------------------
2712 const Type* StoreNode::Value(PhaseGVN* phase) const {
2713   // Either input is TOP ==> the result is TOP
2714   const Type *t1 = phase->type( in(MemNode::Memory) );
2715   if( t1 == Type::TOP ) return Type::TOP;
2716   const Type *t2 = phase->type( in(MemNode::Address) );
2717   if( t2 == Type::TOP ) return Type::TOP;
2718   const Type *t3 = phase->type( in(MemNode::ValueIn) );
2719   if( t3 == Type::TOP ) return Type::TOP;
2720   return Type::MEMORY;
2721 }
2722 
2723 //------------------------------Identity---------------------------------------
2724 // Remove redundant stores:
2725 //   Store(m, p, Load(m, p)) changes to m.
2726 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
2727 Node* StoreNode::Identity(PhaseGVN* phase) {
2728   Node* mem = in(MemNode::Memory);
2729   Node* adr = in(MemNode::Address);
2730   Node* val = in(MemNode::ValueIn);
2731 
2732   Node* result = this;
2733 
2734   // Load then Store?  Then the Store is useless
2735   if (val->is_Load() &&
2736       val->in(MemNode::Address)->eqv_uncast(adr) &&
2737       val->in(MemNode::Memory )->eqv_uncast(mem) &&
2738       val->as_Load()->store_Opcode() == Opcode()) {
2739     result = mem;
2740   }
2741 
2742   // Two stores in a row of the same value?
2743   if (result == this &&
2744       mem->is_Store() &&
2745       mem->in(MemNode::Address)->eqv_uncast(adr) &&
2746       mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
2747       mem->Opcode() == Opcode()) {
2748     result = mem;
2749   }
2750 
2751   // Store of zero anywhere into a freshly-allocated object?
2752   // Then the store is useless.
2753   // (It must already have been captured by the InitializeNode.)
2754   if (result == this &&
2755       ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
2756     // a newly allocated object is already all-zeroes everywhere
2757     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
2758       result = mem;
2759     }
2760 
2761     if (result == this) {
2762       // the store may also apply to zero-bits in an earlier object
2763       Node* prev_mem = find_previous_store(phase);
2764       // Steps (a), (b):  Walk past independent stores to find an exact match.
2765       if (prev_mem != nullptr) {
2766         Node* prev_val = can_see_stored_value(prev_mem, phase);
2767         if (prev_val != nullptr && prev_val == val) {
2768           // prev_val and val might differ by a cast; it would be good
2769           // to keep the more informative of the two.
2770           result = mem;
2771         }
2772       }
2773     }
2774   }
2775 
2776   PhaseIterGVN* igvn = phase->is_IterGVN();
2777   if (result != this && igvn != nullptr) {
2778     MemBarNode* trailing = trailing_membar();
2779     if (trailing != nullptr) {
2780 #ifdef ASSERT
2781       const TypeOopPtr* t_oop = phase->type(in(Address))->isa_oopptr();
2782       assert(t_oop == nullptr || t_oop->is_known_instance_field(), "only for non escaping objects");
2783 #endif
2784       trailing->remove(igvn);
2785     }
2786   }
2787 
2788   return result;
2789 }
2790 
2791 //------------------------------match_edge-------------------------------------
2792 // Do we Match on this edge index or not?  Match only memory & value
2793 uint StoreNode::match_edge(uint idx) const {
2794   return idx == MemNode::Address || idx == MemNode::ValueIn;
2795 }
2796 
2797 //------------------------------cmp--------------------------------------------
2798 // Do not common stores up together.  They generally have to be split
2799 // back up anyways, so do not bother.
2800 bool StoreNode::cmp( const Node &n ) const {
2801   return (&n == this);          // Always fail except on self
2802 }
2803 
2804 //------------------------------Ideal_masked_input-----------------------------
2805 // Check for a useless mask before a partial-word store
2806 // (StoreB ... (AndI valIn conIa) )
2807 // If (conIa & mask == mask) this simplifies to
2808 // (StoreB ... (valIn) )
2809 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
2810   Node *val = in(MemNode::ValueIn);
2811   if( val->Opcode() == Op_AndI ) {
2812     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2813     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
2814       set_req_X(MemNode::ValueIn, val->in(1), phase);
2815       return this;
2816     }
2817   }
2818   return nullptr;
2819 }
2820 
2821 
2822 //------------------------------Ideal_sign_extended_input----------------------
2823 // Check for useless sign-extension before a partial-word store
2824 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
2825 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
2826 // (StoreB ... (valIn) )
2827 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
2828   Node *val = in(MemNode::ValueIn);
2829   if( val->Opcode() == Op_RShiftI ) {
2830     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2831     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
2832       Node *shl = val->in(1);
2833       if( shl->Opcode() == Op_LShiftI ) {
2834         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
2835         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
2836           set_req_X(MemNode::ValueIn, shl->in(1), phase);
2837           return this;
2838         }
2839       }
2840     }
2841   }
2842   return nullptr;
2843 }
2844 
2845 //------------------------------value_never_loaded-----------------------------------
2846 // Determine whether there are any possible loads of the value stored.
2847 // For simplicity, we actually check if there are any loads from the
2848 // address stored to, not just for loads of the value stored by this node.
2849 //
2850 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
2851   Node *adr = in(Address);
2852   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
2853   if (adr_oop == nullptr)
2854     return false;
2855   if (!adr_oop->is_known_instance_field())
2856     return false; // if not a distinct instance, there may be aliases of the address
2857   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
2858     Node *use = adr->fast_out(i);
2859     if (use->is_Load() || use->is_LoadStore()) {
2860       return false;
2861     }
2862   }
2863   return true;
2864 }
2865 
2866 MemBarNode* StoreNode::trailing_membar() const {
2867   if (is_release()) {
2868     MemBarNode* trailing_mb = nullptr;
2869     for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
2870       Node* u = fast_out(i);
2871       if (u->is_MemBar()) {
2872         if (u->as_MemBar()->trailing_store()) {
2873           assert(u->Opcode() == Op_MemBarVolatile, "");
2874           assert(trailing_mb == nullptr, "only one");
2875           trailing_mb = u->as_MemBar();
2876 #ifdef ASSERT
2877           Node* leading = u->as_MemBar()->leading_membar();
2878           assert(leading->Opcode() == Op_MemBarRelease, "incorrect membar");
2879           assert(leading->as_MemBar()->leading_store(), "incorrect membar pair");
2880           assert(leading->as_MemBar()->trailing_membar() == u, "incorrect membar pair");
2881 #endif
2882         } else {
2883           assert(u->as_MemBar()->standalone(), "");
2884         }
2885       }
2886     }
2887     return trailing_mb;
2888   }
2889   return nullptr;
2890 }
2891 
2892 
2893 //=============================================================================
2894 //------------------------------Ideal------------------------------------------
2895 // If the store is from an AND mask that leaves the low bits untouched, then
2896 // we can skip the AND operation.  If the store is from a sign-extension
2897 // (a left shift, then right shift) we can skip both.
2898 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
2899   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
2900   if( progress != nullptr ) return progress;
2901 
2902   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
2903   if( progress != nullptr ) return progress;
2904 
2905   // Finally check the default case
2906   return StoreNode::Ideal(phase, can_reshape);
2907 }
2908 
2909 //=============================================================================
2910 //------------------------------Ideal------------------------------------------
2911 // If the store is from an AND mask that leaves the low bits untouched, then
2912 // we can skip the AND operation
2913 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
2914   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
2915   if( progress != nullptr ) return progress;
2916 
2917   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
2918   if( progress != nullptr ) return progress;
2919 
2920   // Finally check the default case
2921   return StoreNode::Ideal(phase, can_reshape);
2922 }
2923 
2924 //=============================================================================
2925 //------------------------------Identity---------------------------------------
2926 Node* StoreCMNode::Identity(PhaseGVN* phase) {
2927   // No need to card mark when storing a null ptr
2928   Node* my_store = in(MemNode::OopStore);
2929   if (my_store->is_Store()) {
2930     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
2931     if( t1 == TypePtr::NULL_PTR ) {
2932       return in(MemNode::Memory);
2933     }
2934   }
2935   return this;
2936 }
2937 
2938 //=============================================================================
2939 //------------------------------Ideal---------------------------------------
2940 Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
2941   Node* progress = StoreNode::Ideal(phase, can_reshape);
2942   if (progress != nullptr) return progress;
2943 
2944   Node* my_store = in(MemNode::OopStore);
2945   if (my_store->is_MergeMem()) {
2946     Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
2947     set_req_X(MemNode::OopStore, mem, phase);
2948     return this;
2949   }
2950 
2951   return nullptr;
2952 }
2953 
2954 //------------------------------Value-----------------------------------------
2955 const Type* StoreCMNode::Value(PhaseGVN* phase) const {
2956   // Either input is TOP ==> the result is TOP (checked in StoreNode::Value).
2957   // If extra input is TOP ==> the result is TOP
2958   const Type* t = phase->type(in(MemNode::OopStore));
2959   if (t == Type::TOP) {
2960     return Type::TOP;
2961   }
2962   return StoreNode::Value(phase);
2963 }
2964 
2965 
2966 //=============================================================================
2967 //----------------------------------SCMemProjNode------------------------------
2968 const Type* SCMemProjNode::Value(PhaseGVN* phase) const
2969 {
2970   if (in(0) == nullptr || phase->type(in(0)) == Type::TOP) {
2971     return Type::TOP;
2972   }
2973   return bottom_type();
2974 }
2975 
2976 //=============================================================================
2977 //----------------------------------LoadStoreNode------------------------------
2978 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
2979   : Node(required),
2980     _type(rt),
2981     _adr_type(at),
2982     _barrier_data(0)
2983 {
2984   init_req(MemNode::Control, c  );
2985   init_req(MemNode::Memory , mem);
2986   init_req(MemNode::Address, adr);
2987   init_req(MemNode::ValueIn, val);
2988   init_class_id(Class_LoadStore);
2989 }
2990 
2991 //------------------------------Value-----------------------------------------
2992 const Type* LoadStoreNode::Value(PhaseGVN* phase) const {
2993   // Either input is TOP ==> the result is TOP
2994   if (!in(MemNode::Control) || phase->type(in(MemNode::Control)) == Type::TOP) {
2995     return Type::TOP;
2996   }
2997   const Type* t = phase->type(in(MemNode::Memory));
2998   if (t == Type::TOP) {
2999     return Type::TOP;
3000   }
3001   t = phase->type(in(MemNode::Address));
3002   if (t == Type::TOP) {
3003     return Type::TOP;
3004   }
3005   t = phase->type(in(MemNode::ValueIn));
3006   if (t == Type::TOP) {
3007     return Type::TOP;
3008   }
3009   return bottom_type();
3010 }
3011 
3012 uint LoadStoreNode::ideal_reg() const {
3013   return _type->ideal_reg();
3014 }
3015 
3016 bool LoadStoreNode::result_not_used() const {
3017   for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
3018     Node *x = fast_out(i);
3019     if (x->Opcode() == Op_SCMemProj) continue;
3020     return false;
3021   }
3022   return true;
3023 }
3024 
3025 MemBarNode* LoadStoreNode::trailing_membar() const {
3026   MemBarNode* trailing = nullptr;
3027   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
3028     Node* u = fast_out(i);
3029     if (u->is_MemBar()) {
3030       if (u->as_MemBar()->trailing_load_store()) {
3031         assert(u->Opcode() == Op_MemBarAcquire, "");
3032         assert(trailing == nullptr, "only one");
3033         trailing = u->as_MemBar();
3034 #ifdef ASSERT
3035         Node* leading = trailing->leading_membar();
3036         assert(support_IRIW_for_not_multiple_copy_atomic_cpu || leading->Opcode() == Op_MemBarRelease, "incorrect membar");
3037         assert(leading->as_MemBar()->leading_load_store(), "incorrect membar pair");
3038         assert(leading->as_MemBar()->trailing_membar() == trailing, "incorrect membar pair");
3039 #endif
3040       } else {
3041         assert(u->as_MemBar()->standalone(), "wrong barrier kind");
3042       }
3043     }
3044   }
3045 
3046   return trailing;
3047 }
3048 
3049 uint LoadStoreNode::size_of() const { return sizeof(*this); }
3050 
3051 //=============================================================================
3052 //----------------------------------LoadStoreConditionalNode--------------------
3053 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, nullptr, TypeInt::BOOL, 5) {
3054   init_req(ExpectedIn, ex );
3055 }
3056 
3057 const Type* LoadStoreConditionalNode::Value(PhaseGVN* phase) const {
3058   // Either input is TOP ==> the result is TOP
3059   const Type* t = phase->type(in(ExpectedIn));
3060   if (t == Type::TOP) {
3061     return Type::TOP;
3062   }
3063   return LoadStoreNode::Value(phase);
3064 }
3065 
3066 //=============================================================================
3067 //-------------------------------adr_type--------------------------------------
3068 const TypePtr* ClearArrayNode::adr_type() const {
3069   Node *adr = in(3);
3070   if (adr == nullptr)  return nullptr; // node is dead
3071   return MemNode::calculate_adr_type(adr->bottom_type());
3072 }
3073 
3074 //------------------------------match_edge-------------------------------------
3075 // Do we Match on this edge index or not?  Do not match memory
3076 uint ClearArrayNode::match_edge(uint idx) const {
3077   return idx > 1;
3078 }
3079 
3080 //------------------------------Identity---------------------------------------
3081 // Clearing a zero length array does nothing
3082 Node* ClearArrayNode::Identity(PhaseGVN* phase) {
3083   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
3084 }
3085 
3086 //------------------------------Idealize---------------------------------------
3087 // Clearing a short array is faster with stores
3088 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3089   // Already know this is a large node, do not try to ideal it
3090   if (_is_large) return nullptr;
3091 
3092   const int unit = BytesPerLong;
3093   const TypeX* t = phase->type(in(2))->isa_intptr_t();
3094   if (!t)  return nullptr;
3095   if (!t->is_con())  return nullptr;
3096   intptr_t raw_count = t->get_con();
3097   intptr_t size = raw_count;
3098   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
3099   // Clearing nothing uses the Identity call.
3100   // Negative clears are possible on dead ClearArrays
3101   // (see jck test stmt114.stmt11402.val).
3102   if (size <= 0 || size % unit != 0)  return nullptr;
3103   intptr_t count = size / unit;
3104   // Length too long; communicate this to matchers and assemblers.
3105   // Assemblers are responsible to produce fast hardware clears for it.
3106   if (size > InitArrayShortSize) {
3107     return new ClearArrayNode(in(0), in(1), in(2), in(3), true);
3108   } else if (size > 2 && Matcher::match_rule_supported_vector(Op_ClearArray, 4, T_LONG)) {
3109     return nullptr;
3110   }
3111   if (!IdealizeClearArrayNode) return nullptr;
3112   Node *mem = in(1);
3113   if( phase->type(mem)==Type::TOP ) return nullptr;
3114   Node *adr = in(3);
3115   const Type* at = phase->type(adr);
3116   if( at==Type::TOP ) return nullptr;
3117   const TypePtr* atp = at->isa_ptr();
3118   // adjust atp to be the correct array element address type
3119   if (atp == nullptr)  atp = TypePtr::BOTTOM;
3120   else              atp = atp->add_offset(Type::OffsetBot);
3121   // Get base for derived pointer purposes
3122   if( adr->Opcode() != Op_AddP ) Unimplemented();
3123   Node *base = adr->in(1);
3124 
3125   Node *zero = phase->makecon(TypeLong::ZERO);
3126   Node *off  = phase->MakeConX(BytesPerLong);
3127   mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
3128   count--;
3129   while( count-- ) {
3130     mem = phase->transform(mem);
3131     adr = phase->transform(new AddPNode(base,adr,off));
3132     mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
3133   }
3134   return mem;
3135 }
3136 
3137 //----------------------------step_through----------------------------------
3138 // Return allocation input memory edge if it is different instance
3139 // or itself if it is the one we are looking for.
3140 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseTransform* phase) {
3141   Node* n = *np;
3142   assert(n->is_ClearArray(), "sanity");
3143   intptr_t offset;
3144   AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
3145   // This method is called only before Allocate nodes are expanded
3146   // during macro nodes expansion. Before that ClearArray nodes are
3147   // only generated in PhaseMacroExpand::generate_arraycopy() (before
3148   // Allocate nodes are expanded) which follows allocations.
3149   assert(alloc != nullptr, "should have allocation");
3150   if (alloc->_idx == instance_id) {
3151     // Can not bypass initialization of the instance we are looking for.
3152     return false;
3153   }
3154   // Otherwise skip it.
3155   InitializeNode* init = alloc->initialization();
3156   if (init != nullptr)
3157     *np = init->in(TypeFunc::Memory);
3158   else
3159     *np = alloc->in(TypeFunc::Memory);
3160   return true;
3161 }
3162 
3163 //----------------------------clear_memory-------------------------------------
3164 // Generate code to initialize object storage to zero.
3165 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3166                                    intptr_t start_offset,
3167                                    Node* end_offset,
3168                                    PhaseGVN* phase) {
3169   intptr_t offset = start_offset;
3170 
3171   int unit = BytesPerLong;
3172   if ((offset % unit) != 0) {
3173     Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset));
3174     adr = phase->transform(adr);
3175     const TypePtr* atp = TypeRawPtr::BOTTOM;
3176     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
3177     mem = phase->transform(mem);
3178     offset += BytesPerInt;
3179   }
3180   assert((offset % unit) == 0, "");
3181 
3182   // Initialize the remaining stuff, if any, with a ClearArray.
3183   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
3184 }
3185 
3186 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3187                                    Node* start_offset,
3188                                    Node* end_offset,
3189                                    PhaseGVN* phase) {
3190   if (start_offset == end_offset) {
3191     // nothing to do
3192     return mem;
3193   }
3194 
3195   int unit = BytesPerLong;
3196   Node* zbase = start_offset;
3197   Node* zend  = end_offset;
3198 
3199   // Scale to the unit required by the CPU:
3200   if (!Matcher::init_array_count_is_in_bytes) {
3201     Node* shift = phase->intcon(exact_log2(unit));
3202     zbase = phase->transform(new URShiftXNode(zbase, shift) );
3203     zend  = phase->transform(new URShiftXNode(zend,  shift) );
3204   }
3205 
3206   // Bulk clear double-words
3207   Node* zsize = phase->transform(new SubXNode(zend, zbase) );
3208   Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) );
3209   mem = new ClearArrayNode(ctl, mem, zsize, adr, false);
3210   return phase->transform(mem);
3211 }
3212 
3213 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3214                                    intptr_t start_offset,
3215                                    intptr_t end_offset,
3216                                    PhaseGVN* phase) {
3217   if (start_offset == end_offset) {
3218     // nothing to do
3219     return mem;
3220   }
3221 
3222   assert((end_offset % BytesPerInt) == 0, "odd end offset");
3223   intptr_t done_offset = end_offset;
3224   if ((done_offset % BytesPerLong) != 0) {
3225     done_offset -= BytesPerInt;
3226   }
3227   if (done_offset > start_offset) {
3228     mem = clear_memory(ctl, mem, dest,
3229                        start_offset, phase->MakeConX(done_offset), phase);
3230   }
3231   if (done_offset < end_offset) { // emit the final 32-bit store
3232     Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset));
3233     adr = phase->transform(adr);
3234     const TypePtr* atp = TypeRawPtr::BOTTOM;
3235     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
3236     mem = phase->transform(mem);
3237     done_offset += BytesPerInt;
3238   }
3239   assert(done_offset == end_offset, "");
3240   return mem;
3241 }
3242 
3243 //=============================================================================
3244 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
3245   : MultiNode(TypeFunc::Parms + (precedent == nullptr? 0: 1)),
3246     _adr_type(C->get_adr_type(alias_idx)), _kind(Standalone)
3247 #ifdef ASSERT
3248   , _pair_idx(0)
3249 #endif
3250 {
3251   init_class_id(Class_MemBar);
3252   Node* top = C->top();
3253   init_req(TypeFunc::I_O,top);
3254   init_req(TypeFunc::FramePtr,top);
3255   init_req(TypeFunc::ReturnAdr,top);
3256   if (precedent != nullptr)
3257     init_req(TypeFunc::Parms, precedent);
3258 }
3259 
3260 //------------------------------cmp--------------------------------------------
3261 uint MemBarNode::hash() const { return NO_HASH; }
3262 bool MemBarNode::cmp( const Node &n ) const {
3263   return (&n == this);          // Always fail except on self
3264 }
3265 
3266 //------------------------------make-------------------------------------------
3267 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
3268   switch (opcode) {
3269   case Op_MemBarAcquire:     return new MemBarAcquireNode(C, atp, pn);
3270   case Op_LoadFence:         return new LoadFenceNode(C, atp, pn);
3271   case Op_MemBarRelease:     return new MemBarReleaseNode(C, atp, pn);
3272   case Op_StoreFence:        return new StoreFenceNode(C, atp, pn);
3273   case Op_MemBarStoreStore:  return new MemBarStoreStoreNode(C, atp, pn);
3274   case Op_StoreStoreFence:   return new StoreStoreFenceNode(C, atp, pn);
3275   case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn);
3276   case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn);
3277   case Op_MemBarVolatile:    return new MemBarVolatileNode(C, atp, pn);
3278   case Op_MemBarCPUOrder:    return new MemBarCPUOrderNode(C, atp, pn);
3279   case Op_OnSpinWait:        return new OnSpinWaitNode(C, atp, pn);
3280   case Op_Initialize:        return new InitializeNode(C, atp, pn);
3281   default: ShouldNotReachHere(); return nullptr;
3282   }
3283 }
3284 
3285 void MemBarNode::remove(PhaseIterGVN *igvn) {
3286   if (outcnt() != 2) {
3287     assert(Opcode() == Op_Initialize, "Only seen when there are no use of init memory");
3288     assert(outcnt() == 1, "Only control then");
3289   }
3290   if (trailing_store() || trailing_load_store()) {
3291     MemBarNode* leading = leading_membar();
3292     if (leading != nullptr) {
3293       assert(leading->trailing_membar() == this, "inconsistent leading/trailing membars");
3294       leading->remove(igvn);
3295     }
3296   }
3297   if (proj_out_or_null(TypeFunc::Memory) != nullptr) {
3298     igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
3299   }
3300   if (proj_out_or_null(TypeFunc::Control) != nullptr) {
3301     igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
3302   }
3303 }
3304 
3305 //------------------------------Ideal------------------------------------------
3306 // Return a node which is more "ideal" than the current node.  Strip out
3307 // control copies
3308 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3309   if (remove_dead_region(phase, can_reshape)) return this;
3310   // Don't bother trying to transform a dead node
3311   if (in(0) && in(0)->is_top()) {
3312     return nullptr;
3313   }
3314 
3315   bool progress = false;
3316   // Eliminate volatile MemBars for scalar replaced objects.
3317   if (can_reshape && req() == (Precedent+1)) {
3318     bool eliminate = false;
3319     int opc = Opcode();
3320     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
3321       // Volatile field loads and stores.
3322       Node* my_mem = in(MemBarNode::Precedent);
3323       // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
3324       if ((my_mem != nullptr) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
3325         // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
3326         // replace this Precedent (decodeN) with the Load instead.
3327         if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1))  {
3328           Node* load_node = my_mem->in(1);
3329           set_req(MemBarNode::Precedent, load_node);
3330           phase->is_IterGVN()->_worklist.push(my_mem);
3331           my_mem = load_node;
3332         } else {
3333           assert(my_mem->unique_out() == this, "sanity");
3334           del_req(Precedent);
3335           phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
3336           my_mem = nullptr;
3337         }
3338         progress = true;
3339       }
3340       if (my_mem != nullptr && my_mem->is_Mem()) {
3341         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
3342         // Check for scalar replaced object reference.
3343         if( t_oop != nullptr && t_oop->is_known_instance_field() &&
3344             t_oop->offset() != Type::OffsetBot &&
3345             t_oop->offset() != Type::OffsetTop) {
3346           eliminate = true;
3347         }
3348       }
3349     } else if (opc == Op_MemBarRelease) {
3350       // Final field stores.
3351       Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent), phase);
3352       if ((alloc != nullptr) && alloc->is_Allocate() &&
3353           alloc->as_Allocate()->does_not_escape_thread()) {
3354         // The allocated object does not escape.
3355         eliminate = true;
3356       }
3357     }
3358     if (eliminate) {
3359       // Replace MemBar projections by its inputs.
3360       PhaseIterGVN* igvn = phase->is_IterGVN();
3361       remove(igvn);
3362       // Must return either the original node (now dead) or a new node
3363       // (Do not return a top here, since that would break the uniqueness of top.)
3364       return new ConINode(TypeInt::ZERO);
3365     }
3366   }
3367   return progress ? this : nullptr;
3368 }
3369 
3370 //------------------------------Value------------------------------------------
3371 const Type* MemBarNode::Value(PhaseGVN* phase) const {
3372   if( !in(0) ) return Type::TOP;
3373   if( phase->type(in(0)) == Type::TOP )
3374     return Type::TOP;
3375   return TypeTuple::MEMBAR;
3376 }
3377 
3378 //------------------------------match------------------------------------------
3379 // Construct projections for memory.
3380 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
3381   switch (proj->_con) {
3382   case TypeFunc::Control:
3383   case TypeFunc::Memory:
3384     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
3385   }
3386   ShouldNotReachHere();
3387   return nullptr;
3388 }
3389 
3390 void MemBarNode::set_store_pair(MemBarNode* leading, MemBarNode* trailing) {
3391   trailing->_kind = TrailingStore;
3392   leading->_kind = LeadingStore;
3393 #ifdef ASSERT
3394   trailing->_pair_idx = leading->_idx;
3395   leading->_pair_idx = leading->_idx;
3396 #endif
3397 }
3398 
3399 void MemBarNode::set_load_store_pair(MemBarNode* leading, MemBarNode* trailing) {
3400   trailing->_kind = TrailingLoadStore;
3401   leading->_kind = LeadingLoadStore;
3402 #ifdef ASSERT
3403   trailing->_pair_idx = leading->_idx;
3404   leading->_pair_idx = leading->_idx;
3405 #endif
3406 }
3407 
3408 MemBarNode* MemBarNode::trailing_membar() const {
3409   ResourceMark rm;
3410   Node* trailing = (Node*)this;
3411   VectorSet seen;
3412   Node_Stack multis(0);
3413   do {
3414     Node* c = trailing;
3415     uint i = 0;
3416     do {
3417       trailing = nullptr;
3418       for (; i < c->outcnt(); i++) {
3419         Node* next = c->raw_out(i);
3420         if (next != c && next->is_CFG()) {
3421           if (c->is_MultiBranch()) {
3422             if (multis.node() == c) {
3423               multis.set_index(i+1);
3424             } else {
3425               multis.push(c, i+1);
3426             }
3427           }
3428           trailing = next;
3429           break;
3430         }
3431       }
3432       if (trailing != nullptr && !seen.test_set(trailing->_idx)) {
3433         break;
3434       }
3435       while (multis.size() > 0) {
3436         c = multis.node();
3437         i = multis.index();
3438         if (i < c->req()) {
3439           break;
3440         }
3441         multis.pop();
3442       }
3443     } while (multis.size() > 0);
3444   } while (!trailing->is_MemBar() || !trailing->as_MemBar()->trailing());
3445 
3446   MemBarNode* mb = trailing->as_MemBar();
3447   assert((mb->_kind == TrailingStore && _kind == LeadingStore) ||
3448          (mb->_kind == TrailingLoadStore && _kind == LeadingLoadStore), "bad trailing membar");
3449   assert(mb->_pair_idx == _pair_idx, "bad trailing membar");
3450   return mb;
3451 }
3452 
3453 MemBarNode* MemBarNode::leading_membar() const {
3454   ResourceMark rm;
3455   VectorSet seen;
3456   Node_Stack regions(0);
3457   Node* leading = in(0);
3458   while (leading != nullptr && (!leading->is_MemBar() || !leading->as_MemBar()->leading())) {
3459     while (leading == nullptr || leading->is_top() || seen.test_set(leading->_idx)) {
3460       leading = nullptr;
3461       while (regions.size() > 0 && leading == nullptr) {
3462         Node* r = regions.node();
3463         uint i = regions.index();
3464         if (i < r->req()) {
3465           leading = r->in(i);
3466           regions.set_index(i+1);
3467         } else {
3468           regions.pop();
3469         }
3470       }
3471       if (leading == nullptr) {
3472         assert(regions.size() == 0, "all paths should have been tried");
3473         return nullptr;
3474       }
3475     }
3476     if (leading->is_Region()) {
3477       regions.push(leading, 2);
3478       leading = leading->in(1);
3479     } else {
3480       leading = leading->in(0);
3481     }
3482   }
3483 #ifdef ASSERT
3484   Unique_Node_List wq;
3485   wq.push((Node*)this);
3486   uint found = 0;
3487   for (uint i = 0; i < wq.size(); i++) {
3488     Node* n = wq.at(i);
3489     if (n->is_Region()) {
3490       for (uint j = 1; j < n->req(); j++) {
3491         Node* in = n->in(j);
3492         if (in != nullptr && !in->is_top()) {
3493           wq.push(in);
3494         }
3495       }
3496     } else {
3497       if (n->is_MemBar() && n->as_MemBar()->leading()) {
3498         assert(n == leading, "consistency check failed");
3499         found++;
3500       } else {
3501         Node* in = n->in(0);
3502         if (in != nullptr && !in->is_top()) {
3503           wq.push(in);
3504         }
3505       }
3506     }
3507   }
3508   assert(found == 1 || (found == 0 && leading == nullptr), "consistency check failed");
3509 #endif
3510   if (leading == nullptr) {
3511     return nullptr;
3512   }
3513   MemBarNode* mb = leading->as_MemBar();
3514   assert((mb->_kind == LeadingStore && _kind == TrailingStore) ||
3515          (mb->_kind == LeadingLoadStore && _kind == TrailingLoadStore), "bad leading membar");
3516   assert(mb->_pair_idx == _pair_idx, "bad leading membar");
3517   return mb;
3518 }
3519 
3520 
3521 //===========================InitializeNode====================================
3522 // SUMMARY:
3523 // This node acts as a memory barrier on raw memory, after some raw stores.
3524 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
3525 // The Initialize can 'capture' suitably constrained stores as raw inits.
3526 // It can coalesce related raw stores into larger units (called 'tiles').
3527 // It can avoid zeroing new storage for memory units which have raw inits.
3528 // At macro-expansion, it is marked 'complete', and does not optimize further.
3529 //
3530 // EXAMPLE:
3531 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
3532 //   ctl = incoming control; mem* = incoming memory
3533 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
3534 // First allocate uninitialized memory and fill in the header:
3535 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
3536 //   ctl := alloc.Control; mem* := alloc.Memory*
3537 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
3538 // Then initialize to zero the non-header parts of the raw memory block:
3539 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
3540 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
3541 // After the initialize node executes, the object is ready for service:
3542 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
3543 // Suppose its body is immediately initialized as {1,2}:
3544 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3545 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3546 //   mem.SLICE(#short[*]) := store2
3547 //
3548 // DETAILS:
3549 // An InitializeNode collects and isolates object initialization after
3550 // an AllocateNode and before the next possible safepoint.  As a
3551 // memory barrier (MemBarNode), it keeps critical stores from drifting
3552 // down past any safepoint or any publication of the allocation.
3553 // Before this barrier, a newly-allocated object may have uninitialized bits.
3554 // After this barrier, it may be treated as a real oop, and GC is allowed.
3555 //
3556 // The semantics of the InitializeNode include an implicit zeroing of
3557 // the new object from object header to the end of the object.
3558 // (The object header and end are determined by the AllocateNode.)
3559 //
3560 // Certain stores may be added as direct inputs to the InitializeNode.
3561 // These stores must update raw memory, and they must be to addresses
3562 // derived from the raw address produced by AllocateNode, and with
3563 // a constant offset.  They must be ordered by increasing offset.
3564 // The first one is at in(RawStores), the last at in(req()-1).
3565 // Unlike most memory operations, they are not linked in a chain,
3566 // but are displayed in parallel as users of the rawmem output of
3567 // the allocation.
3568 //
3569 // (See comments in InitializeNode::capture_store, which continue
3570 // the example given above.)
3571 //
3572 // When the associated Allocate is macro-expanded, the InitializeNode
3573 // may be rewritten to optimize collected stores.  A ClearArrayNode
3574 // may also be created at that point to represent any required zeroing.
3575 // The InitializeNode is then marked 'complete', prohibiting further
3576 // capturing of nearby memory operations.
3577 //
3578 // During macro-expansion, all captured initializations which store
3579 // constant values of 32 bits or smaller are coalesced (if advantageous)
3580 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
3581 // initialized in fewer memory operations.  Memory words which are
3582 // covered by neither tiles nor non-constant stores are pre-zeroed
3583 // by explicit stores of zero.  (The code shape happens to do all
3584 // zeroing first, then all other stores, with both sequences occurring
3585 // in order of ascending offsets.)
3586 //
3587 // Alternatively, code may be inserted between an AllocateNode and its
3588 // InitializeNode, to perform arbitrary initialization of the new object.
3589 // E.g., the object copying intrinsics insert complex data transfers here.
3590 // The initialization must then be marked as 'complete' disable the
3591 // built-in zeroing semantics and the collection of initializing stores.
3592 //
3593 // While an InitializeNode is incomplete, reads from the memory state
3594 // produced by it are optimizable if they match the control edge and
3595 // new oop address associated with the allocation/initialization.
3596 // They return a stored value (if the offset matches) or else zero.
3597 // A write to the memory state, if it matches control and address,
3598 // and if it is to a constant offset, may be 'captured' by the
3599 // InitializeNode.  It is cloned as a raw memory operation and rewired
3600 // inside the initialization, to the raw oop produced by the allocation.
3601 // Operations on addresses which are provably distinct (e.g., to
3602 // other AllocateNodes) are allowed to bypass the initialization.
3603 //
3604 // The effect of all this is to consolidate object initialization
3605 // (both arrays and non-arrays, both piecewise and bulk) into a
3606 // single location, where it can be optimized as a unit.
3607 //
3608 // Only stores with an offset less than TrackedInitializationLimit words
3609 // will be considered for capture by an InitializeNode.  This puts a
3610 // reasonable limit on the complexity of optimized initializations.
3611 
3612 //---------------------------InitializeNode------------------------------------
3613 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
3614   : MemBarNode(C, adr_type, rawoop),
3615     _is_complete(Incomplete), _does_not_escape(false)
3616 {
3617   init_class_id(Class_Initialize);
3618 
3619   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
3620   assert(in(RawAddress) == rawoop, "proper init");
3621   // Note:  allocation() can be null, for secondary initialization barriers
3622 }
3623 
3624 // Since this node is not matched, it will be processed by the
3625 // register allocator.  Declare that there are no constraints
3626 // on the allocation of the RawAddress edge.
3627 const RegMask &InitializeNode::in_RegMask(uint idx) const {
3628   // This edge should be set to top, by the set_complete.  But be conservative.
3629   if (idx == InitializeNode::RawAddress)
3630     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
3631   return RegMask::Empty;
3632 }
3633 
3634 Node* InitializeNode::memory(uint alias_idx) {
3635   Node* mem = in(Memory);
3636   if (mem->is_MergeMem()) {
3637     return mem->as_MergeMem()->memory_at(alias_idx);
3638   } else {
3639     // incoming raw memory is not split
3640     return mem;
3641   }
3642 }
3643 
3644 bool InitializeNode::is_non_zero() {
3645   if (is_complete())  return false;
3646   remove_extra_zeroes();
3647   return (req() > RawStores);
3648 }
3649 
3650 void InitializeNode::set_complete(PhaseGVN* phase) {
3651   assert(!is_complete(), "caller responsibility");
3652   _is_complete = Complete;
3653 
3654   // After this node is complete, it contains a bunch of
3655   // raw-memory initializations.  There is no need for
3656   // it to have anything to do with non-raw memory effects.
3657   // Therefore, tell all non-raw users to re-optimize themselves,
3658   // after skipping the memory effects of this initialization.
3659   PhaseIterGVN* igvn = phase->is_IterGVN();
3660   if (igvn)  igvn->add_users_to_worklist(this);
3661 }
3662 
3663 // convenience function
3664 // return false if the init contains any stores already
3665 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
3666   InitializeNode* init = initialization();
3667   if (init == nullptr || init->is_complete())  return false;
3668   init->remove_extra_zeroes();
3669   // for now, if this allocation has already collected any inits, bail:
3670   if (init->is_non_zero())  return false;
3671   init->set_complete(phase);
3672   return true;
3673 }
3674 
3675 void InitializeNode::remove_extra_zeroes() {
3676   if (req() == RawStores)  return;
3677   Node* zmem = zero_memory();
3678   uint fill = RawStores;
3679   for (uint i = fill; i < req(); i++) {
3680     Node* n = in(i);
3681     if (n->is_top() || n == zmem)  continue;  // skip
3682     if (fill < i)  set_req(fill, n);          // compact
3683     ++fill;
3684   }
3685   // delete any empty spaces created:
3686   while (fill < req()) {
3687     del_req(fill);
3688   }
3689 }
3690 
3691 // Helper for remembering which stores go with which offsets.
3692 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
3693   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
3694   intptr_t offset = -1;
3695   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
3696                                                phase, offset);
3697   if (base == nullptr)  return -1;  // something is dead,
3698   if (offset < 0)       return -1;  //        dead, dead
3699   return offset;
3700 }
3701 
3702 // Helper for proving that an initialization expression is
3703 // "simple enough" to be folded into an object initialization.
3704 // Attempts to prove that a store's initial value 'n' can be captured
3705 // within the initialization without creating a vicious cycle, such as:
3706 //     { Foo p = new Foo(); p.next = p; }
3707 // True for constants and parameters and small combinations thereof.
3708 bool InitializeNode::detect_init_independence(Node* value, PhaseGVN* phase) {
3709   ResourceMark rm;
3710   Unique_Node_List worklist;
3711   worklist.push(value);
3712 
3713   uint complexity_limit = 20;
3714   for (uint j = 0; j < worklist.size(); j++) {
3715     if (j >= complexity_limit) {
3716       return false;  // Bail out if processed too many nodes
3717     }
3718 
3719     Node* n = worklist.at(j);
3720     if (n == nullptr)   continue;   // (can this really happen?)
3721     if (n->is_Proj())   n = n->in(0);
3722     if (n == this)      return false;  // found a cycle
3723     if (n->is_Con())    continue;
3724     if (n->is_Start())  continue;   // params, etc., are OK
3725     if (n->is_Root())   continue;   // even better
3726 
3727     // There cannot be any dependency if 'n' is a CFG node that dominates the current allocation
3728     if (n->is_CFG() && phase->is_dominator(n, allocation())) {
3729       continue;
3730     }
3731 
3732     Node* ctl = n->in(0);
3733     if (ctl != nullptr && !ctl->is_top()) {
3734       if (ctl->is_Proj())  ctl = ctl->in(0);
3735       if (ctl == this)  return false;
3736 
3737       // If we already know that the enclosing memory op is pinned right after
3738       // the init, then any control flow that the store has picked up
3739       // must have preceded the init, or else be equal to the init.
3740       // Even after loop optimizations (which might change control edges)
3741       // a store is never pinned *before* the availability of its inputs.
3742       if (!MemNode::all_controls_dominate(n, this))
3743         return false;                  // failed to prove a good control
3744     }
3745 
3746     // Check data edges for possible dependencies on 'this'.
3747     for (uint i = 1; i < n->req(); i++) {
3748       Node* m = n->in(i);
3749       if (m == nullptr || m == n || m->is_top())  continue;
3750 
3751       // Only process data inputs once
3752       worklist.push(m);
3753     }
3754   }
3755 
3756   return true;
3757 }
3758 
3759 // Here are all the checks a Store must pass before it can be moved into
3760 // an initialization.  Returns zero if a check fails.
3761 // On success, returns the (constant) offset to which the store applies,
3762 // within the initialized memory.
3763 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseGVN* phase, bool can_reshape) {
3764   const int FAIL = 0;
3765   if (st->req() != MemNode::ValueIn + 1)
3766     return FAIL;                // an inscrutable StoreNode (card mark?)
3767   Node* ctl = st->in(MemNode::Control);
3768   if (!(ctl != nullptr && ctl->is_Proj() && ctl->in(0) == this))
3769     return FAIL;                // must be unconditional after the initialization
3770   Node* mem = st->in(MemNode::Memory);
3771   if (!(mem->is_Proj() && mem->in(0) == this))
3772     return FAIL;                // must not be preceded by other stores
3773   Node* adr = st->in(MemNode::Address);
3774   intptr_t offset;
3775   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
3776   if (alloc == nullptr)
3777     return FAIL;                // inscrutable address
3778   if (alloc != allocation())
3779     return FAIL;                // wrong allocation!  (store needs to float up)
3780   int size_in_bytes = st->memory_size();
3781   if ((size_in_bytes != 0) && (offset % size_in_bytes) != 0) {
3782     return FAIL;                // mismatched access
3783   }
3784   Node* val = st->in(MemNode::ValueIn);
3785 
3786   if (!detect_init_independence(val, phase))
3787     return FAIL;                // stored value must be 'simple enough'
3788 
3789   // The Store can be captured only if nothing after the allocation
3790   // and before the Store is using the memory location that the store
3791   // overwrites.
3792   bool failed = false;
3793   // If is_complete_with_arraycopy() is true the shape of the graph is
3794   // well defined and is safe so no need for extra checks.
3795   if (!is_complete_with_arraycopy()) {
3796     // We are going to look at each use of the memory state following
3797     // the allocation to make sure nothing reads the memory that the
3798     // Store writes.
3799     const TypePtr* t_adr = phase->type(adr)->isa_ptr();
3800     int alias_idx = phase->C->get_alias_index(t_adr);
3801     ResourceMark rm;
3802     Unique_Node_List mems;
3803     mems.push(mem);
3804     Node* unique_merge = nullptr;
3805     for (uint next = 0; next < mems.size(); ++next) {
3806       Node *m  = mems.at(next);
3807       for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
3808         Node *n = m->fast_out(j);
3809         if (n->outcnt() == 0) {
3810           continue;
3811         }
3812         if (n == st) {
3813           continue;
3814         } else if (n->in(0) != nullptr && n->in(0) != ctl) {
3815           // If the control of this use is different from the control
3816           // of the Store which is right after the InitializeNode then
3817           // this node cannot be between the InitializeNode and the
3818           // Store.
3819           continue;
3820         } else if (n->is_MergeMem()) {
3821           if (n->as_MergeMem()->memory_at(alias_idx) == m) {
3822             // We can hit a MergeMemNode (that will likely go away
3823             // later) that is a direct use of the memory state
3824             // following the InitializeNode on the same slice as the
3825             // store node that we'd like to capture. We need to check
3826             // the uses of the MergeMemNode.
3827             mems.push(n);
3828           }
3829         } else if (n->is_Mem()) {
3830           Node* other_adr = n->in(MemNode::Address);
3831           if (other_adr == adr) {
3832             failed = true;
3833             break;
3834           } else {
3835             const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
3836             if (other_t_adr != nullptr) {
3837               int other_alias_idx = phase->C->get_alias_index(other_t_adr);
3838               if (other_alias_idx == alias_idx) {
3839                 // A load from the same memory slice as the store right
3840                 // after the InitializeNode. We check the control of the
3841                 // object/array that is loaded from. If it's the same as
3842                 // the store control then we cannot capture the store.
3843                 assert(!n->is_Store(), "2 stores to same slice on same control?");
3844                 Node* base = other_adr;
3845                 assert(base->is_AddP(), "should be addp but is %s", base->Name());
3846                 base = base->in(AddPNode::Base);
3847                 if (base != nullptr) {
3848                   base = base->uncast();
3849                   if (base->is_Proj() && base->in(0) == alloc) {
3850                     failed = true;
3851                     break;
3852                   }
3853                 }
3854               }
3855             }
3856           }
3857         } else {
3858           failed = true;
3859           break;
3860         }
3861       }
3862     }
3863   }
3864   if (failed) {
3865     if (!can_reshape) {
3866       // We decided we couldn't capture the store during parsing. We
3867       // should try again during the next IGVN once the graph is
3868       // cleaner.
3869       phase->C->record_for_igvn(st);
3870     }
3871     return FAIL;
3872   }
3873 
3874   return offset;                // success
3875 }
3876 
3877 // Find the captured store in(i) which corresponds to the range
3878 // [start..start+size) in the initialized object.
3879 // If there is one, return its index i.  If there isn't, return the
3880 // negative of the index where it should be inserted.
3881 // Return 0 if the queried range overlaps an initialization boundary
3882 // or if dead code is encountered.
3883 // If size_in_bytes is zero, do not bother with overlap checks.
3884 int InitializeNode::captured_store_insertion_point(intptr_t start,
3885                                                    int size_in_bytes,
3886                                                    PhaseTransform* phase) {
3887   const int FAIL = 0, MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize);
3888 
3889   if (is_complete())
3890     return FAIL;                // arraycopy got here first; punt
3891 
3892   assert(allocation() != nullptr, "must be present");
3893 
3894   // no negatives, no header fields:
3895   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
3896 
3897   // after a certain size, we bail out on tracking all the stores:
3898   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3899   if (start >= ti_limit)  return FAIL;
3900 
3901   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
3902     if (i >= limit)  return -(int)i; // not found; here is where to put it
3903 
3904     Node*    st     = in(i);
3905     intptr_t st_off = get_store_offset(st, phase);
3906     if (st_off < 0) {
3907       if (st != zero_memory()) {
3908         return FAIL;            // bail out if there is dead garbage
3909       }
3910     } else if (st_off > start) {
3911       // ...we are done, since stores are ordered
3912       if (st_off < start + size_in_bytes) {
3913         return FAIL;            // the next store overlaps
3914       }
3915       return -(int)i;           // not found; here is where to put it
3916     } else if (st_off < start) {
3917       assert(st->as_Store()->memory_size() <= MAX_STORE, "");
3918       if (size_in_bytes != 0 &&
3919           start < st_off + MAX_STORE &&
3920           start < st_off + st->as_Store()->memory_size()) {
3921         return FAIL;            // the previous store overlaps
3922       }
3923     } else {
3924       if (size_in_bytes != 0 &&
3925           st->as_Store()->memory_size() != size_in_bytes) {
3926         return FAIL;            // mismatched store size
3927       }
3928       return i;
3929     }
3930 
3931     ++i;
3932   }
3933 }
3934 
3935 // Look for a captured store which initializes at the offset 'start'
3936 // with the given size.  If there is no such store, and no other
3937 // initialization interferes, then return zero_memory (the memory
3938 // projection of the AllocateNode).
3939 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
3940                                           PhaseTransform* phase) {
3941   assert(stores_are_sane(phase), "");
3942   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3943   if (i == 0) {
3944     return nullptr;              // something is dead
3945   } else if (i < 0) {
3946     return zero_memory();       // just primordial zero bits here
3947   } else {
3948     Node* st = in(i);           // here is the store at this position
3949     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
3950     return st;
3951   }
3952 }
3953 
3954 // Create, as a raw pointer, an address within my new object at 'offset'.
3955 Node* InitializeNode::make_raw_address(intptr_t offset,
3956                                        PhaseTransform* phase) {
3957   Node* addr = in(RawAddress);
3958   if (offset != 0) {
3959     Compile* C = phase->C;
3960     addr = phase->transform( new AddPNode(C->top(), addr,
3961                                                  phase->MakeConX(offset)) );
3962   }
3963   return addr;
3964 }
3965 
3966 // Clone the given store, converting it into a raw store
3967 // initializing a field or element of my new object.
3968 // Caller is responsible for retiring the original store,
3969 // with subsume_node or the like.
3970 //
3971 // From the example above InitializeNode::InitializeNode,
3972 // here are the old stores to be captured:
3973 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3974 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3975 //
3976 // Here is the changed code; note the extra edges on init:
3977 //   alloc = (Allocate ...)
3978 //   rawoop = alloc.RawAddress
3979 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
3980 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
3981 //   init = (Initialize alloc.Control alloc.Memory rawoop
3982 //                      rawstore1 rawstore2)
3983 //
3984 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
3985                                     PhaseGVN* phase, bool can_reshape) {
3986   assert(stores_are_sane(phase), "");
3987 
3988   if (start < 0)  return nullptr;
3989   assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
3990 
3991   Compile* C = phase->C;
3992   int size_in_bytes = st->memory_size();
3993   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3994   if (i == 0)  return nullptr;  // bail out
3995   Node* prev_mem = nullptr;     // raw memory for the captured store
3996   if (i > 0) {
3997     prev_mem = in(i);           // there is a pre-existing store under this one
3998     set_req(i, C->top());       // temporarily disconnect it
3999     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
4000   } else {
4001     i = -i;                     // no pre-existing store
4002     prev_mem = zero_memory();   // a slice of the newly allocated object
4003     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
4004       set_req(--i, C->top());   // reuse this edge; it has been folded away
4005     else
4006       ins_req(i, C->top());     // build a new edge
4007   }
4008   Node* new_st = st->clone();
4009   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4010   new_st->set_req(MemNode::Control, in(Control));
4011   new_st->set_req(MemNode::Memory,  prev_mem);
4012   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
4013   bs->eliminate_gc_barrier_data(new_st);
4014   new_st = phase->transform(new_st);
4015 
4016   // At this point, new_st might have swallowed a pre-existing store
4017   // at the same offset, or perhaps new_st might have disappeared,
4018   // if it redundantly stored the same value (or zero to fresh memory).
4019 
4020   // In any case, wire it in:
4021   PhaseIterGVN* igvn = phase->is_IterGVN();
4022   if (igvn) {
4023     igvn->rehash_node_delayed(this);
4024   }
4025   set_req(i, new_st);
4026 
4027   // The caller may now kill the old guy.
4028   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
4029   assert(check_st == new_st || check_st == nullptr, "must be findable");
4030   assert(!is_complete(), "");
4031   return new_st;
4032 }
4033 
4034 static bool store_constant(jlong* tiles, int num_tiles,
4035                            intptr_t st_off, int st_size,
4036                            jlong con) {
4037   if ((st_off & (st_size-1)) != 0)
4038     return false;               // strange store offset (assume size==2**N)
4039   address addr = (address)tiles + st_off;
4040   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
4041   switch (st_size) {
4042   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
4043   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
4044   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
4045   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
4046   default: return false;        // strange store size (detect size!=2**N here)
4047   }
4048   return true;                  // return success to caller
4049 }
4050 
4051 // Coalesce subword constants into int constants and possibly
4052 // into long constants.  The goal, if the CPU permits,
4053 // is to initialize the object with a small number of 64-bit tiles.
4054 // Also, convert floating-point constants to bit patterns.
4055 // Non-constants are not relevant to this pass.
4056 //
4057 // In terms of the running example on InitializeNode::InitializeNode
4058 // and InitializeNode::capture_store, here is the transformation
4059 // of rawstore1 and rawstore2 into rawstore12:
4060 //   alloc = (Allocate ...)
4061 //   rawoop = alloc.RawAddress
4062 //   tile12 = 0x00010002
4063 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
4064 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
4065 //
4066 void
4067 InitializeNode::coalesce_subword_stores(intptr_t header_size,
4068                                         Node* size_in_bytes,
4069                                         PhaseGVN* phase) {
4070   Compile* C = phase->C;
4071 
4072   assert(stores_are_sane(phase), "");
4073   // Note:  After this pass, they are not completely sane,
4074   // since there may be some overlaps.
4075 
4076   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
4077 
4078   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
4079   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
4080   size_limit = MIN2(size_limit, ti_limit);
4081   size_limit = align_up(size_limit, BytesPerLong);
4082   int num_tiles = size_limit / BytesPerLong;
4083 
4084   // allocate space for the tile map:
4085   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
4086   jlong  tiles_buf[small_len];
4087   Node*  nodes_buf[small_len];
4088   jlong  inits_buf[small_len];
4089   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
4090                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
4091   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
4092                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
4093   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
4094                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
4095   // tiles: exact bitwise model of all primitive constants
4096   // nodes: last constant-storing node subsumed into the tiles model
4097   // inits: which bytes (in each tile) are touched by any initializations
4098 
4099   //// Pass A: Fill in the tile model with any relevant stores.
4100 
4101   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
4102   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
4103   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
4104   Node* zmem = zero_memory(); // initially zero memory state
4105   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
4106     Node* st = in(i);
4107     intptr_t st_off = get_store_offset(st, phase);
4108 
4109     // Figure out the store's offset and constant value:
4110     if (st_off < header_size)             continue; //skip (ignore header)
4111     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
4112     int st_size = st->as_Store()->memory_size();
4113     if (st_off + st_size > size_limit)    break;
4114 
4115     // Record which bytes are touched, whether by constant or not.
4116     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
4117       continue;                 // skip (strange store size)
4118 
4119     const Type* val = phase->type(st->in(MemNode::ValueIn));
4120     if (!val->singleton())                continue; //skip (non-con store)
4121     BasicType type = val->basic_type();
4122 
4123     jlong con = 0;
4124     switch (type) {
4125     case T_INT:    con = val->is_int()->get_con();  break;
4126     case T_LONG:   con = val->is_long()->get_con(); break;
4127     case T_FLOAT:  con = jint_cast(val->getf());    break;
4128     case T_DOUBLE: con = jlong_cast(val->getd());   break;
4129     default:                              continue; //skip (odd store type)
4130     }
4131 
4132     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
4133         st->Opcode() == Op_StoreL) {
4134       continue;                 // This StoreL is already optimal.
4135     }
4136 
4137     // Store down the constant.
4138     store_constant(tiles, num_tiles, st_off, st_size, con);
4139 
4140     intptr_t j = st_off >> LogBytesPerLong;
4141 
4142     if (type == T_INT && st_size == BytesPerInt
4143         && (st_off & BytesPerInt) == BytesPerInt) {
4144       jlong lcon = tiles[j];
4145       if (!Matcher::isSimpleConstant64(lcon) &&
4146           st->Opcode() == Op_StoreI) {
4147         // This StoreI is already optimal by itself.
4148         jint* intcon = (jint*) &tiles[j];
4149         intcon[1] = 0;  // undo the store_constant()
4150 
4151         // If the previous store is also optimal by itself, back up and
4152         // undo the action of the previous loop iteration... if we can.
4153         // But if we can't, just let the previous half take care of itself.
4154         st = nodes[j];
4155         st_off -= BytesPerInt;
4156         con = intcon[0];
4157         if (con != 0 && st != nullptr && st->Opcode() == Op_StoreI) {
4158           assert(st_off >= header_size, "still ignoring header");
4159           assert(get_store_offset(st, phase) == st_off, "must be");
4160           assert(in(i-1) == zmem, "must be");
4161           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
4162           assert(con == tcon->is_int()->get_con(), "must be");
4163           // Undo the effects of the previous loop trip, which swallowed st:
4164           intcon[0] = 0;        // undo store_constant()
4165           set_req(i-1, st);     // undo set_req(i, zmem)
4166           nodes[j] = nullptr;   // undo nodes[j] = st
4167           --old_subword;        // undo ++old_subword
4168         }
4169         continue;               // This StoreI is already optimal.
4170       }
4171     }
4172 
4173     // This store is not needed.
4174     set_req(i, zmem);
4175     nodes[j] = st;              // record for the moment
4176     if (st_size < BytesPerLong) // something has changed
4177           ++old_subword;        // includes int/float, but who's counting...
4178     else  ++old_long;
4179   }
4180 
4181   if ((old_subword + old_long) == 0)
4182     return;                     // nothing more to do
4183 
4184   //// Pass B: Convert any non-zero tiles into optimal constant stores.
4185   // Be sure to insert them before overlapping non-constant stores.
4186   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
4187   for (int j = 0; j < num_tiles; j++) {
4188     jlong con  = tiles[j];
4189     jlong init = inits[j];
4190     if (con == 0)  continue;
4191     jint con0,  con1;           // split the constant, address-wise
4192     jint init0, init1;          // split the init map, address-wise
4193     { union { jlong con; jint intcon[2]; } u;
4194       u.con = con;
4195       con0  = u.intcon[0];
4196       con1  = u.intcon[1];
4197       u.con = init;
4198       init0 = u.intcon[0];
4199       init1 = u.intcon[1];
4200     }
4201 
4202     Node* old = nodes[j];
4203     assert(old != nullptr, "need the prior store");
4204     intptr_t offset = (j * BytesPerLong);
4205 
4206     bool split = !Matcher::isSimpleConstant64(con);
4207 
4208     if (offset < header_size) {
4209       assert(offset + BytesPerInt >= header_size, "second int counts");
4210       assert(*(jint*)&tiles[j] == 0, "junk in header");
4211       split = true;             // only the second word counts
4212       // Example:  int a[] = { 42 ... }
4213     } else if (con0 == 0 && init0 == -1) {
4214       split = true;             // first word is covered by full inits
4215       // Example:  int a[] = { ... foo(), 42 ... }
4216     } else if (con1 == 0 && init1 == -1) {
4217       split = true;             // second word is covered by full inits
4218       // Example:  int a[] = { ... 42, foo() ... }
4219     }
4220 
4221     // Here's a case where init0 is neither 0 nor -1:
4222     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
4223     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
4224     // In this case the tile is not split; it is (jlong)42.
4225     // The big tile is stored down, and then the foo() value is inserted.
4226     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
4227 
4228     Node* ctl = old->in(MemNode::Control);
4229     Node* adr = make_raw_address(offset, phase);
4230     const TypePtr* atp = TypeRawPtr::BOTTOM;
4231 
4232     // One or two coalesced stores to plop down.
4233     Node*    st[2];
4234     intptr_t off[2];
4235     int  nst = 0;
4236     if (!split) {
4237       ++new_long;
4238       off[nst] = offset;
4239       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4240                                   phase->longcon(con), T_LONG, MemNode::unordered);
4241     } else {
4242       // Omit either if it is a zero.
4243       if (con0 != 0) {
4244         ++new_int;
4245         off[nst]  = offset;
4246         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4247                                     phase->intcon(con0), T_INT, MemNode::unordered);
4248       }
4249       if (con1 != 0) {
4250         ++new_int;
4251         offset += BytesPerInt;
4252         adr = make_raw_address(offset, phase);
4253         off[nst]  = offset;
4254         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4255                                     phase->intcon(con1), T_INT, MemNode::unordered);
4256       }
4257     }
4258 
4259     // Insert second store first, then the first before the second.
4260     // Insert each one just before any overlapping non-constant stores.
4261     while (nst > 0) {
4262       Node* st1 = st[--nst];
4263       C->copy_node_notes_to(st1, old);
4264       st1 = phase->transform(st1);
4265       offset = off[nst];
4266       assert(offset >= header_size, "do not smash header");
4267       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
4268       guarantee(ins_idx != 0, "must re-insert constant store");
4269       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
4270       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
4271         set_req(--ins_idx, st1);
4272       else
4273         ins_req(ins_idx, st1);
4274     }
4275   }
4276 
4277   if (PrintCompilation && WizardMode)
4278     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
4279                   old_subword, old_long, new_int, new_long);
4280   if (C->log() != nullptr)
4281     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
4282                    old_subword, old_long, new_int, new_long);
4283 
4284   // Clean up any remaining occurrences of zmem:
4285   remove_extra_zeroes();
4286 }
4287 
4288 // Explore forward from in(start) to find the first fully initialized
4289 // word, and return its offset.  Skip groups of subword stores which
4290 // together initialize full words.  If in(start) is itself part of a
4291 // fully initialized word, return the offset of in(start).  If there
4292 // are no following full-word stores, or if something is fishy, return
4293 // a negative value.
4294 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
4295   int       int_map = 0;
4296   intptr_t  int_map_off = 0;
4297   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
4298 
4299   for (uint i = start, limit = req(); i < limit; i++) {
4300     Node* st = in(i);
4301 
4302     intptr_t st_off = get_store_offset(st, phase);
4303     if (st_off < 0)  break;  // return conservative answer
4304 
4305     int st_size = st->as_Store()->memory_size();
4306     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
4307       return st_off;            // we found a complete word init
4308     }
4309 
4310     // update the map:
4311 
4312     intptr_t this_int_off = align_down(st_off, BytesPerInt);
4313     if (this_int_off != int_map_off) {
4314       // reset the map:
4315       int_map = 0;
4316       int_map_off = this_int_off;
4317     }
4318 
4319     int subword_off = st_off - this_int_off;
4320     int_map |= right_n_bits(st_size) << subword_off;
4321     if ((int_map & FULL_MAP) == FULL_MAP) {
4322       return this_int_off;      // we found a complete word init
4323     }
4324 
4325     // Did this store hit or cross the word boundary?
4326     intptr_t next_int_off = align_down(st_off + st_size, BytesPerInt);
4327     if (next_int_off == this_int_off + BytesPerInt) {
4328       // We passed the current int, without fully initializing it.
4329       int_map_off = next_int_off;
4330       int_map >>= BytesPerInt;
4331     } else if (next_int_off > this_int_off + BytesPerInt) {
4332       // We passed the current and next int.
4333       return this_int_off + BytesPerInt;
4334     }
4335   }
4336 
4337   return -1;
4338 }
4339 
4340 
4341 // Called when the associated AllocateNode is expanded into CFG.
4342 // At this point, we may perform additional optimizations.
4343 // Linearize the stores by ascending offset, to make memory
4344 // activity as coherent as possible.
4345 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
4346                                       intptr_t header_size,
4347                                       Node* size_in_bytes,
4348                                       PhaseIterGVN* phase) {
4349   assert(!is_complete(), "not already complete");
4350   assert(stores_are_sane(phase), "");
4351   assert(allocation() != nullptr, "must be present");
4352 
4353   remove_extra_zeroes();
4354 
4355   if (ReduceFieldZeroing || ReduceBulkZeroing)
4356     // reduce instruction count for common initialization patterns
4357     coalesce_subword_stores(header_size, size_in_bytes, phase);
4358 
4359   Node* zmem = zero_memory();   // initially zero memory state
4360   Node* inits = zmem;           // accumulating a linearized chain of inits
4361   #ifdef ASSERT
4362   intptr_t first_offset = allocation()->minimum_header_size();
4363   intptr_t last_init_off = first_offset;  // previous init offset
4364   intptr_t last_init_end = first_offset;  // previous init offset+size
4365   intptr_t last_tile_end = first_offset;  // previous tile offset+size
4366   #endif
4367   intptr_t zeroes_done = header_size;
4368 
4369   bool do_zeroing = true;       // we might give up if inits are very sparse
4370   int  big_init_gaps = 0;       // how many large gaps have we seen?
4371 
4372   if (UseTLAB && ZeroTLAB)  do_zeroing = false;
4373   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
4374 
4375   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
4376     Node* st = in(i);
4377     intptr_t st_off = get_store_offset(st, phase);
4378     if (st_off < 0)
4379       break;                    // unknown junk in the inits
4380     if (st->in(MemNode::Memory) != zmem)
4381       break;                    // complicated store chains somehow in list
4382 
4383     int st_size = st->as_Store()->memory_size();
4384     intptr_t next_init_off = st_off + st_size;
4385 
4386     if (do_zeroing && zeroes_done < next_init_off) {
4387       // See if this store needs a zero before it or under it.
4388       intptr_t zeroes_needed = st_off;
4389 
4390       if (st_size < BytesPerInt) {
4391         // Look for subword stores which only partially initialize words.
4392         // If we find some, we must lay down some word-level zeroes first,
4393         // underneath the subword stores.
4394         //
4395         // Examples:
4396         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
4397         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
4398         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
4399         //
4400         // Note:  coalesce_subword_stores may have already done this,
4401         // if it was prompted by constant non-zero subword initializers.
4402         // But this case can still arise with non-constant stores.
4403 
4404         intptr_t next_full_store = find_next_fullword_store(i, phase);
4405 
4406         // In the examples above:
4407         //   in(i)          p   q   r   s     x   y     z
4408         //   st_off        12  13  14  15    12  13    14
4409         //   st_size        1   1   1   1     1   1     1
4410         //   next_full_s.  12  16  16  16    16  16    16
4411         //   z's_done      12  16  16  16    12  16    12
4412         //   z's_needed    12  16  16  16    16  16    16
4413         //   zsize          0   0   0   0     4   0     4
4414         if (next_full_store < 0) {
4415           // Conservative tack:  Zero to end of current word.
4416           zeroes_needed = align_up(zeroes_needed, BytesPerInt);
4417         } else {
4418           // Zero to beginning of next fully initialized word.
4419           // Or, don't zero at all, if we are already in that word.
4420           assert(next_full_store >= zeroes_needed, "must go forward");
4421           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
4422           zeroes_needed = next_full_store;
4423         }
4424       }
4425 
4426       if (zeroes_needed > zeroes_done) {
4427         intptr_t zsize = zeroes_needed - zeroes_done;
4428         // Do some incremental zeroing on rawmem, in parallel with inits.
4429         zeroes_done = align_down(zeroes_done, BytesPerInt);
4430         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
4431                                               zeroes_done, zeroes_needed,
4432                                               phase);
4433         zeroes_done = zeroes_needed;
4434         if (zsize > InitArrayShortSize && ++big_init_gaps > 2)
4435           do_zeroing = false;   // leave the hole, next time
4436       }
4437     }
4438 
4439     // Collect the store and move on:
4440     phase->replace_input_of(st, MemNode::Memory, inits);
4441     inits = st;                 // put it on the linearized chain
4442     set_req(i, zmem);           // unhook from previous position
4443 
4444     if (zeroes_done == st_off)
4445       zeroes_done = next_init_off;
4446 
4447     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
4448 
4449     #ifdef ASSERT
4450     // Various order invariants.  Weaker than stores_are_sane because
4451     // a large constant tile can be filled in by smaller non-constant stores.
4452     assert(st_off >= last_init_off, "inits do not reverse");
4453     last_init_off = st_off;
4454     const Type* val = nullptr;
4455     if (st_size >= BytesPerInt &&
4456         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
4457         (int)val->basic_type() < (int)T_OBJECT) {
4458       assert(st_off >= last_tile_end, "tiles do not overlap");
4459       assert(st_off >= last_init_end, "tiles do not overwrite inits");
4460       last_tile_end = MAX2(last_tile_end, next_init_off);
4461     } else {
4462       intptr_t st_tile_end = align_up(next_init_off, BytesPerLong);
4463       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
4464       assert(st_off      >= last_init_end, "inits do not overlap");
4465       last_init_end = next_init_off;  // it's a non-tile
4466     }
4467     #endif //ASSERT
4468   }
4469 
4470   remove_extra_zeroes();        // clear out all the zmems left over
4471   add_req(inits);
4472 
4473   if (!(UseTLAB && ZeroTLAB)) {
4474     // If anything remains to be zeroed, zero it all now.
4475     zeroes_done = align_down(zeroes_done, BytesPerInt);
4476     // if it is the last unused 4 bytes of an instance, forget about it
4477     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
4478     if (zeroes_done + BytesPerLong >= size_limit) {
4479       AllocateNode* alloc = allocation();
4480       assert(alloc != nullptr, "must be present");
4481       if (alloc != nullptr && alloc->Opcode() == Op_Allocate) {
4482         Node* klass_node = alloc->in(AllocateNode::KlassNode);
4483         ciKlass* k = phase->type(klass_node)->is_instklassptr()->instance_klass();
4484         if (zeroes_done == k->layout_helper())
4485           zeroes_done = size_limit;
4486       }
4487     }
4488     if (zeroes_done < size_limit) {
4489       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
4490                                             zeroes_done, size_in_bytes, phase);
4491     }
4492   }
4493 
4494   set_complete(phase);
4495   return rawmem;
4496 }
4497 
4498 
4499 #ifdef ASSERT
4500 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
4501   if (is_complete())
4502     return true;                // stores could be anything at this point
4503   assert(allocation() != nullptr, "must be present");
4504   intptr_t last_off = allocation()->minimum_header_size();
4505   for (uint i = InitializeNode::RawStores; i < req(); i++) {
4506     Node* st = in(i);
4507     intptr_t st_off = get_store_offset(st, phase);
4508     if (st_off < 0)  continue;  // ignore dead garbage
4509     if (last_off > st_off) {
4510       tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
4511       this->dump(2);
4512       assert(false, "ascending store offsets");
4513       return false;
4514     }
4515     last_off = st_off + st->as_Store()->memory_size();
4516   }
4517   return true;
4518 }
4519 #endif //ASSERT
4520 
4521 
4522 
4523 
4524 //============================MergeMemNode=====================================
4525 //
4526 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
4527 // contributing store or call operations.  Each contributor provides the memory
4528 // state for a particular "alias type" (see Compile::alias_type).  For example,
4529 // if a MergeMem has an input X for alias category #6, then any memory reference
4530 // to alias category #6 may use X as its memory state input, as an exact equivalent
4531 // to using the MergeMem as a whole.
4532 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
4533 //
4534 // (Here, the <N> notation gives the index of the relevant adr_type.)
4535 //
4536 // In one special case (and more cases in the future), alias categories overlap.
4537 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
4538 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
4539 // it is exactly equivalent to that state W:
4540 //   MergeMem(<Bot>: W) <==> W
4541 //
4542 // Usually, the merge has more than one input.  In that case, where inputs
4543 // overlap (i.e., one is Bot), the narrower alias type determines the memory
4544 // state for that type, and the wider alias type (Bot) fills in everywhere else:
4545 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
4546 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
4547 //
4548 // A merge can take a "wide" memory state as one of its narrow inputs.
4549 // This simply means that the merge observes out only the relevant parts of
4550 // the wide input.  That is, wide memory states arriving at narrow merge inputs
4551 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
4552 //
4553 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
4554 // and that memory slices "leak through":
4555 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
4556 //
4557 // But, in such a cascade, repeated memory slices can "block the leak":
4558 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
4559 //
4560 // In the last example, Y is not part of the combined memory state of the
4561 // outermost MergeMem.  The system must, of course, prevent unschedulable
4562 // memory states from arising, so you can be sure that the state Y is somehow
4563 // a precursor to state Y'.
4564 //
4565 //
4566 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
4567 // of each MergeMemNode array are exactly the numerical alias indexes, including
4568 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
4569 // Compile::alias_type (and kin) produce and manage these indexes.
4570 //
4571 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
4572 // (Note that this provides quick access to the top node inside MergeMem methods,
4573 // without the need to reach out via TLS to Compile::current.)
4574 //
4575 // As a consequence of what was just described, a MergeMem that represents a full
4576 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
4577 // containing all alias categories.
4578 //
4579 // MergeMem nodes never (?) have control inputs, so in(0) is null.
4580 //
4581 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
4582 // a memory state for the alias type <N>, or else the top node, meaning that
4583 // there is no particular input for that alias type.  Note that the length of
4584 // a MergeMem is variable, and may be extended at any time to accommodate new
4585 // memory states at larger alias indexes.  When merges grow, they are of course
4586 // filled with "top" in the unused in() positions.
4587 //
4588 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
4589 // (Top was chosen because it works smoothly with passes like GCM.)
4590 //
4591 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
4592 // the type of random VM bits like TLS references.)  Since it is always the
4593 // first non-Bot memory slice, some low-level loops use it to initialize an
4594 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
4595 //
4596 //
4597 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
4598 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
4599 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
4600 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
4601 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
4602 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
4603 //
4604 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
4605 // really that different from the other memory inputs.  An abbreviation called
4606 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
4607 //
4608 //
4609 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
4610 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
4611 // that "emerges though" the base memory will be marked as excluding the alias types
4612 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
4613 //
4614 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
4615 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
4616 //
4617 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
4618 // (It is currently unimplemented.)  As you can see, the resulting merge is
4619 // actually a disjoint union of memory states, rather than an overlay.
4620 //
4621 
4622 //------------------------------MergeMemNode-----------------------------------
4623 Node* MergeMemNode::make_empty_memory() {
4624   Node* empty_memory = (Node*) Compile::current()->top();
4625   assert(empty_memory->is_top(), "correct sentinel identity");
4626   return empty_memory;
4627 }
4628 
4629 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
4630   init_class_id(Class_MergeMem);
4631   // all inputs are nullified in Node::Node(int)
4632   // set_input(0, nullptr);  // no control input
4633 
4634   // Initialize the edges uniformly to top, for starters.
4635   Node* empty_mem = make_empty_memory();
4636   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
4637     init_req(i,empty_mem);
4638   }
4639   assert(empty_memory() == empty_mem, "");
4640 
4641   if( new_base != nullptr && new_base->is_MergeMem() ) {
4642     MergeMemNode* mdef = new_base->as_MergeMem();
4643     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
4644     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
4645       mms.set_memory(mms.memory2());
4646     }
4647     assert(base_memory() == mdef->base_memory(), "");
4648   } else {
4649     set_base_memory(new_base);
4650   }
4651 }
4652 
4653 // Make a new, untransformed MergeMem with the same base as 'mem'.
4654 // If mem is itself a MergeMem, populate the result with the same edges.
4655 MergeMemNode* MergeMemNode::make(Node* mem) {
4656   return new MergeMemNode(mem);
4657 }
4658 
4659 //------------------------------cmp--------------------------------------------
4660 uint MergeMemNode::hash() const { return NO_HASH; }
4661 bool MergeMemNode::cmp( const Node &n ) const {
4662   return (&n == this);          // Always fail except on self
4663 }
4664 
4665 //------------------------------Identity---------------------------------------
4666 Node* MergeMemNode::Identity(PhaseGVN* phase) {
4667   // Identity if this merge point does not record any interesting memory
4668   // disambiguations.
4669   Node* base_mem = base_memory();
4670   Node* empty_mem = empty_memory();
4671   if (base_mem != empty_mem) {  // Memory path is not dead?
4672     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4673       Node* mem = in(i);
4674       if (mem != empty_mem && mem != base_mem) {
4675         return this;            // Many memory splits; no change
4676       }
4677     }
4678   }
4679   return base_mem;              // No memory splits; ID on the one true input
4680 }
4681 
4682 //------------------------------Ideal------------------------------------------
4683 // This method is invoked recursively on chains of MergeMem nodes
4684 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4685   // Remove chain'd MergeMems
4686   //
4687   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
4688   // relative to the "in(Bot)".  Since we are patching both at the same time,
4689   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
4690   // but rewrite each "in(i)" relative to the new "in(Bot)".
4691   Node *progress = nullptr;
4692 
4693 
4694   Node* old_base = base_memory();
4695   Node* empty_mem = empty_memory();
4696   if (old_base == empty_mem)
4697     return nullptr; // Dead memory path.
4698 
4699   MergeMemNode* old_mbase;
4700   if (old_base != nullptr && old_base->is_MergeMem())
4701     old_mbase = old_base->as_MergeMem();
4702   else
4703     old_mbase = nullptr;
4704   Node* new_base = old_base;
4705 
4706   // simplify stacked MergeMems in base memory
4707   if (old_mbase)  new_base = old_mbase->base_memory();
4708 
4709   // the base memory might contribute new slices beyond my req()
4710   if (old_mbase)  grow_to_match(old_mbase);
4711 
4712   // Note:  We do not call verify_sparse on entry, because inputs
4713   // can normalize to the base_memory via subsume_node or similar
4714   // mechanisms.  This method repairs that damage.
4715 
4716   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
4717 
4718   // Look at each slice.
4719   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4720     Node* old_in = in(i);
4721     // calculate the old memory value
4722     Node* old_mem = old_in;
4723     if (old_mem == empty_mem)  old_mem = old_base;
4724     assert(old_mem == memory_at(i), "");
4725 
4726     // maybe update (reslice) the old memory value
4727 
4728     // simplify stacked MergeMems
4729     Node* new_mem = old_mem;
4730     MergeMemNode* old_mmem;
4731     if (old_mem != nullptr && old_mem->is_MergeMem())
4732       old_mmem = old_mem->as_MergeMem();
4733     else
4734       old_mmem = nullptr;
4735     if (old_mmem == this) {
4736       // This can happen if loops break up and safepoints disappear.
4737       // A merge of BotPtr (default) with a RawPtr memory derived from a
4738       // safepoint can be rewritten to a merge of the same BotPtr with
4739       // the BotPtr phi coming into the loop.  If that phi disappears
4740       // also, we can end up with a self-loop of the mergemem.
4741       // In general, if loops degenerate and memory effects disappear,
4742       // a mergemem can be left looking at itself.  This simply means
4743       // that the mergemem's default should be used, since there is
4744       // no longer any apparent effect on this slice.
4745       // Note: If a memory slice is a MergeMem cycle, it is unreachable
4746       //       from start.  Update the input to TOP.
4747       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
4748     }
4749     else if (old_mmem != nullptr) {
4750       new_mem = old_mmem->memory_at(i);
4751     }
4752     // else preceding memory was not a MergeMem
4753 
4754     // maybe store down a new value
4755     Node* new_in = new_mem;
4756     if (new_in == new_base)  new_in = empty_mem;
4757 
4758     if (new_in != old_in) {
4759       // Warning:  Do not combine this "if" with the previous "if"
4760       // A memory slice might have be be rewritten even if it is semantically
4761       // unchanged, if the base_memory value has changed.
4762       set_req_X(i, new_in, phase);
4763       progress = this;          // Report progress
4764     }
4765   }
4766 
4767   if (new_base != old_base) {
4768     set_req_X(Compile::AliasIdxBot, new_base, phase);
4769     // Don't use set_base_memory(new_base), because we need to update du.
4770     assert(base_memory() == new_base, "");
4771     progress = this;
4772   }
4773 
4774   if( base_memory() == this ) {
4775     // a self cycle indicates this memory path is dead
4776     set_req(Compile::AliasIdxBot, empty_mem);
4777   }
4778 
4779   // Resolve external cycles by calling Ideal on a MergeMem base_memory
4780   // Recursion must occur after the self cycle check above
4781   if( base_memory()->is_MergeMem() ) {
4782     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
4783     Node *m = phase->transform(new_mbase);  // Rollup any cycles
4784     if( m != nullptr &&
4785         (m->is_top() ||
4786          (m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem)) ) {
4787       // propagate rollup of dead cycle to self
4788       set_req(Compile::AliasIdxBot, empty_mem);
4789     }
4790   }
4791 
4792   if( base_memory() == empty_mem ) {
4793     progress = this;
4794     // Cut inputs during Parse phase only.
4795     // During Optimize phase a dead MergeMem node will be subsumed by Top.
4796     if( !can_reshape ) {
4797       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4798         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
4799       }
4800     }
4801   }
4802 
4803   if( !progress && base_memory()->is_Phi() && can_reshape ) {
4804     // Check if PhiNode::Ideal's "Split phis through memory merges"
4805     // transform should be attempted. Look for this->phi->this cycle.
4806     uint merge_width = req();
4807     if (merge_width > Compile::AliasIdxRaw) {
4808       PhiNode* phi = base_memory()->as_Phi();
4809       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
4810         if (phi->in(i) == this) {
4811           phase->is_IterGVN()->_worklist.push(phi);
4812           break;
4813         }
4814       }
4815     }
4816   }
4817 
4818   assert(progress || verify_sparse(), "please, no dups of base");
4819   return progress;
4820 }
4821 
4822 //-------------------------set_base_memory-------------------------------------
4823 void MergeMemNode::set_base_memory(Node *new_base) {
4824   Node* empty_mem = empty_memory();
4825   set_req(Compile::AliasIdxBot, new_base);
4826   assert(memory_at(req()) == new_base, "must set default memory");
4827   // Clear out other occurrences of new_base:
4828   if (new_base != empty_mem) {
4829     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4830       if (in(i) == new_base)  set_req(i, empty_mem);
4831     }
4832   }
4833 }
4834 
4835 //------------------------------out_RegMask------------------------------------
4836 const RegMask &MergeMemNode::out_RegMask() const {
4837   return RegMask::Empty;
4838 }
4839 
4840 //------------------------------dump_spec--------------------------------------
4841 #ifndef PRODUCT
4842 void MergeMemNode::dump_spec(outputStream *st) const {
4843   st->print(" {");
4844   Node* base_mem = base_memory();
4845   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
4846     Node* mem = (in(i) != nullptr) ? memory_at(i) : base_mem;
4847     if (mem == base_mem) { st->print(" -"); continue; }
4848     st->print( " N%d:", mem->_idx );
4849     Compile::current()->get_adr_type(i)->dump_on(st);
4850   }
4851   st->print(" }");
4852 }
4853 #endif // !PRODUCT
4854 
4855 
4856 #ifdef ASSERT
4857 static bool might_be_same(Node* a, Node* b) {
4858   if (a == b)  return true;
4859   if (!(a->is_Phi() || b->is_Phi()))  return false;
4860   // phis shift around during optimization
4861   return true;  // pretty stupid...
4862 }
4863 
4864 // verify a narrow slice (either incoming or outgoing)
4865 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
4866   if (!VerifyAliases)                return;  // don't bother to verify unless requested
4867   if (VMError::is_error_reported())  return;  // muzzle asserts when debugging an error
4868   if (Node::in_dump())               return;  // muzzle asserts when printing
4869   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
4870   assert(n != nullptr, "");
4871   // Elide intervening MergeMem's
4872   while (n->is_MergeMem()) {
4873     n = n->as_MergeMem()->memory_at(alias_idx);
4874   }
4875   Compile* C = Compile::current();
4876   const TypePtr* n_adr_type = n->adr_type();
4877   if (n == m->empty_memory()) {
4878     // Implicit copy of base_memory()
4879   } else if (n_adr_type != TypePtr::BOTTOM) {
4880     assert(n_adr_type != nullptr, "new memory must have a well-defined adr_type");
4881     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
4882   } else {
4883     // A few places like make_runtime_call "know" that VM calls are narrow,
4884     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
4885     bool expected_wide_mem = false;
4886     if (n == m->base_memory()) {
4887       expected_wide_mem = true;
4888     } else if (alias_idx == Compile::AliasIdxRaw ||
4889                n == m->memory_at(Compile::AliasIdxRaw)) {
4890       expected_wide_mem = true;
4891     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
4892       // memory can "leak through" calls on channels that
4893       // are write-once.  Allow this also.
4894       expected_wide_mem = true;
4895     }
4896     assert(expected_wide_mem, "expected narrow slice replacement");
4897   }
4898 }
4899 #else // !ASSERT
4900 #define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
4901 #endif
4902 
4903 
4904 //-----------------------------memory_at---------------------------------------
4905 Node* MergeMemNode::memory_at(uint alias_idx) const {
4906   assert(alias_idx >= Compile::AliasIdxRaw ||
4907          alias_idx == Compile::AliasIdxBot && !Compile::current()->do_aliasing(),
4908          "must avoid base_memory and AliasIdxTop");
4909 
4910   // Otherwise, it is a narrow slice.
4911   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
4912   if (is_empty_memory(n)) {
4913     // the array is sparse; empty slots are the "top" node
4914     n = base_memory();
4915     assert(Node::in_dump()
4916            || n == nullptr || n->bottom_type() == Type::TOP
4917            || n->adr_type() == nullptr // address is TOP
4918            || n->adr_type() == TypePtr::BOTTOM
4919            || n->adr_type() == TypeRawPtr::BOTTOM
4920            || !Compile::current()->do_aliasing(),
4921            "must be a wide memory");
4922     // do_aliasing == false if we are organizing the memory states manually.
4923     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
4924   } else {
4925     // make sure the stored slice is sane
4926     #ifdef ASSERT
4927     if (VMError::is_error_reported() || Node::in_dump()) {
4928     } else if (might_be_same(n, base_memory())) {
4929       // Give it a pass:  It is a mostly harmless repetition of the base.
4930       // This can arise normally from node subsumption during optimization.
4931     } else {
4932       verify_memory_slice(this, alias_idx, n);
4933     }
4934     #endif
4935   }
4936   return n;
4937 }
4938 
4939 //---------------------------set_memory_at-------------------------------------
4940 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
4941   verify_memory_slice(this, alias_idx, n);
4942   Node* empty_mem = empty_memory();
4943   if (n == base_memory())  n = empty_mem;  // collapse default
4944   uint need_req = alias_idx+1;
4945   if (req() < need_req) {
4946     if (n == empty_mem)  return;  // already the default, so do not grow me
4947     // grow the sparse array
4948     do {
4949       add_req(empty_mem);
4950     } while (req() < need_req);
4951   }
4952   set_req( alias_idx, n );
4953 }
4954 
4955 
4956 
4957 //--------------------------iteration_setup------------------------------------
4958 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
4959   if (other != nullptr) {
4960     grow_to_match(other);
4961     // invariant:  the finite support of mm2 is within mm->req()
4962     #ifdef ASSERT
4963     for (uint i = req(); i < other->req(); i++) {
4964       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
4965     }
4966     #endif
4967   }
4968   // Replace spurious copies of base_memory by top.
4969   Node* base_mem = base_memory();
4970   if (base_mem != nullptr && !base_mem->is_top()) {
4971     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
4972       if (in(i) == base_mem)
4973         set_req(i, empty_memory());
4974     }
4975   }
4976 }
4977 
4978 //---------------------------grow_to_match-------------------------------------
4979 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
4980   Node* empty_mem = empty_memory();
4981   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
4982   // look for the finite support of the other memory
4983   for (uint i = other->req(); --i >= req(); ) {
4984     if (other->in(i) != empty_mem) {
4985       uint new_len = i+1;
4986       while (req() < new_len)  add_req(empty_mem);
4987       break;
4988     }
4989   }
4990 }
4991 
4992 //---------------------------verify_sparse-------------------------------------
4993 #ifndef PRODUCT
4994 bool MergeMemNode::verify_sparse() const {
4995   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
4996   Node* base_mem = base_memory();
4997   // The following can happen in degenerate cases, since empty==top.
4998   if (is_empty_memory(base_mem))  return true;
4999   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
5000     assert(in(i) != nullptr, "sane slice");
5001     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
5002   }
5003   return true;
5004 }
5005 
5006 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
5007   Node* n;
5008   n = mm->in(idx);
5009   if (mem == n)  return true;  // might be empty_memory()
5010   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
5011   if (mem == n)  return true;
5012   return false;
5013 }
5014 #endif // !PRODUCT