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