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