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