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