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