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