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