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