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