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