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