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