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