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