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