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