1 /*
   2  * Copyright 1997-2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 // Portions of code courtesy of Clifford Click
  26 
  27 // Optimization - Graph Style
  28 
  29 #include "incls/_precompiled.incl"
  30 #include "incls/_memnode.cpp.incl"
  31 
  32 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
  33 
  34 //=============================================================================
  35 uint MemNode::size_of() const { return sizeof(*this); }
  36 
  37 const TypePtr *MemNode::adr_type() const {
  38   Node* adr = in(Address);
  39   const TypePtr* cross_check = NULL;
  40   DEBUG_ONLY(cross_check = _adr_type);
  41   return calculate_adr_type(adr->bottom_type(), cross_check);
  42 }
  43 
  44 #ifndef PRODUCT
  45 void MemNode::dump_spec(outputStream *st) const {
  46   if (in(Address) == NULL)  return; // node is dead
  47 #ifndef ASSERT
  48   // fake the missing field
  49   const TypePtr* _adr_type = NULL;
  50   if (in(Address) != NULL)
  51     _adr_type = in(Address)->bottom_type()->isa_ptr();
  52 #endif
  53   dump_adr_type(this, _adr_type, st);
  54 
  55   Compile* C = Compile::current();
  56   if( C->alias_type(_adr_type)->is_volatile() )
  57     st->print(" Volatile!");
  58 }
  59 
  60 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
  61   st->print(" @");
  62   if (adr_type == NULL) {
  63     st->print("NULL");
  64   } else {
  65     adr_type->dump_on(st);
  66     Compile* C = Compile::current();
  67     Compile::AliasType* atp = NULL;
  68     if (C->have_alias_type(adr_type))  atp = C->alias_type(adr_type);
  69     if (atp == NULL)
  70       st->print(", idx=?\?;");
  71     else if (atp->index() == Compile::AliasIdxBot)
  72       st->print(", idx=Bot;");
  73     else if (atp->index() == Compile::AliasIdxTop)
  74       st->print(", idx=Top;");
  75     else if (atp->index() == Compile::AliasIdxRaw)
  76       st->print(", idx=Raw;");
  77     else {
  78       ciField* field = atp->field();
  79       if (field) {
  80         st->print(", name=");
  81         field->print_name_on(st);
  82       }
  83       st->print(", idx=%d;", atp->index());
  84     }
  85   }
  86 }
  87 
  88 extern void print_alias_types();
  89 
  90 #endif
  91 
  92 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypePtr *t_adr, PhaseGVN *phase) {
  93   const TypeOopPtr *tinst = t_adr->isa_oopptr();
  94   if (tinst == NULL || !tinst->is_instance_field())
  95     return mchain;  // don't try to optimize non-instance types
  96   uint instance_id = tinst->instance_id();
  97   Node *prev = NULL;
  98   Node *result = mchain;
  99   while (prev != result) {
 100     prev = result;
 101     // skip over a call which does not affect this memory slice
 102     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
 103       Node *proj_in = result->in(0);
 104       if (proj_in->is_Call()) {
 105         CallNode *call = proj_in->as_Call();
 106         if (!call->may_modify(t_adr, phase)) {
 107           result = call->in(TypeFunc::Memory);
 108         }
 109       } else if (proj_in->is_Initialize()) {
 110         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
 111         // Stop if this is the initialization for the object instance which
 112         // which contains this memory slice, otherwise skip over it.
 113         if (alloc != NULL && alloc->_idx != instance_id) {
 114           result = proj_in->in(TypeFunc::Memory);
 115         }
 116       } else if (proj_in->is_MemBar()) {
 117         result = proj_in->in(TypeFunc::Memory);
 118       }
 119     } else if (result->is_MergeMem()) {
 120       result = step_through_mergemem(phase, result->as_MergeMem(), t_adr, NULL, tty);
 121     }
 122   }
 123   return result;
 124 }
 125 
 126 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, PhaseGVN *phase) {
 127   const TypeOopPtr *t_oop = t_adr->isa_oopptr();
 128   bool is_instance = (t_oop != NULL) && t_oop->is_instance_field();
 129   PhaseIterGVN *igvn = phase->is_IterGVN();
 130   Node *result = mchain;
 131   result = optimize_simple_memory_chain(result, t_adr, phase);
 132   if (is_instance && igvn != NULL  && result->is_Phi()) {
 133     PhiNode *mphi = result->as_Phi();
 134     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
 135     const TypePtr *t = mphi->adr_type();
 136     if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM) {
 137       // clone the Phi with our address type
 138       result = mphi->split_out_instance(t_adr, igvn);
 139     } else {
 140       assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
 141     }
 142   }
 143   return result;
 144 }
 145 
 146 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
 147   uint alias_idx = phase->C->get_alias_index(tp);
 148   Node *mem = mmem;
 149 #ifdef ASSERT
 150   {
 151     // Check that current type is consistent with the alias index used during graph construction
 152     assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
 153     bool consistent =  adr_check == NULL || adr_check->empty() ||
 154                        phase->C->must_alias(adr_check, alias_idx );
 155     // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
 156     if( !consistent && adr_check != NULL && !adr_check->empty() &&
 157            tp->isa_aryptr() &&    tp->offset() == Type::OffsetBot &&
 158         adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
 159         ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
 160           adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
 161           adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
 162       // don't assert if it is dead code.
 163       consistent = true;
 164     }
 165     if( !consistent ) {
 166       st->print("alias_idx==%d, adr_check==", alias_idx);
 167       if( adr_check == NULL ) {
 168         st->print("NULL");
 169       } else {
 170         adr_check->dump();
 171       }
 172       st->cr();
 173       print_alias_types();
 174       assert(consistent, "adr_check must match alias idx");
 175     }
 176   }
 177 #endif
 178   // TypeInstPtr::NOTNULL+any is an OOP with unknown offset - generally
 179   // means an array I have not precisely typed yet.  Do not do any
 180   // alias stuff with it any time soon.
 181   const TypeOopPtr *tinst = tp->isa_oopptr();
 182   if( tp->base() != Type::AnyPtr &&
 183       !(tinst &&
 184         tinst->klass()->is_java_lang_Object() &&
 185         tinst->offset() == Type::OffsetBot) ) {
 186     // compress paths and change unreachable cycles to TOP
 187     // If not, we can update the input infinitely along a MergeMem cycle
 188     // Equivalent code in PhiNode::Ideal
 189     Node* m  = phase->transform(mmem);
 190     // If tranformed to a MergeMem, get the desired slice
 191     // Otherwise the returned node represents memory for every slice
 192     mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
 193     // Update input if it is progress over what we have now
 194   }
 195   return mem;
 196 }
 197 
 198 //--------------------------Ideal_common---------------------------------------
 199 // Look for degenerate control and memory inputs.  Bypass MergeMem inputs.
 200 // Unhook non-raw memories from complete (macro-expanded) initializations.
 201 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
 202   // If our control input is a dead region, kill all below the region
 203   Node *ctl = in(MemNode::Control);
 204   if (ctl && remove_dead_region(phase, can_reshape))
 205     return this;
 206 
 207   // Ignore if memory is dead, or self-loop
 208   Node *mem = in(MemNode::Memory);
 209   if( phase->type( mem ) == Type::TOP ) return NodeSentinel; // caller will return NULL
 210   assert( mem != this, "dead loop in MemNode::Ideal" );
 211 
 212   Node *address = in(MemNode::Address);
 213   const Type *t_adr = phase->type( address );
 214   if( t_adr == Type::TOP )              return NodeSentinel; // caller will return NULL
 215 
 216   // Avoid independent memory operations
 217   Node* old_mem = mem;
 218 
 219   // The code which unhooks non-raw memories from complete (macro-expanded)
 220   // initializations was removed. After macro-expansion all stores catched
 221   // by Initialize node became raw stores and there is no information
 222   // which memory slices they modify. So it is unsafe to move any memory
 223   // operation above these stores. Also in most cases hooked non-raw memories
 224   // were already unhooked by using information from detect_ptr_independence()
 225   // and find_previous_store().
 226 
 227   if (mem->is_MergeMem()) {
 228     MergeMemNode* mmem = mem->as_MergeMem();
 229     const TypePtr *tp = t_adr->is_ptr();
 230 
 231     mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
 232   }
 233 
 234   if (mem != old_mem) {
 235     set_req(MemNode::Memory, mem);
 236     return this;
 237   }
 238 
 239   // let the subclass continue analyzing...
 240   return NULL;
 241 }
 242 
 243 // Helper function for proving some simple control dominations.
 244 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
 245 // Already assumes that 'dom' is available at 'sub', and that 'sub'
 246 // is not a constant (dominated by the method's StartNode).
 247 // Used by MemNode::find_previous_store to prove that the
 248 // control input of a memory operation predates (dominates)
 249 // an allocation it wants to look past.
 250 bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
 251   if (dom == NULL || dom->is_top() || sub == NULL || sub->is_top())
 252     return false; // Conservative answer for dead code
 253 
 254   // Check 'dom'.
 255   dom = dom->find_exact_control(dom);
 256   if (dom == NULL || dom->is_top())
 257     return false; // Conservative answer for dead code
 258 
 259   if (dom->is_Start() || dom->is_Root() || dom == sub)
 260     return true;
 261 
 262   // 'dom' dominates 'sub' if its control edge and control edges
 263   // of all its inputs dominate or equal to sub's control edge.
 264 
 265   // Currently 'sub' is either Allocate, Initialize or Start nodes.
 266   assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start(), "expecting only these nodes");
 267 
 268   // Get control edge of 'sub'.
 269   sub = sub->find_exact_control(sub->in(0));
 270   if (sub == NULL || sub->is_top())
 271     return false; // Conservative answer for dead code
 272 
 273   assert(sub->is_CFG(), "expecting control");
 274 
 275   if (sub == dom)
 276     return true;
 277 
 278   if (sub->is_Start() || sub->is_Root())
 279     return false;
 280 
 281   {
 282     // Check all control edges of 'dom'.
 283 
 284     ResourceMark rm;
 285     Arena* arena = Thread::current()->resource_area();
 286     Node_List nlist(arena);
 287     Unique_Node_List dom_list(arena);
 288 
 289     dom_list.push(dom);
 290     bool only_dominating_controls = false;
 291 
 292     for (uint next = 0; next < dom_list.size(); next++) {
 293       Node* n = dom_list.at(next);
 294       if (!n->is_CFG() && n->pinned()) {
 295         // Check only own control edge for pinned non-control nodes.
 296         n = n->find_exact_control(n->in(0));
 297         if (n == NULL || n->is_top())
 298           return false; // Conservative answer for dead code
 299         assert(n->is_CFG(), "expecting control");
 300       }
 301       if (n->is_Start() || n->is_Root()) {
 302         only_dominating_controls = true;
 303       } else if (n->is_CFG()) {
 304         if (n->dominates(sub, nlist))
 305           only_dominating_controls = true;
 306         else
 307           return false;
 308       } else {
 309         // First, own control edge.
 310         Node* m = n->find_exact_control(n->in(0));
 311         if (m == NULL)
 312           continue;
 313         if (m->is_top())
 314           return false; // Conservative answer for dead code
 315         dom_list.push(m);
 316 
 317         // Now, the rest of edges.
 318         uint cnt = n->req();
 319         for (uint i = 1; i < cnt; i++) {
 320           m = n->find_exact_control(n->in(i));
 321           if (m == NULL || m->is_top())
 322             continue;
 323           dom_list.push(m);
 324         }
 325       }
 326     }
 327     return only_dominating_controls;
 328   }
 329 }
 330 
 331 //---------------------detect_ptr_independence---------------------------------
 332 // Used by MemNode::find_previous_store to prove that two base
 333 // pointers are never equal.
 334 // The pointers are accompanied by their associated allocations,
 335 // if any, which have been previously discovered by the caller.
 336 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
 337                                       Node* p2, AllocateNode* a2,
 338                                       PhaseTransform* phase) {
 339   // Attempt to prove that these two pointers cannot be aliased.
 340   // They may both manifestly be allocations, and they should differ.
 341   // Or, if they are not both allocations, they can be distinct constants.
 342   // Otherwise, one is an allocation and the other a pre-existing value.
 343   if (a1 == NULL && a2 == NULL) {           // neither an allocation
 344     return (p1 != p2) && p1->is_Con() && p2->is_Con();
 345   } else if (a1 != NULL && a2 != NULL) {    // both allocations
 346     return (a1 != a2);
 347   } else if (a1 != NULL) {                  // one allocation a1
 348     // (Note:  p2->is_Con implies p2->in(0)->is_Root, which dominates.)
 349     return all_controls_dominate(p2, a1);
 350   } else { //(a2 != NULL)                   // one allocation a2
 351     return all_controls_dominate(p1, a2);
 352   }
 353   return false;
 354 }
 355 
 356 
 357 // The logic for reordering loads and stores uses four steps:
 358 // (a) Walk carefully past stores and initializations which we
 359 //     can prove are independent of this load.
 360 // (b) Observe that the next memory state makes an exact match
 361 //     with self (load or store), and locate the relevant store.
 362 // (c) Ensure that, if we were to wire self directly to the store,
 363 //     the optimizer would fold it up somehow.
 364 // (d) Do the rewiring, and return, depending on some other part of
 365 //     the optimizer to fold up the load.
 366 // This routine handles steps (a) and (b).  Steps (c) and (d) are
 367 // specific to loads and stores, so they are handled by the callers.
 368 // (Currently, only LoadNode::Ideal has steps (c), (d).  More later.)
 369 //
 370 Node* MemNode::find_previous_store(PhaseTransform* phase) {
 371   Node*         ctrl   = in(MemNode::Control);
 372   Node*         adr    = in(MemNode::Address);
 373   intptr_t      offset = 0;
 374   Node*         base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
 375   AllocateNode* alloc  = AllocateNode::Ideal_allocation(base, phase);
 376 
 377   if (offset == Type::OffsetBot)
 378     return NULL;            // cannot unalias unless there are precise offsets
 379 
 380   const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
 381 
 382   intptr_t size_in_bytes = memory_size();
 383 
 384   Node* mem = in(MemNode::Memory);   // start searching here...
 385 
 386   int cnt = 50;             // Cycle limiter
 387   for (;;) {                // While we can dance past unrelated stores...
 388     if (--cnt < 0)  break;  // Caught in cycle or a complicated dance?
 389 
 390     if (mem->is_Store()) {
 391       Node* st_adr = mem->in(MemNode::Address);
 392       intptr_t st_offset = 0;
 393       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
 394       if (st_base == NULL)
 395         break;              // inscrutable pointer
 396       if (st_offset != offset && st_offset != Type::OffsetBot) {
 397         const int MAX_STORE = BytesPerLong;
 398         if (st_offset >= offset + size_in_bytes ||
 399             st_offset <= offset - MAX_STORE ||
 400             st_offset <= offset - mem->as_Store()->memory_size()) {
 401           // Success:  The offsets are provably independent.
 402           // (You may ask, why not just test st_offset != offset and be done?
 403           // The answer is that stores of different sizes can co-exist
 404           // in the same sequence of RawMem effects.  We sometimes initialize
 405           // a whole 'tile' of array elements with a single jint or jlong.)
 406           mem = mem->in(MemNode::Memory);
 407           continue;           // (a) advance through independent store memory
 408         }
 409       }
 410       if (st_base != base &&
 411           detect_ptr_independence(base, alloc,
 412                                   st_base,
 413                                   AllocateNode::Ideal_allocation(st_base, phase),
 414                                   phase)) {
 415         // Success:  The bases are provably independent.
 416         mem = mem->in(MemNode::Memory);
 417         continue;           // (a) advance through independent store memory
 418       }
 419 
 420       // (b) At this point, if the bases or offsets do not agree, we lose,
 421       // since we have not managed to prove 'this' and 'mem' independent.
 422       if (st_base == base && st_offset == offset) {
 423         return mem;         // let caller handle steps (c), (d)
 424       }
 425 
 426     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
 427       InitializeNode* st_init = mem->in(0)->as_Initialize();
 428       AllocateNode*  st_alloc = st_init->allocation();
 429       if (st_alloc == NULL)
 430         break;              // something degenerated
 431       bool known_identical = false;
 432       bool known_independent = false;
 433       if (alloc == st_alloc)
 434         known_identical = true;
 435       else if (alloc != NULL)
 436         known_independent = true;
 437       else if (all_controls_dominate(this, st_alloc))
 438         known_independent = true;
 439 
 440       if (known_independent) {
 441         // The bases are provably independent: Either they are
 442         // manifestly distinct allocations, or else the control
 443         // of this load dominates the store's allocation.
 444         int alias_idx = phase->C->get_alias_index(adr_type());
 445         if (alias_idx == Compile::AliasIdxRaw) {
 446           mem = st_alloc->in(TypeFunc::Memory);
 447         } else {
 448           mem = st_init->memory(alias_idx);
 449         }
 450         continue;           // (a) advance through independent store memory
 451       }
 452 
 453       // (b) at this point, if we are not looking at a store initializing
 454       // the same allocation we are loading from, we lose.
 455       if (known_identical) {
 456         // From caller, can_see_stored_value will consult find_captured_store.
 457         return mem;         // let caller handle steps (c), (d)
 458       }
 459 
 460     } else if (addr_t != NULL && addr_t->is_instance_field()) {
 461       // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
 462       if (mem->is_Proj() && mem->in(0)->is_Call()) {
 463         CallNode *call = mem->in(0)->as_Call();
 464         if (!call->may_modify(addr_t, phase)) {
 465           mem = call->in(TypeFunc::Memory);
 466           continue;         // (a) advance through independent call memory
 467         }
 468       } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
 469         mem = mem->in(0)->in(TypeFunc::Memory);
 470         continue;           // (a) advance through independent MemBar memory
 471       } else if (mem->is_MergeMem()) {
 472         int alias_idx = phase->C->get_alias_index(adr_type());
 473         mem = mem->as_MergeMem()->memory_at(alias_idx);
 474         continue;           // (a) advance through independent MergeMem memory
 475       }
 476     }
 477 
 478     // Unless there is an explicit 'continue', we must bail out here,
 479     // because 'mem' is an inscrutable memory state (e.g., a call).
 480     break;
 481   }
 482 
 483   return NULL;              // bail out
 484 }
 485 
 486 //----------------------calculate_adr_type-------------------------------------
 487 // Helper function.  Notices when the given type of address hits top or bottom.
 488 // Also, asserts a cross-check of the type against the expected address type.
 489 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
 490   if (t == Type::TOP)  return NULL; // does not touch memory any more?
 491   #ifdef PRODUCT
 492   cross_check = NULL;
 493   #else
 494   if (!VerifyAliases || is_error_reported() || Node::in_dump())  cross_check = NULL;
 495   #endif
 496   const TypePtr* tp = t->isa_ptr();
 497   if (tp == NULL) {
 498     assert(cross_check == NULL || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
 499     return TypePtr::BOTTOM;           // touches lots of memory
 500   } else {
 501     #ifdef ASSERT
 502     // %%%% [phh] We don't check the alias index if cross_check is
 503     //            TypeRawPtr::BOTTOM.  Needs to be investigated.
 504     if (cross_check != NULL &&
 505         cross_check != TypePtr::BOTTOM &&
 506         cross_check != TypeRawPtr::BOTTOM) {
 507       // Recheck the alias index, to see if it has changed (due to a bug).
 508       Compile* C = Compile::current();
 509       assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
 510              "must stay in the original alias category");
 511       // The type of the address must be contained in the adr_type,
 512       // disregarding "null"-ness.
 513       // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
 514       const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
 515       assert(cross_check->meet(tp_notnull) == cross_check,
 516              "real address must not escape from expected memory type");
 517     }
 518     #endif
 519     return tp;
 520   }
 521 }
 522 
 523 //------------------------adr_phi_is_loop_invariant----------------------------
 524 // A helper function for Ideal_DU_postCCP to check if a Phi in a counted
 525 // loop is loop invariant. Make a quick traversal of Phi and associated
 526 // CastPP nodes, looking to see if they are a closed group within the loop.
 527 bool MemNode::adr_phi_is_loop_invariant(Node* adr_phi, Node* cast) {
 528   // The idea is that the phi-nest must boil down to only CastPP nodes
 529   // with the same data. This implies that any path into the loop already
 530   // includes such a CastPP, and so the original cast, whatever its input,
 531   // must be covered by an equivalent cast, with an earlier control input.
 532   ResourceMark rm;
 533 
 534   // The loop entry input of the phi should be the unique dominating
 535   // node for every Phi/CastPP in the loop.
 536   Unique_Node_List closure;
 537   closure.push(adr_phi->in(LoopNode::EntryControl));
 538 
 539   // Add the phi node and the cast to the worklist.
 540   Unique_Node_List worklist;
 541   worklist.push(adr_phi);
 542   if( cast != NULL ){
 543     if( !cast->is_ConstraintCast() ) return false;
 544     worklist.push(cast);
 545   }
 546 
 547   // Begin recursive walk of phi nodes.
 548   while( worklist.size() ){
 549     // Take a node off the worklist
 550     Node *n = worklist.pop();
 551     if( !closure.member(n) ){
 552       // Add it to the closure.
 553       closure.push(n);
 554       // Make a sanity check to ensure we don't waste too much time here.
 555       if( closure.size() > 20) return false;
 556       // This node is OK if:
 557       //  - it is a cast of an identical value
 558       //  - or it is a phi node (then we add its inputs to the worklist)
 559       // Otherwise, the node is not OK, and we presume the cast is not invariant
 560       if( n->is_ConstraintCast() ){
 561         worklist.push(n->in(1));
 562       } else if( n->is_Phi() ) {
 563         for( uint i = 1; i < n->req(); i++ ) {
 564           worklist.push(n->in(i));
 565         }
 566       } else {
 567         return false;
 568       }
 569     }
 570   }
 571 
 572   // Quit when the worklist is empty, and we've found no offending nodes.
 573   return true;
 574 }
 575 
 576 //------------------------------Ideal_DU_postCCP-------------------------------
 577 // Find any cast-away of null-ness and keep its control.  Null cast-aways are
 578 // going away in this pass and we need to make this memory op depend on the
 579 // gating null check.
 580 
 581 // I tried to leave the CastPP's in.  This makes the graph more accurate in
 582 // some sense; we get to keep around the knowledge that an oop is not-null
 583 // after some test.  Alas, the CastPP's interfere with GVN (some values are
 584 // the regular oop, some are the CastPP of the oop, all merge at Phi's which
 585 // cannot collapse, etc).  This cost us 10% on SpecJVM, even when I removed
 586 // some of the more trivial cases in the optimizer.  Removing more useless
 587 // Phi's started allowing Loads to illegally float above null checks.  I gave
 588 // up on this approach.  CNC 10/20/2000
 589 Node *MemNode::Ideal_DU_postCCP( PhaseCCP *ccp ) {
 590   Node *ctr = in(MemNode::Control);
 591   Node *mem = in(MemNode::Memory);
 592   Node *adr = in(MemNode::Address);
 593   Node *skipped_cast = NULL;
 594   // Need a null check?  Regular static accesses do not because they are
 595   // from constant addresses.  Array ops are gated by the range check (which
 596   // always includes a NULL check).  Just check field ops.
 597   if( !ctr ) {
 598     // Scan upwards for the highest location we can place this memory op.
 599     while( true ) {
 600       switch( adr->Opcode() ) {
 601 
 602       case Op_AddP:             // No change to NULL-ness, so peek thru AddP's
 603         adr = adr->in(AddPNode::Base);
 604         continue;
 605 
 606       case Op_DecodeN:         // No change to NULL-ness, so peek thru
 607         adr = adr->in(1);
 608         continue;
 609 
 610       case Op_CastPP:
 611         // If the CastPP is useless, just peek on through it.
 612         if( ccp->type(adr) == ccp->type(adr->in(1)) ) {
 613           // Remember the cast that we've peeked though. If we peek
 614           // through more than one, then we end up remembering the highest
 615           // one, that is, if in a loop, the one closest to the top.
 616           skipped_cast = adr;
 617           adr = adr->in(1);
 618           continue;
 619         }
 620         // CastPP is going away in this pass!  We need this memory op to be
 621         // control-dependent on the test that is guarding the CastPP.
 622         ccp->hash_delete(this);
 623         set_req(MemNode::Control, adr->in(0));
 624         ccp->hash_insert(this);
 625         return this;
 626 
 627       case Op_Phi:
 628         // Attempt to float above a Phi to some dominating point.
 629         if (adr->in(0) != NULL && adr->in(0)->is_CountedLoop()) {
 630           // If we've already peeked through a Cast (which could have set the
 631           // control), we can't float above a Phi, because the skipped Cast
 632           // may not be loop invariant.
 633           if (adr_phi_is_loop_invariant(adr, skipped_cast)) {
 634             adr = adr->in(1);
 635             continue;
 636           }
 637         }
 638 
 639         // Intentional fallthrough!
 640 
 641         // No obvious dominating point.  The mem op is pinned below the Phi
 642         // by the Phi itself.  If the Phi goes away (no true value is merged)
 643         // then the mem op can float, but not indefinitely.  It must be pinned
 644         // behind the controls leading to the Phi.
 645       case Op_CheckCastPP:
 646         // These usually stick around to change address type, however a
 647         // useless one can be elided and we still need to pick up a control edge
 648         if (adr->in(0) == NULL) {
 649           // This CheckCastPP node has NO control and is likely useless. But we
 650           // need check further up the ancestor chain for a control input to keep
 651           // the node in place. 4959717.
 652           skipped_cast = adr;
 653           adr = adr->in(1);
 654           continue;
 655         }
 656         ccp->hash_delete(this);
 657         set_req(MemNode::Control, adr->in(0));
 658         ccp->hash_insert(this);
 659         return this;
 660 
 661         // List of "safe" opcodes; those that implicitly block the memory
 662         // op below any null check.
 663       case Op_CastX2P:          // no null checks on native pointers
 664       case Op_Parm:             // 'this' pointer is not null
 665       case Op_LoadP:            // Loading from within a klass
 666       case Op_LoadN:            // Loading from within a klass
 667       case Op_LoadKlass:        // Loading from within a klass
 668       case Op_ConP:             // Loading from a klass
 669       case Op_CreateEx:         // Sucking up the guts of an exception oop
 670       case Op_Con:              // Reading from TLS
 671       case Op_CMoveP:           // CMoveP is pinned
 672         break;                  // No progress
 673 
 674       case Op_Proj:             // Direct call to an allocation routine
 675       case Op_SCMemProj:        // Memory state from store conditional ops
 676 #ifdef ASSERT
 677         {
 678           assert(adr->as_Proj()->_con == TypeFunc::Parms, "must be return value");
 679           const Node* call = adr->in(0);
 680           if (call->is_CallStaticJava()) {
 681             const CallStaticJavaNode* call_java = call->as_CallStaticJava();
 682             const TypeTuple *r = call_java->tf()->range();
 683             assert(r->cnt() > TypeFunc::Parms, "must return value");
 684             const Type* ret_type = r->field_at(TypeFunc::Parms);
 685             assert(ret_type && ret_type->isa_ptr(), "must return pointer");
 686             // We further presume that this is one of
 687             // new_instance_Java, new_array_Java, or
 688             // the like, but do not assert for this.
 689           } else if (call->is_Allocate()) {
 690             // similar case to new_instance_Java, etc.
 691           } else if (!call->is_CallLeaf()) {
 692             // Projections from fetch_oop (OSR) are allowed as well.
 693             ShouldNotReachHere();
 694           }
 695         }
 696 #endif
 697         break;
 698       default:
 699         ShouldNotReachHere();
 700       }
 701       break;
 702     }
 703   }
 704 
 705   return  NULL;               // No progress
 706 }
 707 
 708 
 709 //=============================================================================
 710 uint LoadNode::size_of() const { return sizeof(*this); }
 711 uint LoadNode::cmp( const Node &n ) const
 712 { return !Type::cmp( _type, ((LoadNode&)n)._type ); }
 713 const Type *LoadNode::bottom_type() const { return _type; }
 714 uint LoadNode::ideal_reg() const {
 715   return Matcher::base2reg[_type->base()];
 716 }
 717 
 718 #ifndef PRODUCT
 719 void LoadNode::dump_spec(outputStream *st) const {
 720   MemNode::dump_spec(st);
 721   if( !Verbose && !WizardMode ) {
 722     // standard dump does this in Verbose and WizardMode
 723     st->print(" #"); _type->dump_on(st);
 724   }
 725 }
 726 #endif
 727 
 728 
 729 //----------------------------LoadNode::make-----------------------------------
 730 // Polymorphic factory method:
 731 Node *LoadNode::make( PhaseGVN& gvn, Node *ctl, Node *mem, Node *adr, const TypePtr* adr_type, const Type *rt, BasicType bt ) {
 732   Compile* C = gvn.C;
 733 
 734   // sanity check the alias category against the created node type
 735   assert(!(adr_type->isa_oopptr() &&
 736            adr_type->offset() == oopDesc::klass_offset_in_bytes()),
 737          "use LoadKlassNode instead");
 738   assert(!(adr_type->isa_aryptr() &&
 739            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
 740          "use LoadRangeNode instead");
 741   switch (bt) {
 742   case T_BOOLEAN:
 743   case T_BYTE:    return new (C, 3) LoadBNode(ctl, mem, adr, adr_type, rt->is_int()    );
 744   case T_INT:     return new (C, 3) LoadINode(ctl, mem, adr, adr_type, rt->is_int()    );
 745   case T_CHAR:    return new (C, 3) LoadCNode(ctl, mem, adr, adr_type, rt->is_int()    );
 746   case T_SHORT:   return new (C, 3) LoadSNode(ctl, mem, adr, adr_type, rt->is_int()    );
 747   case T_LONG:    return new (C, 3) LoadLNode(ctl, mem, adr, adr_type, rt->is_long()   );
 748   case T_FLOAT:   return new (C, 3) LoadFNode(ctl, mem, adr, adr_type, rt              );
 749   case T_DOUBLE:  return new (C, 3) LoadDNode(ctl, mem, adr, adr_type, rt              );
 750   case T_ADDRESS: return new (C, 3) LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr()    );
 751   case T_OBJECT:
 752 #ifdef _LP64
 753     if (adr->bottom_type()->is_narrow()) {
 754       const TypeNarrowOop* narrowtype;
 755       if (rt->isa_narrowoop()) {
 756         narrowtype = rt->is_narrowoop();
 757         rt = narrowtype->make_oopptr();
 758       } else {
 759         narrowtype = rt->is_oopptr()->make_narrowoop();
 760       }
 761       Node* load  = gvn.transform(new (C, 3) LoadNNode(ctl, mem, adr, adr_type, narrowtype));
 762 
 763       return new (C, 2) DecodeNNode(load, rt);
 764     } else
 765 #endif
 766       {
 767         assert(!adr->bottom_type()->is_narrow(), "should have got back a narrow oop");
 768         return new (C, 3) LoadPNode(ctl, mem, adr, adr_type, rt->is_oopptr());
 769       }
 770   }
 771   ShouldNotReachHere();
 772   return (LoadNode*)NULL;
 773 }
 774 
 775 LoadLNode* LoadLNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt) {
 776   bool require_atomic = true;
 777   return new (C, 3) LoadLNode(ctl, mem, adr, adr_type, rt->is_long(), require_atomic);
 778 }
 779 
 780 
 781 
 782 
 783 //------------------------------hash-------------------------------------------
 784 uint LoadNode::hash() const {
 785   // unroll addition of interesting fields
 786   return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
 787 }
 788 
 789 //---------------------------can_see_stored_value------------------------------
 790 // This routine exists to make sure this set of tests is done the same
 791 // everywhere.  We need to make a coordinated change: first LoadNode::Ideal
 792 // will change the graph shape in a way which makes memory alive twice at the
 793 // same time (uses the Oracle model of aliasing), then some
 794 // LoadXNode::Identity will fold things back to the equivalence-class model
 795 // of aliasing.
 796 Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
 797   Node* ld_adr = in(MemNode::Address);
 798 
 799   const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
 800   Compile::AliasType* atp = tp != NULL ? phase->C->alias_type(tp) : NULL;
 801   if (EliminateAutoBox && atp != NULL && atp->index() >= Compile::AliasIdxRaw &&
 802       atp->field() != NULL && !atp->field()->is_volatile()) {
 803     uint alias_idx = atp->index();
 804     bool final = atp->field()->is_final();
 805     Node* result = NULL;
 806     Node* current = st;
 807     // Skip through chains of MemBarNodes checking the MergeMems for
 808     // new states for the slice of this load.  Stop once any other
 809     // kind of node is encountered.  Loads from final memory can skip
 810     // through any kind of MemBar but normal loads shouldn't skip
 811     // through MemBarAcquire since the could allow them to move out of
 812     // a synchronized region.
 813     while (current->is_Proj()) {
 814       int opc = current->in(0)->Opcode();
 815       if ((final && opc == Op_MemBarAcquire) ||
 816           opc == Op_MemBarRelease || opc == Op_MemBarCPUOrder) {
 817         Node* mem = current->in(0)->in(TypeFunc::Memory);
 818         if (mem->is_MergeMem()) {
 819           MergeMemNode* merge = mem->as_MergeMem();
 820           Node* new_st = merge->memory_at(alias_idx);
 821           if (new_st == merge->base_memory()) {
 822             // Keep searching
 823             current = merge->base_memory();
 824             continue;
 825           }
 826           // Save the new memory state for the slice and fall through
 827           // to exit.
 828           result = new_st;
 829         }
 830       }
 831       break;
 832     }
 833     if (result != NULL) {
 834       st = result;
 835     }
 836   }
 837 
 838 
 839   // Loop around twice in the case Load -> Initialize -> Store.
 840   // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
 841   for (int trip = 0; trip <= 1; trip++) {
 842 
 843     if (st->is_Store()) {
 844       Node* st_adr = st->in(MemNode::Address);
 845       if (!phase->eqv(st_adr, ld_adr)) {
 846         // Try harder before giving up...  Match raw and non-raw pointers.
 847         intptr_t st_off = 0;
 848         AllocateNode* alloc = AllocateNode::Ideal_allocation(st_adr, phase, st_off);
 849         if (alloc == NULL)       return NULL;
 850         intptr_t ld_off = 0;
 851         AllocateNode* allo2 = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
 852         if (alloc != allo2)      return NULL;
 853         if (ld_off != st_off)    return NULL;
 854         // At this point we have proven something like this setup:
 855         //  A = Allocate(...)
 856         //  L = LoadQ(,  AddP(CastPP(, A.Parm),, #Off))
 857         //  S = StoreQ(, AddP(,        A.Parm  , #Off), V)
 858         // (Actually, we haven't yet proven the Q's are the same.)
 859         // In other words, we are loading from a casted version of
 860         // the same pointer-and-offset that we stored to.
 861         // Thus, we are able to replace L by V.
 862       }
 863       // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
 864       if (store_Opcode() != st->Opcode())
 865         return NULL;
 866       return st->in(MemNode::ValueIn);
 867     }
 868 
 869     intptr_t offset = 0;  // scratch
 870 
 871     // A load from a freshly-created object always returns zero.
 872     // (This can happen after LoadNode::Ideal resets the load's memory input
 873     // to find_captured_store, which returned InitializeNode::zero_memory.)
 874     if (st->is_Proj() && st->in(0)->is_Allocate() &&
 875         st->in(0) == AllocateNode::Ideal_allocation(ld_adr, phase, offset) &&
 876         offset >= st->in(0)->as_Allocate()->minimum_header_size()) {
 877       // return a zero value for the load's basic type
 878       // (This is one of the few places where a generic PhaseTransform
 879       // can create new nodes.  Think of it as lazily manifesting
 880       // virtually pre-existing constants.)
 881       return phase->zerocon(memory_type());
 882     }
 883 
 884     // A load from an initialization barrier can match a captured store.
 885     if (st->is_Proj() && st->in(0)->is_Initialize()) {
 886       InitializeNode* init = st->in(0)->as_Initialize();
 887       AllocateNode* alloc = init->allocation();
 888       if (alloc != NULL &&
 889           alloc == AllocateNode::Ideal_allocation(ld_adr, phase, offset)) {
 890         // examine a captured store value
 891         st = init->find_captured_store(offset, memory_size(), phase);
 892         if (st != NULL)
 893           continue;             // take one more trip around
 894       }
 895     }
 896 
 897     break;
 898   }
 899 
 900   return NULL;
 901 }
 902 
 903 //----------------------is_instance_field_load_with_local_phi------------------
 904 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
 905   if( in(MemNode::Memory)->is_Phi() && in(MemNode::Memory)->in(0) == ctrl &&
 906       in(MemNode::Address)->is_AddP() ) {
 907     const TypeOopPtr* t_oop = in(MemNode::Address)->bottom_type()->isa_oopptr();
 908     // Only instances.
 909     if( t_oop != NULL && t_oop->is_instance_field() &&
 910         t_oop->offset() != Type::OffsetBot &&
 911         t_oop->offset() != Type::OffsetTop) {
 912       return true;
 913     }
 914   }
 915   return false;
 916 }
 917 
 918 //------------------------------Identity---------------------------------------
 919 // Loads are identity if previous store is to same address
 920 Node *LoadNode::Identity( PhaseTransform *phase ) {
 921   // If the previous store-maker is the right kind of Store, and the store is
 922   // to the same address, then we are equal to the value stored.
 923   Node* mem = in(MemNode::Memory);
 924   Node* value = can_see_stored_value(mem, phase);
 925   if( value ) {
 926     // byte, short & char stores truncate naturally.
 927     // A load has to load the truncated value which requires
 928     // some sort of masking operation and that requires an
 929     // Ideal call instead of an Identity call.
 930     if (memory_size() < BytesPerInt) {
 931       // If the input to the store does not fit with the load's result type,
 932       // it must be truncated via an Ideal call.
 933       if (!phase->type(value)->higher_equal(phase->type(this)))
 934         return this;
 935     }
 936     // (This works even when value is a Con, but LoadNode::Value
 937     // usually runs first, producing the singleton type of the Con.)
 938     return value;
 939   }
 940 
 941   // Search for an existing data phi which was generated before for the same
 942   // instance's field to avoid infinite genertion of phis in a loop.
 943   Node *region = mem->in(0);
 944   if (is_instance_field_load_with_local_phi(region)) {
 945     const TypePtr *addr_t = in(MemNode::Address)->bottom_type()->isa_ptr();
 946     int this_index  = phase->C->get_alias_index(addr_t);
 947     int this_offset = addr_t->offset();
 948     int this_id    = addr_t->is_oopptr()->instance_id();
 949     const Type* this_type = bottom_type();
 950     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
 951       Node* phi = region->fast_out(i);
 952       if (phi->is_Phi() && phi != mem &&
 953           phi->as_Phi()->is_same_inst_field(this_type, this_id, this_index, this_offset)) {
 954         return phi;
 955       }
 956     }
 957   }
 958 
 959   return this;
 960 }
 961 
 962 
 963 // Returns true if the AliasType refers to the field that holds the
 964 // cached box array.  Currently only handles the IntegerCache case.
 965 static bool is_autobox_cache(Compile::AliasType* atp) {
 966   if (atp != NULL && atp->field() != NULL) {
 967     ciField* field = atp->field();
 968     ciSymbol* klass = field->holder()->name();
 969     if (field->name() == ciSymbol::cache_field_name() &&
 970         field->holder()->uses_default_loader() &&
 971         klass == ciSymbol::java_lang_Integer_IntegerCache()) {
 972       return true;
 973     }
 974   }
 975   return false;
 976 }
 977 
 978 // Fetch the base value in the autobox array
 979 static bool fetch_autobox_base(Compile::AliasType* atp, int& cache_offset) {
 980   if (atp != NULL && atp->field() != NULL) {
 981     ciField* field = atp->field();
 982     ciSymbol* klass = field->holder()->name();
 983     if (field->name() == ciSymbol::cache_field_name() &&
 984         field->holder()->uses_default_loader() &&
 985         klass == ciSymbol::java_lang_Integer_IntegerCache()) {
 986       assert(field->is_constant(), "what?");
 987       ciObjArray* array = field->constant_value().as_object()->as_obj_array();
 988       // Fetch the box object at the base of the array and get its value
 989       ciInstance* box = array->obj_at(0)->as_instance();
 990       ciInstanceKlass* ik = box->klass()->as_instance_klass();
 991       if (ik->nof_nonstatic_fields() == 1) {
 992         // This should be true nonstatic_field_at requires calling
 993         // nof_nonstatic_fields so check it anyway
 994         ciConstant c = box->field_value(ik->nonstatic_field_at(0));
 995         cache_offset = c.as_int();
 996       }
 997       return true;
 998     }
 999   }
1000   return false;
1001 }
1002 
1003 // Returns true if the AliasType refers to the value field of an
1004 // autobox object.  Currently only handles Integer.
1005 static bool is_autobox_object(Compile::AliasType* atp) {
1006   if (atp != NULL && atp->field() != NULL) {
1007     ciField* field = atp->field();
1008     ciSymbol* klass = field->holder()->name();
1009     if (field->name() == ciSymbol::value_name() &&
1010         field->holder()->uses_default_loader() &&
1011         klass == ciSymbol::java_lang_Integer()) {
1012       return true;
1013     }
1014   }
1015   return false;
1016 }
1017 
1018 
1019 // We're loading from an object which has autobox behaviour.
1020 // If this object is result of a valueOf call we'll have a phi
1021 // merging a newly allocated object and a load from the cache.
1022 // We want to replace this load with the original incoming
1023 // argument to the valueOf call.
1024 Node* LoadNode::eliminate_autobox(PhaseGVN* phase) {
1025   Node* base = in(Address)->in(AddPNode::Base);
1026   if (base->is_Phi() && base->req() == 3) {
1027     AllocateNode* allocation = NULL;
1028     int allocation_index = -1;
1029     int load_index = -1;
1030     for (uint i = 1; i < base->req(); i++) {
1031       allocation = AllocateNode::Ideal_allocation(base->in(i), phase);
1032       if (allocation != NULL) {
1033         allocation_index = i;
1034         load_index = 3 - allocation_index;
1035         break;
1036       }
1037     }
1038     LoadNode* load = NULL;
1039     if (allocation != NULL && base->in(load_index)->is_Load()) {
1040       load = base->in(load_index)->as_Load();
1041     }
1042     if (load != NULL && in(Memory)->is_Phi() && in(Memory)->in(0) == base->in(0)) {
1043       // Push the loads from the phi that comes from valueOf up
1044       // through it to allow elimination of the loads and the recovery
1045       // of the original value.
1046       Node* mem_phi = in(Memory);
1047       Node* offset = in(Address)->in(AddPNode::Offset);
1048 
1049       Node* in1 = clone();
1050       Node* in1_addr = in1->in(Address)->clone();
1051       in1_addr->set_req(AddPNode::Base, base->in(allocation_index));
1052       in1_addr->set_req(AddPNode::Address, base->in(allocation_index));
1053       in1_addr->set_req(AddPNode::Offset, offset);
1054       in1->set_req(0, base->in(allocation_index));
1055       in1->set_req(Address, in1_addr);
1056       in1->set_req(Memory, mem_phi->in(allocation_index));
1057 
1058       Node* in2 = clone();
1059       Node* in2_addr = in2->in(Address)->clone();
1060       in2_addr->set_req(AddPNode::Base, base->in(load_index));
1061       in2_addr->set_req(AddPNode::Address, base->in(load_index));
1062       in2_addr->set_req(AddPNode::Offset, offset);
1063       in2->set_req(0, base->in(load_index));
1064       in2->set_req(Address, in2_addr);
1065       in2->set_req(Memory, mem_phi->in(load_index));
1066 
1067       in1_addr = phase->transform(in1_addr);
1068       in1 =      phase->transform(in1);
1069       in2_addr = phase->transform(in2_addr);
1070       in2 =      phase->transform(in2);
1071 
1072       PhiNode* result = PhiNode::make_blank(base->in(0), this);
1073       result->set_req(allocation_index, in1);
1074       result->set_req(load_index, in2);
1075       return result;
1076     }
1077   } else if (base->is_Load()) {
1078     // Eliminate the load of Integer.value for integers from the cache
1079     // array by deriving the value from the index into the array.
1080     // Capture the offset of the load and then reverse the computation.
1081     Node* load_base = base->in(Address)->in(AddPNode::Base);
1082     if (load_base != NULL) {
1083       Compile::AliasType* atp = phase->C->alias_type(load_base->adr_type());
1084       intptr_t cache_offset;
1085       int shift = -1;
1086       Node* cache = NULL;
1087       if (is_autobox_cache(atp)) {
1088         shift  = exact_log2(type2aelembytes(T_OBJECT));
1089         cache = AddPNode::Ideal_base_and_offset(load_base->in(Address), phase, cache_offset);
1090       }
1091       if (cache != NULL && base->in(Address)->is_AddP()) {
1092         Node* elements[4];
1093         int count = base->in(Address)->as_AddP()->unpack_offsets(elements, ARRAY_SIZE(elements));
1094         int cache_low;
1095         if (count > 0 && fetch_autobox_base(atp, cache_low)) {
1096           int offset = arrayOopDesc::base_offset_in_bytes(memory_type()) - (cache_low << shift);
1097           // Add up all the offsets making of the address of the load
1098           Node* result = elements[0];
1099           for (int i = 1; i < count; i++) {
1100             result = phase->transform(new (phase->C, 3) AddXNode(result, elements[i]));
1101           }
1102           // Remove the constant offset from the address and then
1103           // remove the scaling of the offset to recover the original index.
1104           result = phase->transform(new (phase->C, 3) AddXNode(result, phase->MakeConX(-offset)));
1105           if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) {
1106             // Peel the shift off directly but wrap it in a dummy node
1107             // since Ideal can't return existing nodes
1108             result = new (phase->C, 3) RShiftXNode(result->in(1), phase->intcon(0));
1109           } else {
1110             result = new (phase->C, 3) RShiftXNode(result, phase->intcon(shift));
1111           }
1112 #ifdef _LP64
1113           result = new (phase->C, 2) ConvL2INode(phase->transform(result));
1114 #endif
1115           return result;
1116         }
1117       }
1118     }
1119   }
1120   return NULL;
1121 }
1122 
1123 
1124 //------------------------------Ideal------------------------------------------
1125 // If the load is from Field memory and the pointer is non-null, we can
1126 // zero out the control input.
1127 // If the offset is constant and the base is an object allocation,
1128 // try to hook me up to the exact initializing store.
1129 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1130   Node* p = MemNode::Ideal_common(phase, can_reshape);
1131   if (p)  return (p == NodeSentinel) ? NULL : p;
1132 
1133   Node* ctrl    = in(MemNode::Control);
1134   Node* address = in(MemNode::Address);
1135 
1136   // Skip up past a SafePoint control.  Cannot do this for Stores because
1137   // pointer stores & cardmarks must stay on the same side of a SafePoint.
1138   if( ctrl != NULL && ctrl->Opcode() == Op_SafePoint &&
1139       phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw ) {
1140     ctrl = ctrl->in(0);
1141     set_req(MemNode::Control,ctrl);
1142   }
1143 
1144   // Check for useless control edge in some common special cases
1145   if (in(MemNode::Control) != NULL) {
1146     intptr_t ignore = 0;
1147     Node*    base   = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1148     if (base != NULL
1149         && phase->type(base)->higher_equal(TypePtr::NOTNULL)
1150         && all_controls_dominate(base, phase->C->start())) {
1151       // A method-invariant, non-null address (constant or 'this' argument).
1152       set_req(MemNode::Control, NULL);
1153     }
1154   }
1155 
1156   if (EliminateAutoBox && can_reshape && in(Address)->is_AddP()) {
1157     Node* base = in(Address)->in(AddPNode::Base);
1158     if (base != NULL) {
1159       Compile::AliasType* atp = phase->C->alias_type(adr_type());
1160       if (is_autobox_object(atp)) {
1161         Node* result = eliminate_autobox(phase);
1162         if (result != NULL) return result;
1163       }
1164     }
1165   }
1166 
1167   Node* mem = in(MemNode::Memory);
1168   const TypePtr *addr_t = phase->type(address)->isa_ptr();
1169 
1170   if (addr_t != NULL) {
1171     // try to optimize our memory input
1172     Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, phase);
1173     if (opt_mem != mem) {
1174       set_req(MemNode::Memory, opt_mem);
1175       return this;
1176     }
1177     const TypeOopPtr *t_oop = addr_t->isa_oopptr();
1178     if (can_reshape && opt_mem->is_Phi() &&
1179         (t_oop != NULL) && t_oop->is_instance_field()) {
1180       assert(t_oop->offset() != Type::OffsetBot && t_oop->offset() != Type::OffsetTop, "");
1181       Node *region = opt_mem->in(0);
1182       uint cnt = opt_mem->req();
1183       for( uint i = 1; i < cnt; i++ ) {
1184         Node *in = opt_mem->in(i);
1185         if( in == NULL ) {
1186           region = NULL; // Wait stable graph
1187           break;
1188         }
1189       }
1190       if (region != NULL) {
1191         // Check for loop invariant.
1192         if (cnt == 3) {
1193           for( uint i = 1; i < cnt; i++ ) {
1194             Node *in = opt_mem->in(i);
1195             Node* m = MemNode::optimize_memory_chain(in, addr_t, phase);
1196             if (m == opt_mem) {
1197               set_req(MemNode::Memory, opt_mem->in(cnt - i)); // Skip this phi.
1198               return this;
1199             }
1200           }
1201         }
1202         // Split through Phi (see original code in loopopts.cpp).
1203         assert(phase->C->have_alias_type(addr_t), "instance should have alias type");
1204 
1205         // Do nothing here if Identity will find a value
1206         // (to avoid infinite chain of value phis generation).
1207         if ( !phase->eqv(this, this->Identity(phase)) )
1208           return NULL;
1209 
1210         const Type* this_type = this->bottom_type();
1211         int this_index  = phase->C->get_alias_index(addr_t);
1212         int this_offset = addr_t->offset();
1213         int this_iid    = addr_t->is_oopptr()->instance_id();
1214         int wins = 0;
1215         PhaseIterGVN *igvn = phase->is_IterGVN();
1216         Node *phi = new (igvn->C, region->req()) PhiNode(region, this_type, NULL, this_iid, this_index, this_offset);
1217         for( uint i = 1; i < region->req(); i++ ) {
1218           Node *x;
1219           Node* the_clone = NULL;
1220           if( region->in(i) == phase->C->top() ) {
1221             x = phase->C->top();      // Dead path?  Use a dead data op
1222           } else {
1223             x = this->clone();        // Else clone up the data op
1224             the_clone = x;            // Remember for possible deletion.
1225             // Alter data node to use pre-phi inputs
1226             if( this->in(0) == region ) {
1227               x->set_req( 0, region->in(i) );
1228             } else {
1229               x->set_req( 0, NULL );
1230             }
1231             for( uint j = 1; j < this->req(); j++ ) {
1232               Node *in = this->in(j);
1233               if( in->is_Phi() && in->in(0) == region )
1234                 x->set_req( j, in->in(i) ); // Use pre-Phi input for the clone
1235             }
1236           }
1237           // Check for a 'win' on some paths
1238           const Type *t = x->Value(igvn);
1239 
1240           bool singleton = t->singleton();
1241 
1242           // See comments in PhaseIdealLoop::split_thru_phi().
1243           if( singleton && t == Type::TOP ) {
1244             singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
1245           }
1246 
1247           if( singleton ) {
1248             wins++;
1249             x = igvn->makecon(t);
1250           } else {
1251             // We now call Identity to try to simplify the cloned node.
1252             // Note that some Identity methods call phase->type(this).
1253             // Make sure that the type array is big enough for
1254             // our new node, even though we may throw the node away.
1255             // (This tweaking with igvn only works because x is a new node.)
1256             igvn->set_type(x, t);
1257             Node *y = x->Identity(igvn);
1258             if( y != x ) {
1259               wins++;
1260               x = y;
1261             } else {
1262               y = igvn->hash_find(x);
1263               if( y ) {
1264                 wins++;
1265                 x = y;
1266               } else {
1267                 // Else x is a new node we are keeping
1268                 // We do not need register_new_node_with_optimizer
1269                 // because set_type has already been called.
1270                 igvn->_worklist.push(x);
1271               }
1272             }
1273           }
1274           if (x != the_clone && the_clone != NULL)
1275             igvn->remove_dead_node(the_clone);
1276           phi->set_req(i, x);
1277         }
1278         if( wins > 0 ) {
1279           // Record Phi
1280           igvn->register_new_node_with_optimizer(phi);
1281           return phi;
1282         } else {
1283           igvn->remove_dead_node(phi);
1284         }
1285       }
1286     }
1287   }
1288 
1289   // Check for prior store with a different base or offset; make Load
1290   // independent.  Skip through any number of them.  Bail out if the stores
1291   // are in an endless dead cycle and report no progress.  This is a key
1292   // transform for Reflection.  However, if after skipping through the Stores
1293   // we can't then fold up against a prior store do NOT do the transform as
1294   // this amounts to using the 'Oracle' model of aliasing.  It leaves the same
1295   // array memory alive twice: once for the hoisted Load and again after the
1296   // bypassed Store.  This situation only works if EVERYBODY who does
1297   // anti-dependence work knows how to bypass.  I.e. we need all
1298   // anti-dependence checks to ask the same Oracle.  Right now, that Oracle is
1299   // the alias index stuff.  So instead, peek through Stores and IFF we can
1300   // fold up, do so.
1301   Node* prev_mem = find_previous_store(phase);
1302   // Steps (a), (b):  Walk past independent stores to find an exact match.
1303   if (prev_mem != NULL && prev_mem != in(MemNode::Memory)) {
1304     // (c) See if we can fold up on the spot, but don't fold up here.
1305     // Fold-up might require truncation (for LoadB/LoadS/LoadC) or
1306     // just return a prior value, which is done by Identity calls.
1307     if (can_see_stored_value(prev_mem, phase)) {
1308       // Make ready for step (d):
1309       set_req(MemNode::Memory, prev_mem);
1310       return this;
1311     }
1312   }
1313 
1314   return NULL;                  // No further progress
1315 }
1316 
1317 // Helper to recognize certain Klass fields which are invariant across
1318 // some group of array types (e.g., int[] or all T[] where T < Object).
1319 const Type*
1320 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
1321                                  ciKlass* klass) const {
1322   if (tkls->offset() == Klass::modifier_flags_offset_in_bytes() + (int)sizeof(oopDesc)) {
1323     // The field is Klass::_modifier_flags.  Return its (constant) value.
1324     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
1325     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
1326     return TypeInt::make(klass->modifier_flags());
1327   }
1328   if (tkls->offset() == Klass::access_flags_offset_in_bytes() + (int)sizeof(oopDesc)) {
1329     // The field is Klass::_access_flags.  Return its (constant) value.
1330     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
1331     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
1332     return TypeInt::make(klass->access_flags());
1333   }
1334   if (tkls->offset() == Klass::layout_helper_offset_in_bytes() + (int)sizeof(oopDesc)) {
1335     // The field is Klass::_layout_helper.  Return its constant value if known.
1336     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
1337     return TypeInt::make(klass->layout_helper());
1338   }
1339 
1340   // No match.
1341   return NULL;
1342 }
1343 
1344 //------------------------------Value-----------------------------------------
1345 const Type *LoadNode::Value( PhaseTransform *phase ) const {
1346   // Either input is TOP ==> the result is TOP
1347   Node* mem = in(MemNode::Memory);
1348   const Type *t1 = phase->type(mem);
1349   if (t1 == Type::TOP)  return Type::TOP;
1350   Node* adr = in(MemNode::Address);
1351   const TypePtr* tp = phase->type(adr)->isa_ptr();
1352   if (tp == NULL || tp->empty())  return Type::TOP;
1353   int off = tp->offset();
1354   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
1355 
1356   // Try to guess loaded type from pointer type
1357   if (tp->base() == Type::AryPtr) {
1358     const Type *t = tp->is_aryptr()->elem();
1359     // Don't do this for integer types. There is only potential profit if
1360     // the element type t is lower than _type; that is, for int types, if _type is
1361     // more restrictive than t.  This only happens here if one is short and the other
1362     // char (both 16 bits), and in those cases we've made an intentional decision
1363     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
1364     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
1365     //
1366     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
1367     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
1368     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
1369     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
1370     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
1371     // In fact, that could have been the original type of p1, and p1 could have
1372     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
1373     // expression (LShiftL quux 3) independently optimized to the constant 8.
1374     if ((t->isa_int() == NULL) && (t->isa_long() == NULL)
1375         && Opcode() != Op_LoadKlass) {
1376       // t might actually be lower than _type, if _type is a unique
1377       // concrete subclass of abstract class t.
1378       // Make sure the reference is not into the header, by comparing
1379       // the offset against the offset of the start of the array's data.
1380       // Different array types begin at slightly different offsets (12 vs. 16).
1381       // We choose T_BYTE as an example base type that is least restrictive
1382       // as to alignment, which will therefore produce the smallest
1383       // possible base offset.
1384       const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1385       if ((uint)off >= (uint)min_base_off) {  // is the offset beyond the header?
1386         const Type* jt = t->join(_type);
1387         // In any case, do not allow the join, per se, to empty out the type.
1388         if (jt->empty() && !t->empty()) {
1389           // This can happen if a interface-typed array narrows to a class type.
1390           jt = _type;
1391         }
1392 
1393         if (EliminateAutoBox) {
1394           // The pointers in the autobox arrays are always non-null
1395           Node* base = in(Address)->in(AddPNode::Base);
1396           if (base != NULL) {
1397             Compile::AliasType* atp = phase->C->alias_type(base->adr_type());
1398             if (is_autobox_cache(atp)) {
1399               return jt->join(TypePtr::NOTNULL)->is_ptr();
1400             }
1401           }
1402         }
1403         return jt;
1404       }
1405     }
1406   } else if (tp->base() == Type::InstPtr) {
1407     assert( off != Type::OffsetBot ||
1408             // arrays can be cast to Objects
1409             tp->is_oopptr()->klass()->is_java_lang_Object() ||
1410             // unsafe field access may not have a constant offset
1411             phase->C->has_unsafe_access(),
1412             "Field accesses must be precise" );
1413     // For oop loads, we expect the _type to be precise
1414   } else if (tp->base() == Type::KlassPtr) {
1415     assert( off != Type::OffsetBot ||
1416             // arrays can be cast to Objects
1417             tp->is_klassptr()->klass()->is_java_lang_Object() ||
1418             // also allow array-loading from the primary supertype
1419             // array during subtype checks
1420             Opcode() == Op_LoadKlass,
1421             "Field accesses must be precise" );
1422     // For klass/static loads, we expect the _type to be precise
1423   }
1424 
1425   const TypeKlassPtr *tkls = tp->isa_klassptr();
1426   if (tkls != NULL && !StressReflectiveCode) {
1427     ciKlass* klass = tkls->klass();
1428     if (klass->is_loaded() && tkls->klass_is_exact()) {
1429       // We are loading a field from a Klass metaobject whose identity
1430       // is known at compile time (the type is "exact" or "precise").
1431       // Check for fields we know are maintained as constants by the VM.
1432       if (tkls->offset() == Klass::super_check_offset_offset_in_bytes() + (int)sizeof(oopDesc)) {
1433         // The field is Klass::_super_check_offset.  Return its (constant) value.
1434         // (Folds up type checking code.)
1435         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
1436         return TypeInt::make(klass->super_check_offset());
1437       }
1438       // Compute index into primary_supers array
1439       juint depth = (tkls->offset() - (Klass::primary_supers_offset_in_bytes() + (int)sizeof(oopDesc))) / sizeof(klassOop);
1440       // Check for overflowing; use unsigned compare to handle the negative case.
1441       if( depth < ciKlass::primary_super_limit() ) {
1442         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
1443         // (Folds up type checking code.)
1444         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1445         ciKlass *ss = klass->super_of_depth(depth);
1446         return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1447       }
1448       const Type* aift = load_array_final_field(tkls, klass);
1449       if (aift != NULL)  return aift;
1450       if (tkls->offset() == in_bytes(arrayKlass::component_mirror_offset()) + (int)sizeof(oopDesc)
1451           && klass->is_array_klass()) {
1452         // The field is arrayKlass::_component_mirror.  Return its (constant) value.
1453         // (Folds up aClassConstant.getComponentType, common in Arrays.copyOf.)
1454         assert(Opcode() == Op_LoadP, "must load an oop from _component_mirror");
1455         return TypeInstPtr::make(klass->as_array_klass()->component_mirror());
1456       }
1457       if (tkls->offset() == Klass::java_mirror_offset_in_bytes() + (int)sizeof(oopDesc)) {
1458         // The field is Klass::_java_mirror.  Return its (constant) value.
1459         // (Folds up the 2nd indirection in anObjConstant.getClass().)
1460         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
1461         return TypeInstPtr::make(klass->java_mirror());
1462       }
1463     }
1464 
1465     // We can still check if we are loading from the primary_supers array at a
1466     // shallow enough depth.  Even though the klass is not exact, entries less
1467     // than or equal to its super depth are correct.
1468     if (klass->is_loaded() ) {
1469       ciType *inner = klass->klass();
1470       while( inner->is_obj_array_klass() )
1471         inner = inner->as_obj_array_klass()->base_element_type();
1472       if( inner->is_instance_klass() &&
1473           !inner->as_instance_klass()->flags().is_interface() ) {
1474         // Compute index into primary_supers array
1475         juint depth = (tkls->offset() - (Klass::primary_supers_offset_in_bytes() + (int)sizeof(oopDesc))) / sizeof(klassOop);
1476         // Check for overflowing; use unsigned compare to handle the negative case.
1477         if( depth < ciKlass::primary_super_limit() &&
1478             depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
1479           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
1480           // (Folds up type checking code.)
1481           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1482           ciKlass *ss = klass->super_of_depth(depth);
1483           return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1484         }
1485       }
1486     }
1487 
1488     // If the type is enough to determine that the thing is not an array,
1489     // we can give the layout_helper a positive interval type.
1490     // This will help short-circuit some reflective code.
1491     if (tkls->offset() == Klass::layout_helper_offset_in_bytes() + (int)sizeof(oopDesc)
1492         && !klass->is_array_klass() // not directly typed as an array
1493         && !klass->is_interface()  // specifically not Serializable & Cloneable
1494         && !klass->is_java_lang_Object()   // not the supertype of all T[]
1495         ) {
1496       // Note:  When interfaces are reliable, we can narrow the interface
1497       // test to (klass != Serializable && klass != Cloneable).
1498       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
1499       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
1500       // The key property of this type is that it folds up tests
1501       // for array-ness, since it proves that the layout_helper is positive.
1502       // Thus, a generic value like the basic object layout helper works fine.
1503       return TypeInt::make(min_size, max_jint, Type::WidenMin);
1504     }
1505   }
1506 
1507   // If we are loading from a freshly-allocated object, produce a zero,
1508   // if the load is provably beyond the header of the object.
1509   // (Also allow a variable load from a fresh array to produce zero.)
1510   if (ReduceFieldZeroing) {
1511     Node* value = can_see_stored_value(mem,phase);
1512     if (value != NULL && value->is_Con())
1513       return value->bottom_type();
1514   }
1515 
1516   const TypeOopPtr *tinst = tp->isa_oopptr();
1517   if (tinst != NULL && tinst->is_instance_field()) {
1518     // If we have an instance type and our memory input is the
1519     // programs's initial memory state, there is no matching store,
1520     // so just return a zero of the appropriate type
1521     Node *mem = in(MemNode::Memory);
1522     if (mem->is_Parm() && mem->in(0)->is_Start()) {
1523       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
1524       return Type::get_zero_type(_type->basic_type());
1525     }
1526   }
1527   return _type;
1528 }
1529 
1530 //------------------------------match_edge-------------------------------------
1531 // Do we Match on this edge index or not?  Match only the address.
1532 uint LoadNode::match_edge(uint idx) const {
1533   return idx == MemNode::Address;
1534 }
1535 
1536 //--------------------------LoadBNode::Ideal--------------------------------------
1537 //
1538 //  If the previous store is to the same address as this load,
1539 //  and the value stored was larger than a byte, replace this load
1540 //  with the value stored truncated to a byte.  If no truncation is
1541 //  needed, the replacement is done in LoadNode::Identity().
1542 //
1543 Node *LoadBNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1544   Node* mem = in(MemNode::Memory);
1545   Node* value = can_see_stored_value(mem,phase);
1546   if( value && !phase->type(value)->higher_equal( _type ) ) {
1547     Node *result = phase->transform( new (phase->C, 3) LShiftINode(value, phase->intcon(24)) );
1548     return new (phase->C, 3) RShiftINode(result, phase->intcon(24));
1549   }
1550   // Identity call will handle the case where truncation is not needed.
1551   return LoadNode::Ideal(phase, can_reshape);
1552 }
1553 
1554 //--------------------------LoadCNode::Ideal--------------------------------------
1555 //
1556 //  If the previous store is to the same address as this load,
1557 //  and the value stored was larger than a char, replace this load
1558 //  with the value stored truncated to a char.  If no truncation is
1559 //  needed, the replacement is done in LoadNode::Identity().
1560 //
1561 Node *LoadCNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1562   Node* mem = in(MemNode::Memory);
1563   Node* value = can_see_stored_value(mem,phase);
1564   if( value && !phase->type(value)->higher_equal( _type ) )
1565     return new (phase->C, 3) AndINode(value,phase->intcon(0xFFFF));
1566   // Identity call will handle the case where truncation is not needed.
1567   return LoadNode::Ideal(phase, can_reshape);
1568 }
1569 
1570 //--------------------------LoadSNode::Ideal--------------------------------------
1571 //
1572 //  If the previous store is to the same address as this load,
1573 //  and the value stored was larger than a short, replace this load
1574 //  with the value stored truncated to a short.  If no truncation is
1575 //  needed, the replacement is done in LoadNode::Identity().
1576 //
1577 Node *LoadSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1578   Node* mem = in(MemNode::Memory);
1579   Node* value = can_see_stored_value(mem,phase);
1580   if( value && !phase->type(value)->higher_equal( _type ) ) {
1581     Node *result = phase->transform( new (phase->C, 3) LShiftINode(value, phase->intcon(16)) );
1582     return new (phase->C, 3) RShiftINode(result, phase->intcon(16));
1583   }
1584   // Identity call will handle the case where truncation is not needed.
1585   return LoadNode::Ideal(phase, can_reshape);
1586 }
1587 
1588 //=============================================================================
1589 //------------------------------Value------------------------------------------
1590 const Type *LoadKlassNode::Value( PhaseTransform *phase ) const {
1591   // Either input is TOP ==> the result is TOP
1592   const Type *t1 = phase->type( in(MemNode::Memory) );
1593   if (t1 == Type::TOP)  return Type::TOP;
1594   Node *adr = in(MemNode::Address);
1595   const Type *t2 = phase->type( adr );
1596   if (t2 == Type::TOP)  return Type::TOP;
1597   const TypePtr *tp = t2->is_ptr();
1598   if (TypePtr::above_centerline(tp->ptr()) ||
1599       tp->ptr() == TypePtr::Null)  return Type::TOP;
1600 
1601   // Return a more precise klass, if possible
1602   const TypeInstPtr *tinst = tp->isa_instptr();
1603   if (tinst != NULL) {
1604     ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
1605     int offset = tinst->offset();
1606     if (ik == phase->C->env()->Class_klass()
1607         && (offset == java_lang_Class::klass_offset_in_bytes() ||
1608             offset == java_lang_Class::array_klass_offset_in_bytes())) {
1609       // We are loading a special hidden field from a Class mirror object,
1610       // the field which points to the VM's Klass metaobject.
1611       ciType* t = tinst->java_mirror_type();
1612       // java_mirror_type returns non-null for compile-time Class constants.
1613       if (t != NULL) {
1614         // constant oop => constant klass
1615         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
1616           return TypeKlassPtr::make(ciArrayKlass::make(t));
1617         }
1618         if (!t->is_klass()) {
1619           // a primitive Class (e.g., int.class) has NULL for a klass field
1620           return TypePtr::NULL_PTR;
1621         }
1622         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
1623         return TypeKlassPtr::make(t->as_klass());
1624       }
1625       // non-constant mirror, so we can't tell what's going on
1626     }
1627     if( !ik->is_loaded() )
1628       return _type;             // Bail out if not loaded
1629     if (offset == oopDesc::klass_offset_in_bytes()) {
1630       if (tinst->klass_is_exact()) {
1631         return TypeKlassPtr::make(ik);
1632       }
1633       // See if we can become precise: no subklasses and no interface
1634       // (Note:  We need to support verified interfaces.)
1635       if (!ik->is_interface() && !ik->has_subklass()) {
1636         //assert(!UseExactTypes, "this code should be useless with exact types");
1637         // Add a dependence; if any subclass added we need to recompile
1638         if (!ik->is_final()) {
1639           // %%% should use stronger assert_unique_concrete_subtype instead
1640           phase->C->dependencies()->assert_leaf_type(ik);
1641         }
1642         // Return precise klass
1643         return TypeKlassPtr::make(ik);
1644       }
1645 
1646       // Return root of possible klass
1647       return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
1648     }
1649   }
1650 
1651   // Check for loading klass from an array
1652   const TypeAryPtr *tary = tp->isa_aryptr();
1653   if( tary != NULL ) {
1654     ciKlass *tary_klass = tary->klass();
1655     if (tary_klass != NULL   // can be NULL when at BOTTOM or TOP
1656         && tary->offset() == oopDesc::klass_offset_in_bytes()) {
1657       if (tary->klass_is_exact()) {
1658         return TypeKlassPtr::make(tary_klass);
1659       }
1660       ciArrayKlass *ak = tary->klass()->as_array_klass();
1661       // If the klass is an object array, we defer the question to the
1662       // array component klass.
1663       if( ak->is_obj_array_klass() ) {
1664         assert( ak->is_loaded(), "" );
1665         ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
1666         if( base_k->is_loaded() && base_k->is_instance_klass() ) {
1667           ciInstanceKlass* ik = base_k->as_instance_klass();
1668           // See if we can become precise: no subklasses and no interface
1669           if (!ik->is_interface() && !ik->has_subklass()) {
1670             //assert(!UseExactTypes, "this code should be useless with exact types");
1671             // Add a dependence; if any subclass added we need to recompile
1672             if (!ik->is_final()) {
1673               phase->C->dependencies()->assert_leaf_type(ik);
1674             }
1675             // Return precise array klass
1676             return TypeKlassPtr::make(ak);
1677           }
1678         }
1679         return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
1680       } else {                  // Found a type-array?
1681         //assert(!UseExactTypes, "this code should be useless with exact types");
1682         assert( ak->is_type_array_klass(), "" );
1683         return TypeKlassPtr::make(ak); // These are always precise
1684       }
1685     }
1686   }
1687 
1688   // Check for loading klass from an array klass
1689   const TypeKlassPtr *tkls = tp->isa_klassptr();
1690   if (tkls != NULL && !StressReflectiveCode) {
1691     ciKlass* klass = tkls->klass();
1692     if( !klass->is_loaded() )
1693       return _type;             // Bail out if not loaded
1694     if( klass->is_obj_array_klass() &&
1695         (uint)tkls->offset() == objArrayKlass::element_klass_offset_in_bytes() + sizeof(oopDesc)) {
1696       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
1697       // // Always returning precise element type is incorrect,
1698       // // e.g., element type could be object and array may contain strings
1699       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
1700 
1701       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
1702       // according to the element type's subclassing.
1703       return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
1704     }
1705     if( klass->is_instance_klass() && tkls->klass_is_exact() &&
1706         (uint)tkls->offset() == Klass::super_offset_in_bytes() + sizeof(oopDesc)) {
1707       ciKlass* sup = klass->as_instance_klass()->super();
1708       // The field is Klass::_super.  Return its (constant) value.
1709       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
1710       return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
1711     }
1712   }
1713 
1714   // Bailout case
1715   return LoadNode::Value(phase);
1716 }
1717 
1718 //------------------------------Identity---------------------------------------
1719 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
1720 // Also feed through the klass in Allocate(...klass...)._klass.
1721 Node* LoadKlassNode::Identity( PhaseTransform *phase ) {
1722   Node* x = LoadNode::Identity(phase);
1723   if (x != this)  return x;
1724 
1725   // Take apart the address into an oop and and offset.
1726   // Return 'this' if we cannot.
1727   Node*    adr    = in(MemNode::Address);
1728   intptr_t offset = 0;
1729   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
1730   if (base == NULL)     return this;
1731   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
1732   if (toop == NULL)     return this;
1733 
1734   // We can fetch the klass directly through an AllocateNode.
1735   // This works even if the klass is not constant (clone or newArray).
1736   if (offset == oopDesc::klass_offset_in_bytes()) {
1737     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
1738     if (allocated_klass != NULL) {
1739       return allocated_klass;
1740     }
1741   }
1742 
1743   // Simplify k.java_mirror.as_klass to plain k, where k is a klassOop.
1744   // Simplify ak.component_mirror.array_klass to plain ak, ak an arrayKlass.
1745   // See inline_native_Class_query for occurrences of these patterns.
1746   // Java Example:  x.getClass().isAssignableFrom(y)
1747   // Java Example:  Array.newInstance(x.getClass().getComponentType(), n)
1748   //
1749   // This improves reflective code, often making the Class
1750   // mirror go completely dead.  (Current exception:  Class
1751   // mirrors may appear in debug info, but we could clean them out by
1752   // introducing a new debug info operator for klassOop.java_mirror).
1753   if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
1754       && (offset == java_lang_Class::klass_offset_in_bytes() ||
1755           offset == java_lang_Class::array_klass_offset_in_bytes())) {
1756     // We are loading a special hidden field from a Class mirror,
1757     // the field which points to its Klass or arrayKlass metaobject.
1758     if (base->is_Load()) {
1759       Node* adr2 = base->in(MemNode::Address);
1760       const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
1761       if (tkls != NULL && !tkls->empty()
1762           && (tkls->klass()->is_instance_klass() ||
1763               tkls->klass()->is_array_klass())
1764           && adr2->is_AddP()
1765           ) {
1766         int mirror_field = Klass::java_mirror_offset_in_bytes();
1767         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
1768           mirror_field = in_bytes(arrayKlass::component_mirror_offset());
1769         }
1770         if (tkls->offset() == mirror_field + (int)sizeof(oopDesc)) {
1771           return adr2->in(AddPNode::Base);
1772         }
1773       }
1774     }
1775   }
1776 
1777   return this;
1778 }
1779 
1780 //------------------------------Value-----------------------------------------
1781 const Type *LoadRangeNode::Value( PhaseTransform *phase ) const {
1782   // Either input is TOP ==> the result is TOP
1783   const Type *t1 = phase->type( in(MemNode::Memory) );
1784   if( t1 == Type::TOP ) return Type::TOP;
1785   Node *adr = in(MemNode::Address);
1786   const Type *t2 = phase->type( adr );
1787   if( t2 == Type::TOP ) return Type::TOP;
1788   const TypePtr *tp = t2->is_ptr();
1789   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
1790   const TypeAryPtr *tap = tp->isa_aryptr();
1791   if( !tap ) return _type;
1792   return tap->size();
1793 }
1794 
1795 //------------------------------Identity---------------------------------------
1796 // Feed through the length in AllocateArray(...length...)._length.
1797 Node* LoadRangeNode::Identity( PhaseTransform *phase ) {
1798   Node* x = LoadINode::Identity(phase);
1799   if (x != this)  return x;
1800 
1801   // Take apart the address into an oop and and offset.
1802   // Return 'this' if we cannot.
1803   Node*    adr    = in(MemNode::Address);
1804   intptr_t offset = 0;
1805   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
1806   if (base == NULL)     return this;
1807   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
1808   if (tary == NULL)     return this;
1809 
1810   // We can fetch the length directly through an AllocateArrayNode.
1811   // This works even if the length is not constant (clone or newArray).
1812   if (offset == arrayOopDesc::length_offset_in_bytes()) {
1813     Node* allocated_length = AllocateArrayNode::Ideal_length(base, phase);
1814     if (allocated_length != NULL) {
1815       return allocated_length;
1816     }
1817   }
1818 
1819   return this;
1820 
1821 }
1822 //=============================================================================
1823 //---------------------------StoreNode::make-----------------------------------
1824 // Polymorphic factory method:
1825 StoreNode* StoreNode::make( PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt ) {
1826   Compile* C = gvn.C;
1827 
1828   switch (bt) {
1829   case T_BOOLEAN:
1830   case T_BYTE:    return new (C, 4) StoreBNode(ctl, mem, adr, adr_type, val);
1831   case T_INT:     return new (C, 4) StoreINode(ctl, mem, adr, adr_type, val);
1832   case T_CHAR:
1833   case T_SHORT:   return new (C, 4) StoreCNode(ctl, mem, adr, adr_type, val);
1834   case T_LONG:    return new (C, 4) StoreLNode(ctl, mem, adr, adr_type, val);
1835   case T_FLOAT:   return new (C, 4) StoreFNode(ctl, mem, adr, adr_type, val);
1836   case T_DOUBLE:  return new (C, 4) StoreDNode(ctl, mem, adr, adr_type, val);
1837   case T_ADDRESS:
1838   case T_OBJECT:
1839 #ifdef _LP64
1840     if (adr->bottom_type()->is_narrow() ||
1841         (UseCompressedOops && val->bottom_type()->isa_klassptr() &&
1842          adr->bottom_type()->isa_rawptr())) {
1843       const TypePtr* type = val->bottom_type()->is_ptr();
1844       Node* cp;
1845       if (type->isa_oopptr()) {
1846         const TypeNarrowOop* etype = type->is_oopptr()->make_narrowoop();
1847         cp = gvn.transform(new (C, 2) EncodePNode(val, etype));
1848       } else if (type == TypePtr::NULL_PTR) {
1849         cp = gvn.transform(new (C, 1) ConNNode(TypeNarrowOop::NULL_PTR));
1850       } else {
1851         ShouldNotReachHere();
1852       }
1853       return new (C, 4) StoreNNode(ctl, mem, adr, adr_type, cp);
1854     } else
1855 #endif
1856       {
1857         return new (C, 4) StorePNode(ctl, mem, adr, adr_type, val);
1858       }
1859   }
1860   ShouldNotReachHere();
1861   return (StoreNode*)NULL;
1862 }
1863 
1864 StoreLNode* StoreLNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val) {
1865   bool require_atomic = true;
1866   return new (C, 4) StoreLNode(ctl, mem, adr, adr_type, val, require_atomic);
1867 }
1868 
1869 
1870 //--------------------------bottom_type----------------------------------------
1871 const Type *StoreNode::bottom_type() const {
1872   return Type::MEMORY;
1873 }
1874 
1875 //------------------------------hash-------------------------------------------
1876 uint StoreNode::hash() const {
1877   // unroll addition of interesting fields
1878   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
1879 
1880   // Since they are not commoned, do not hash them:
1881   return NO_HASH;
1882 }
1883 
1884 //------------------------------Ideal------------------------------------------
1885 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
1886 // When a store immediately follows a relevant allocation/initialization,
1887 // try to capture it into the initialization, or hoist it above.
1888 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1889   Node* p = MemNode::Ideal_common(phase, can_reshape);
1890   if (p)  return (p == NodeSentinel) ? NULL : p;
1891 
1892   Node* mem     = in(MemNode::Memory);
1893   Node* address = in(MemNode::Address);
1894 
1895   // Back-to-back stores to same address?  Fold em up.
1896   // Generally unsafe if I have intervening uses...
1897   if (mem->is_Store() && phase->eqv_uncast(mem->in(MemNode::Address), address)) {
1898     // Looking at a dead closed cycle of memory?
1899     assert(mem != mem->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
1900 
1901     assert(Opcode() == mem->Opcode() ||
1902            phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw,
1903            "no mismatched stores, except on raw memory");
1904 
1905     if (mem->outcnt() == 1 &&           // check for intervening uses
1906         mem->as_Store()->memory_size() <= this->memory_size()) {
1907       // If anybody other than 'this' uses 'mem', we cannot fold 'mem' away.
1908       // For example, 'mem' might be the final state at a conditional return.
1909       // Or, 'mem' might be used by some node which is live at the same time
1910       // 'this' is live, which might be unschedulable.  So, require exactly
1911       // ONE user, the 'this' store, until such time as we clone 'mem' for
1912       // each of 'mem's uses (thus making the exactly-1-user-rule hold true).
1913       if (can_reshape) {  // (%%% is this an anachronism?)
1914         set_req_X(MemNode::Memory, mem->in(MemNode::Memory),
1915                   phase->is_IterGVN());
1916       } else {
1917         // It's OK to do this in the parser, since DU info is always accurate,
1918         // and the parser always refers to nodes via SafePointNode maps.
1919         set_req(MemNode::Memory, mem->in(MemNode::Memory));
1920       }
1921       return this;
1922     }
1923   }
1924 
1925   // Capture an unaliased, unconditional, simple store into an initializer.
1926   // Or, if it is independent of the allocation, hoist it above the allocation.
1927   if (ReduceFieldZeroing && /*can_reshape &&*/
1928       mem->is_Proj() && mem->in(0)->is_Initialize()) {
1929     InitializeNode* init = mem->in(0)->as_Initialize();
1930     intptr_t offset = init->can_capture_store(this, phase);
1931     if (offset > 0) {
1932       Node* moved = init->capture_store(this, offset, phase);
1933       // If the InitializeNode captured me, it made a raw copy of me,
1934       // and I need to disappear.
1935       if (moved != NULL) {
1936         // %%% hack to ensure that Ideal returns a new node:
1937         mem = MergeMemNode::make(phase->C, mem);
1938         return mem;             // fold me away
1939       }
1940     }
1941   }
1942 
1943   return NULL;                  // No further progress
1944 }
1945 
1946 //------------------------------Value-----------------------------------------
1947 const Type *StoreNode::Value( PhaseTransform *phase ) const {
1948   // Either input is TOP ==> the result is TOP
1949   const Type *t1 = phase->type( in(MemNode::Memory) );
1950   if( t1 == Type::TOP ) return Type::TOP;
1951   const Type *t2 = phase->type( in(MemNode::Address) );
1952   if( t2 == Type::TOP ) return Type::TOP;
1953   const Type *t3 = phase->type( in(MemNode::ValueIn) );
1954   if( t3 == Type::TOP ) return Type::TOP;
1955   return Type::MEMORY;
1956 }
1957 
1958 //------------------------------Identity---------------------------------------
1959 // Remove redundant stores:
1960 //   Store(m, p, Load(m, p)) changes to m.
1961 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
1962 Node *StoreNode::Identity( PhaseTransform *phase ) {
1963   Node* mem = in(MemNode::Memory);
1964   Node* adr = in(MemNode::Address);
1965   Node* val = in(MemNode::ValueIn);
1966 
1967   // Load then Store?  Then the Store is useless
1968   if (val->is_Load() &&
1969       phase->eqv_uncast( val->in(MemNode::Address), adr ) &&
1970       phase->eqv_uncast( val->in(MemNode::Memory ), mem ) &&
1971       val->as_Load()->store_Opcode() == Opcode()) {
1972     return mem;
1973   }
1974 
1975   // Two stores in a row of the same value?
1976   if (mem->is_Store() &&
1977       phase->eqv_uncast( mem->in(MemNode::Address), adr ) &&
1978       phase->eqv_uncast( mem->in(MemNode::ValueIn), val ) &&
1979       mem->Opcode() == Opcode()) {
1980     return mem;
1981   }
1982 
1983   // Store of zero anywhere into a freshly-allocated object?
1984   // Then the store is useless.
1985   // (It must already have been captured by the InitializeNode.)
1986   if (ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
1987     // a newly allocated object is already all-zeroes everywhere
1988     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
1989       return mem;
1990     }
1991 
1992     // the store may also apply to zero-bits in an earlier object
1993     Node* prev_mem = find_previous_store(phase);
1994     // Steps (a), (b):  Walk past independent stores to find an exact match.
1995     if (prev_mem != NULL) {
1996       Node* prev_val = can_see_stored_value(prev_mem, phase);
1997       if (prev_val != NULL && phase->eqv(prev_val, val)) {
1998         // prev_val and val might differ by a cast; it would be good
1999         // to keep the more informative of the two.
2000         return mem;
2001       }
2002     }
2003   }
2004 
2005   return this;
2006 }
2007 
2008 //------------------------------match_edge-------------------------------------
2009 // Do we Match on this edge index or not?  Match only memory & value
2010 uint StoreNode::match_edge(uint idx) const {
2011   return idx == MemNode::Address || idx == MemNode::ValueIn;
2012 }
2013 
2014 //------------------------------cmp--------------------------------------------
2015 // Do not common stores up together.  They generally have to be split
2016 // back up anyways, so do not bother.
2017 uint StoreNode::cmp( const Node &n ) const {
2018   return (&n == this);          // Always fail except on self
2019 }
2020 
2021 //------------------------------Ideal_masked_input-----------------------------
2022 // Check for a useless mask before a partial-word store
2023 // (StoreB ... (AndI valIn conIa) )
2024 // If (conIa & mask == mask) this simplifies to
2025 // (StoreB ... (valIn) )
2026 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
2027   Node *val = in(MemNode::ValueIn);
2028   if( val->Opcode() == Op_AndI ) {
2029     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2030     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
2031       set_req(MemNode::ValueIn, val->in(1));
2032       return this;
2033     }
2034   }
2035   return NULL;
2036 }
2037 
2038 
2039 //------------------------------Ideal_sign_extended_input----------------------
2040 // Check for useless sign-extension before a partial-word store
2041 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
2042 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
2043 // (StoreB ... (valIn) )
2044 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
2045   Node *val = in(MemNode::ValueIn);
2046   if( val->Opcode() == Op_RShiftI ) {
2047     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2048     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
2049       Node *shl = val->in(1);
2050       if( shl->Opcode() == Op_LShiftI ) {
2051         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
2052         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
2053           set_req(MemNode::ValueIn, shl->in(1));
2054           return this;
2055         }
2056       }
2057     }
2058   }
2059   return NULL;
2060 }
2061 
2062 //------------------------------value_never_loaded-----------------------------------
2063 // Determine whether there are any possible loads of the value stored.
2064 // For simplicity, we actually check if there are any loads from the
2065 // address stored to, not just for loads of the value stored by this node.
2066 //
2067 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
2068   Node *adr = in(Address);
2069   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
2070   if (adr_oop == NULL)
2071     return false;
2072   if (!adr_oop->is_instance_field())
2073     return false; // if not a distinct instance, there may be aliases of the address
2074   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
2075     Node *use = adr->fast_out(i);
2076     int opc = use->Opcode();
2077     if (use->is_Load() || use->is_LoadStore()) {
2078       return false;
2079     }
2080   }
2081   return true;
2082 }
2083 
2084 //=============================================================================
2085 //------------------------------Ideal------------------------------------------
2086 // If the store is from an AND mask that leaves the low bits untouched, then
2087 // we can skip the AND operation.  If the store is from a sign-extension
2088 // (a left shift, then right shift) we can skip both.
2089 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
2090   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
2091   if( progress != NULL ) return progress;
2092 
2093   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
2094   if( progress != NULL ) return progress;
2095 
2096   // Finally check the default case
2097   return StoreNode::Ideal(phase, can_reshape);
2098 }
2099 
2100 //=============================================================================
2101 //------------------------------Ideal------------------------------------------
2102 // If the store is from an AND mask that leaves the low bits untouched, then
2103 // we can skip the AND operation
2104 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
2105   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
2106   if( progress != NULL ) return progress;
2107 
2108   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
2109   if( progress != NULL ) return progress;
2110 
2111   // Finally check the default case
2112   return StoreNode::Ideal(phase, can_reshape);
2113 }
2114 
2115 //=============================================================================
2116 //------------------------------Identity---------------------------------------
2117 Node *StoreCMNode::Identity( PhaseTransform *phase ) {
2118   // No need to card mark when storing a null ptr
2119   Node* my_store = in(MemNode::OopStore);
2120   if (my_store->is_Store()) {
2121     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
2122     if( t1 == TypePtr::NULL_PTR ) {
2123       return in(MemNode::Memory);
2124     }
2125   }
2126   return this;
2127 }
2128 
2129 //------------------------------Value-----------------------------------------
2130 const Type *StoreCMNode::Value( PhaseTransform *phase ) const {
2131   // Either input is TOP ==> the result is TOP
2132   const Type *t = phase->type( in(MemNode::Memory) );
2133   if( t == Type::TOP ) return Type::TOP;
2134   t = phase->type( in(MemNode::Address) );
2135   if( t == Type::TOP ) return Type::TOP;
2136   t = phase->type( in(MemNode::ValueIn) );
2137   if( t == Type::TOP ) return Type::TOP;
2138   // If extra input is TOP ==> the result is TOP
2139   t = phase->type( in(MemNode::OopStore) );
2140   if( t == Type::TOP ) return Type::TOP;
2141 
2142   return StoreNode::Value( phase );
2143 }
2144 
2145 
2146 //=============================================================================
2147 //----------------------------------SCMemProjNode------------------------------
2148 const Type * SCMemProjNode::Value( PhaseTransform *phase ) const
2149 {
2150   return bottom_type();
2151 }
2152 
2153 //=============================================================================
2154 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : Node(5) {
2155   init_req(MemNode::Control, c  );
2156   init_req(MemNode::Memory , mem);
2157   init_req(MemNode::Address, adr);
2158   init_req(MemNode::ValueIn, val);
2159   init_req(         ExpectedIn, ex );
2160   init_class_id(Class_LoadStore);
2161 
2162 }
2163 
2164 //=============================================================================
2165 //-------------------------------adr_type--------------------------------------
2166 // Do we Match on this edge index or not?  Do not match memory
2167 const TypePtr* ClearArrayNode::adr_type() const {
2168   Node *adr = in(3);
2169   return MemNode::calculate_adr_type(adr->bottom_type());
2170 }
2171 
2172 //------------------------------match_edge-------------------------------------
2173 // Do we Match on this edge index or not?  Do not match memory
2174 uint ClearArrayNode::match_edge(uint idx) const {
2175   return idx > 1;
2176 }
2177 
2178 //------------------------------Identity---------------------------------------
2179 // Clearing a zero length array does nothing
2180 Node *ClearArrayNode::Identity( PhaseTransform *phase ) {
2181   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
2182 }
2183 
2184 //------------------------------Idealize---------------------------------------
2185 // Clearing a short array is faster with stores
2186 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape){
2187   const int unit = BytesPerLong;
2188   const TypeX* t = phase->type(in(2))->isa_intptr_t();
2189   if (!t)  return NULL;
2190   if (!t->is_con())  return NULL;
2191   intptr_t raw_count = t->get_con();
2192   intptr_t size = raw_count;
2193   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
2194   // Clearing nothing uses the Identity call.
2195   // Negative clears are possible on dead ClearArrays
2196   // (see jck test stmt114.stmt11402.val).
2197   if (size <= 0 || size % unit != 0)  return NULL;
2198   intptr_t count = size / unit;
2199   // Length too long; use fast hardware clear
2200   if (size > Matcher::init_array_short_size)  return NULL;
2201   Node *mem = in(1);
2202   if( phase->type(mem)==Type::TOP ) return NULL;
2203   Node *adr = in(3);
2204   const Type* at = phase->type(adr);
2205   if( at==Type::TOP ) return NULL;
2206   const TypePtr* atp = at->isa_ptr();
2207   // adjust atp to be the correct array element address type
2208   if (atp == NULL)  atp = TypePtr::BOTTOM;
2209   else              atp = atp->add_offset(Type::OffsetBot);
2210   // Get base for derived pointer purposes
2211   if( adr->Opcode() != Op_AddP ) Unimplemented();
2212   Node *base = adr->in(1);
2213 
2214   Node *zero = phase->makecon(TypeLong::ZERO);
2215   Node *off  = phase->MakeConX(BytesPerLong);
2216   mem = new (phase->C, 4) StoreLNode(in(0),mem,adr,atp,zero);
2217   count--;
2218   while( count-- ) {
2219     mem = phase->transform(mem);
2220     adr = phase->transform(new (phase->C, 4) AddPNode(base,adr,off));
2221     mem = new (phase->C, 4) StoreLNode(in(0),mem,adr,atp,zero);
2222   }
2223   return mem;
2224 }
2225 
2226 //----------------------------clear_memory-------------------------------------
2227 // Generate code to initialize object storage to zero.
2228 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2229                                    intptr_t start_offset,
2230                                    Node* end_offset,
2231                                    PhaseGVN* phase) {
2232   Compile* C = phase->C;
2233   intptr_t offset = start_offset;
2234 
2235   int unit = BytesPerLong;
2236   if ((offset % unit) != 0) {
2237     Node* adr = new (C, 4) AddPNode(dest, dest, phase->MakeConX(offset));
2238     adr = phase->transform(adr);
2239     const TypePtr* atp = TypeRawPtr::BOTTOM;
2240     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT);
2241     mem = phase->transform(mem);
2242     offset += BytesPerInt;
2243   }
2244   assert((offset % unit) == 0, "");
2245 
2246   // Initialize the remaining stuff, if any, with a ClearArray.
2247   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
2248 }
2249 
2250 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2251                                    Node* start_offset,
2252                                    Node* end_offset,
2253                                    PhaseGVN* phase) {
2254   if (start_offset == end_offset) {
2255     // nothing to do
2256     return mem;
2257   }
2258 
2259   Compile* C = phase->C;
2260   int unit = BytesPerLong;
2261   Node* zbase = start_offset;
2262   Node* zend  = end_offset;
2263 
2264   // Scale to the unit required by the CPU:
2265   if (!Matcher::init_array_count_is_in_bytes) {
2266     Node* shift = phase->intcon(exact_log2(unit));
2267     zbase = phase->transform( new(C,3) URShiftXNode(zbase, shift) );
2268     zend  = phase->transform( new(C,3) URShiftXNode(zend,  shift) );
2269   }
2270 
2271   Node* zsize = phase->transform( new(C,3) SubXNode(zend, zbase) );
2272   Node* zinit = phase->zerocon((unit == BytesPerLong) ? T_LONG : T_INT);
2273 
2274   // Bulk clear double-words
2275   Node* adr = phase->transform( new(C,4) AddPNode(dest, dest, start_offset) );
2276   mem = new (C, 4) ClearArrayNode(ctl, mem, zsize, adr);
2277   return phase->transform(mem);
2278 }
2279 
2280 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2281                                    intptr_t start_offset,
2282                                    intptr_t end_offset,
2283                                    PhaseGVN* phase) {
2284   if (start_offset == end_offset) {
2285     // nothing to do
2286     return mem;
2287   }
2288 
2289   Compile* C = phase->C;
2290   assert((end_offset % BytesPerInt) == 0, "odd end offset");
2291   intptr_t done_offset = end_offset;
2292   if ((done_offset % BytesPerLong) != 0) {
2293     done_offset -= BytesPerInt;
2294   }
2295   if (done_offset > start_offset) {
2296     mem = clear_memory(ctl, mem, dest,
2297                        start_offset, phase->MakeConX(done_offset), phase);
2298   }
2299   if (done_offset < end_offset) { // emit the final 32-bit store
2300     Node* adr = new (C, 4) AddPNode(dest, dest, phase->MakeConX(done_offset));
2301     adr = phase->transform(adr);
2302     const TypePtr* atp = TypeRawPtr::BOTTOM;
2303     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT);
2304     mem = phase->transform(mem);
2305     done_offset += BytesPerInt;
2306   }
2307   assert(done_offset == end_offset, "");
2308   return mem;
2309 }
2310 
2311 //=============================================================================
2312 // Do we match on this edge? No memory edges
2313 uint StrCompNode::match_edge(uint idx) const {
2314   return idx == 5 || idx == 6;
2315 }
2316 
2317 //------------------------------Ideal------------------------------------------
2318 // Return a node which is more "ideal" than the current node.  Strip out
2319 // control copies
2320 Node *StrCompNode::Ideal(PhaseGVN *phase, bool can_reshape){
2321   return remove_dead_region(phase, can_reshape) ? this : NULL;
2322 }
2323 
2324 
2325 //=============================================================================
2326 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
2327   : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
2328     _adr_type(C->get_adr_type(alias_idx))
2329 {
2330   init_class_id(Class_MemBar);
2331   Node* top = C->top();
2332   init_req(TypeFunc::I_O,top);
2333   init_req(TypeFunc::FramePtr,top);
2334   init_req(TypeFunc::ReturnAdr,top);
2335   if (precedent != NULL)
2336     init_req(TypeFunc::Parms, precedent);
2337 }
2338 
2339 //------------------------------cmp--------------------------------------------
2340 uint MemBarNode::hash() const { return NO_HASH; }
2341 uint MemBarNode::cmp( const Node &n ) const {
2342   return (&n == this);          // Always fail except on self
2343 }
2344 
2345 //------------------------------make-------------------------------------------
2346 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
2347   int len = Precedent + (pn == NULL? 0: 1);
2348   switch (opcode) {
2349   case Op_MemBarAcquire:   return new(C, len) MemBarAcquireNode(C,  atp, pn);
2350   case Op_MemBarRelease:   return new(C, len) MemBarReleaseNode(C,  atp, pn);
2351   case Op_MemBarVolatile:  return new(C, len) MemBarVolatileNode(C, atp, pn);
2352   case Op_MemBarCPUOrder:  return new(C, len) MemBarCPUOrderNode(C, atp, pn);
2353   case Op_Initialize:      return new(C, len) InitializeNode(C,     atp, pn);
2354   default:                 ShouldNotReachHere(); return NULL;
2355   }
2356 }
2357 
2358 //------------------------------Ideal------------------------------------------
2359 // Return a node which is more "ideal" than the current node.  Strip out
2360 // control copies
2361 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2362   if (remove_dead_region(phase, can_reshape))  return this;
2363   return NULL;
2364 }
2365 
2366 //------------------------------Value------------------------------------------
2367 const Type *MemBarNode::Value( PhaseTransform *phase ) const {
2368   if( !in(0) ) return Type::TOP;
2369   if( phase->type(in(0)) == Type::TOP )
2370     return Type::TOP;
2371   return TypeTuple::MEMBAR;
2372 }
2373 
2374 //------------------------------match------------------------------------------
2375 // Construct projections for memory.
2376 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
2377   switch (proj->_con) {
2378   case TypeFunc::Control:
2379   case TypeFunc::Memory:
2380     return new (m->C, 1) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
2381   }
2382   ShouldNotReachHere();
2383   return NULL;
2384 }
2385 
2386 //===========================InitializeNode====================================
2387 // SUMMARY:
2388 // This node acts as a memory barrier on raw memory, after some raw stores.
2389 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
2390 // The Initialize can 'capture' suitably constrained stores as raw inits.
2391 // It can coalesce related raw stores into larger units (called 'tiles').
2392 // It can avoid zeroing new storage for memory units which have raw inits.
2393 // At macro-expansion, it is marked 'complete', and does not optimize further.
2394 //
2395 // EXAMPLE:
2396 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
2397 //   ctl = incoming control; mem* = incoming memory
2398 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
2399 // First allocate uninitialized memory and fill in the header:
2400 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
2401 //   ctl := alloc.Control; mem* := alloc.Memory*
2402 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
2403 // Then initialize to zero the non-header parts of the raw memory block:
2404 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
2405 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
2406 // After the initialize node executes, the object is ready for service:
2407 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
2408 // Suppose its body is immediately initialized as {1,2}:
2409 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
2410 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
2411 //   mem.SLICE(#short[*]) := store2
2412 //
2413 // DETAILS:
2414 // An InitializeNode collects and isolates object initialization after
2415 // an AllocateNode and before the next possible safepoint.  As a
2416 // memory barrier (MemBarNode), it keeps critical stores from drifting
2417 // down past any safepoint or any publication of the allocation.
2418 // Before this barrier, a newly-allocated object may have uninitialized bits.
2419 // After this barrier, it may be treated as a real oop, and GC is allowed.
2420 //
2421 // The semantics of the InitializeNode include an implicit zeroing of
2422 // the new object from object header to the end of the object.
2423 // (The object header and end are determined by the AllocateNode.)
2424 //
2425 // Certain stores may be added as direct inputs to the InitializeNode.
2426 // These stores must update raw memory, and they must be to addresses
2427 // derived from the raw address produced by AllocateNode, and with
2428 // a constant offset.  They must be ordered by increasing offset.
2429 // The first one is at in(RawStores), the last at in(req()-1).
2430 // Unlike most memory operations, they are not linked in a chain,
2431 // but are displayed in parallel as users of the rawmem output of
2432 // the allocation.
2433 //
2434 // (See comments in InitializeNode::capture_store, which continue
2435 // the example given above.)
2436 //
2437 // When the associated Allocate is macro-expanded, the InitializeNode
2438 // may be rewritten to optimize collected stores.  A ClearArrayNode
2439 // may also be created at that point to represent any required zeroing.
2440 // The InitializeNode is then marked 'complete', prohibiting further
2441 // capturing of nearby memory operations.
2442 //
2443 // During macro-expansion, all captured initializations which store
2444 // constant values of 32 bits or smaller are coalesced (if advantagous)
2445 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
2446 // initialized in fewer memory operations.  Memory words which are
2447 // covered by neither tiles nor non-constant stores are pre-zeroed
2448 // by explicit stores of zero.  (The code shape happens to do all
2449 // zeroing first, then all other stores, with both sequences occurring
2450 // in order of ascending offsets.)
2451 //
2452 // Alternatively, code may be inserted between an AllocateNode and its
2453 // InitializeNode, to perform arbitrary initialization of the new object.
2454 // E.g., the object copying intrinsics insert complex data transfers here.
2455 // The initialization must then be marked as 'complete' disable the
2456 // built-in zeroing semantics and the collection of initializing stores.
2457 //
2458 // While an InitializeNode is incomplete, reads from the memory state
2459 // produced by it are optimizable if they match the control edge and
2460 // new oop address associated with the allocation/initialization.
2461 // They return a stored value (if the offset matches) or else zero.
2462 // A write to the memory state, if it matches control and address,
2463 // and if it is to a constant offset, may be 'captured' by the
2464 // InitializeNode.  It is cloned as a raw memory operation and rewired
2465 // inside the initialization, to the raw oop produced by the allocation.
2466 // Operations on addresses which are provably distinct (e.g., to
2467 // other AllocateNodes) are allowed to bypass the initialization.
2468 //
2469 // The effect of all this is to consolidate object initialization
2470 // (both arrays and non-arrays, both piecewise and bulk) into a
2471 // single location, where it can be optimized as a unit.
2472 //
2473 // Only stores with an offset less than TrackedInitializationLimit words
2474 // will be considered for capture by an InitializeNode.  This puts a
2475 // reasonable limit on the complexity of optimized initializations.
2476 
2477 //---------------------------InitializeNode------------------------------------
2478 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
2479   : _is_complete(false),
2480     MemBarNode(C, adr_type, rawoop)
2481 {
2482   init_class_id(Class_Initialize);
2483 
2484   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
2485   assert(in(RawAddress) == rawoop, "proper init");
2486   // Note:  allocation() can be NULL, for secondary initialization barriers
2487 }
2488 
2489 // Since this node is not matched, it will be processed by the
2490 // register allocator.  Declare that there are no constraints
2491 // on the allocation of the RawAddress edge.
2492 const RegMask &InitializeNode::in_RegMask(uint idx) const {
2493   // This edge should be set to top, by the set_complete.  But be conservative.
2494   if (idx == InitializeNode::RawAddress)
2495     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
2496   return RegMask::Empty;
2497 }
2498 
2499 Node* InitializeNode::memory(uint alias_idx) {
2500   Node* mem = in(Memory);
2501   if (mem->is_MergeMem()) {
2502     return mem->as_MergeMem()->memory_at(alias_idx);
2503   } else {
2504     // incoming raw memory is not split
2505     return mem;
2506   }
2507 }
2508 
2509 bool InitializeNode::is_non_zero() {
2510   if (is_complete())  return false;
2511   remove_extra_zeroes();
2512   return (req() > RawStores);
2513 }
2514 
2515 void InitializeNode::set_complete(PhaseGVN* phase) {
2516   assert(!is_complete(), "caller responsibility");
2517   _is_complete = true;
2518 
2519   // After this node is complete, it contains a bunch of
2520   // raw-memory initializations.  There is no need for
2521   // it to have anything to do with non-raw memory effects.
2522   // Therefore, tell all non-raw users to re-optimize themselves,
2523   // after skipping the memory effects of this initialization.
2524   PhaseIterGVN* igvn = phase->is_IterGVN();
2525   if (igvn)  igvn->add_users_to_worklist(this);
2526 }
2527 
2528 // convenience function
2529 // return false if the init contains any stores already
2530 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
2531   InitializeNode* init = initialization();
2532   if (init == NULL || init->is_complete())  return false;
2533   init->remove_extra_zeroes();
2534   // for now, if this allocation has already collected any inits, bail:
2535   if (init->is_non_zero())  return false;
2536   init->set_complete(phase);
2537   return true;
2538 }
2539 
2540 void InitializeNode::remove_extra_zeroes() {
2541   if (req() == RawStores)  return;
2542   Node* zmem = zero_memory();
2543   uint fill = RawStores;
2544   for (uint i = fill; i < req(); i++) {
2545     Node* n = in(i);
2546     if (n->is_top() || n == zmem)  continue;  // skip
2547     if (fill < i)  set_req(fill, n);          // compact
2548     ++fill;
2549   }
2550   // delete any empty spaces created:
2551   while (fill < req()) {
2552     del_req(fill);
2553   }
2554 }
2555 
2556 // Helper for remembering which stores go with which offsets.
2557 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
2558   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
2559   intptr_t offset = -1;
2560   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
2561                                                phase, offset);
2562   if (base == NULL)     return -1;  // something is dead,
2563   if (offset < 0)       return -1;  //        dead, dead
2564   return offset;
2565 }
2566 
2567 // Helper for proving that an initialization expression is
2568 // "simple enough" to be folded into an object initialization.
2569 // Attempts to prove that a store's initial value 'n' can be captured
2570 // within the initialization without creating a vicious cycle, such as:
2571 //     { Foo p = new Foo(); p.next = p; }
2572 // True for constants and parameters and small combinations thereof.
2573 bool InitializeNode::detect_init_independence(Node* n,
2574                                               bool st_is_pinned,
2575                                               int& count) {
2576   if (n == NULL)      return true;   // (can this really happen?)
2577   if (n->is_Proj())   n = n->in(0);
2578   if (n == this)      return false;  // found a cycle
2579   if (n->is_Con())    return true;
2580   if (n->is_Start())  return true;   // params, etc., are OK
2581   if (n->is_Root())   return true;   // even better
2582 
2583   Node* ctl = n->in(0);
2584   if (ctl != NULL && !ctl->is_top()) {
2585     if (ctl->is_Proj())  ctl = ctl->in(0);
2586     if (ctl == this)  return false;
2587 
2588     // If we already know that the enclosing memory op is pinned right after
2589     // the init, then any control flow that the store has picked up
2590     // must have preceded the init, or else be equal to the init.
2591     // Even after loop optimizations (which might change control edges)
2592     // a store is never pinned *before* the availability of its inputs.
2593     if (!MemNode::all_controls_dominate(n, this))
2594       return false;                  // failed to prove a good control
2595 
2596   }
2597 
2598   // Check data edges for possible dependencies on 'this'.
2599   if ((count += 1) > 20)  return false;  // complexity limit
2600   for (uint i = 1; i < n->req(); i++) {
2601     Node* m = n->in(i);
2602     if (m == NULL || m == n || m->is_top())  continue;
2603     uint first_i = n->find_edge(m);
2604     if (i != first_i)  continue;  // process duplicate edge just once
2605     if (!detect_init_independence(m, st_is_pinned, count)) {
2606       return false;
2607     }
2608   }
2609 
2610   return true;
2611 }
2612 
2613 // Here are all the checks a Store must pass before it can be moved into
2614 // an initialization.  Returns zero if a check fails.
2615 // On success, returns the (constant) offset to which the store applies,
2616 // within the initialized memory.
2617 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase) {
2618   const int FAIL = 0;
2619   if (st->req() != MemNode::ValueIn + 1)
2620     return FAIL;                // an inscrutable StoreNode (card mark?)
2621   Node* ctl = st->in(MemNode::Control);
2622   if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
2623     return FAIL;                // must be unconditional after the initialization
2624   Node* mem = st->in(MemNode::Memory);
2625   if (!(mem->is_Proj() && mem->in(0) == this))
2626     return FAIL;                // must not be preceded by other stores
2627   Node* adr = st->in(MemNode::Address);
2628   intptr_t offset;
2629   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
2630   if (alloc == NULL)
2631     return FAIL;                // inscrutable address
2632   if (alloc != allocation())
2633     return FAIL;                // wrong allocation!  (store needs to float up)
2634   Node* val = st->in(MemNode::ValueIn);
2635   int complexity_count = 0;
2636   if (!detect_init_independence(val, true, complexity_count))
2637     return FAIL;                // stored value must be 'simple enough'
2638 
2639   return offset;                // success
2640 }
2641 
2642 // Find the captured store in(i) which corresponds to the range
2643 // [start..start+size) in the initialized object.
2644 // If there is one, return its index i.  If there isn't, return the
2645 // negative of the index where it should be inserted.
2646 // Return 0 if the queried range overlaps an initialization boundary
2647 // or if dead code is encountered.
2648 // If size_in_bytes is zero, do not bother with overlap checks.
2649 int InitializeNode::captured_store_insertion_point(intptr_t start,
2650                                                    int size_in_bytes,
2651                                                    PhaseTransform* phase) {
2652   const int FAIL = 0, MAX_STORE = BytesPerLong;
2653 
2654   if (is_complete())
2655     return FAIL;                // arraycopy got here first; punt
2656 
2657   assert(allocation() != NULL, "must be present");
2658 
2659   // no negatives, no header fields:
2660   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
2661 
2662   // after a certain size, we bail out on tracking all the stores:
2663   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
2664   if (start >= ti_limit)  return FAIL;
2665 
2666   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
2667     if (i >= limit)  return -(int)i; // not found; here is where to put it
2668 
2669     Node*    st     = in(i);
2670     intptr_t st_off = get_store_offset(st, phase);
2671     if (st_off < 0) {
2672       if (st != zero_memory()) {
2673         return FAIL;            // bail out if there is dead garbage
2674       }
2675     } else if (st_off > start) {
2676       // ...we are done, since stores are ordered
2677       if (st_off < start + size_in_bytes) {
2678         return FAIL;            // the next store overlaps
2679       }
2680       return -(int)i;           // not found; here is where to put it
2681     } else if (st_off < start) {
2682       if (size_in_bytes != 0 &&
2683           start < st_off + MAX_STORE &&
2684           start < st_off + st->as_Store()->memory_size()) {
2685         return FAIL;            // the previous store overlaps
2686       }
2687     } else {
2688       if (size_in_bytes != 0 &&
2689           st->as_Store()->memory_size() != size_in_bytes) {
2690         return FAIL;            // mismatched store size
2691       }
2692       return i;
2693     }
2694 
2695     ++i;
2696   }
2697 }
2698 
2699 // Look for a captured store which initializes at the offset 'start'
2700 // with the given size.  If there is no such store, and no other
2701 // initialization interferes, then return zero_memory (the memory
2702 // projection of the AllocateNode).
2703 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
2704                                           PhaseTransform* phase) {
2705   assert(stores_are_sane(phase), "");
2706   int i = captured_store_insertion_point(start, size_in_bytes, phase);
2707   if (i == 0) {
2708     return NULL;                // something is dead
2709   } else if (i < 0) {
2710     return zero_memory();       // just primordial zero bits here
2711   } else {
2712     Node* st = in(i);           // here is the store at this position
2713     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
2714     return st;
2715   }
2716 }
2717 
2718 // Create, as a raw pointer, an address within my new object at 'offset'.
2719 Node* InitializeNode::make_raw_address(intptr_t offset,
2720                                        PhaseTransform* phase) {
2721   Node* addr = in(RawAddress);
2722   if (offset != 0) {
2723     Compile* C = phase->C;
2724     addr = phase->transform( new (C, 4) AddPNode(C->top(), addr,
2725                                                  phase->MakeConX(offset)) );
2726   }
2727   return addr;
2728 }
2729 
2730 // Clone the given store, converting it into a raw store
2731 // initializing a field or element of my new object.
2732 // Caller is responsible for retiring the original store,
2733 // with subsume_node or the like.
2734 //
2735 // From the example above InitializeNode::InitializeNode,
2736 // here are the old stores to be captured:
2737 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
2738 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
2739 //
2740 // Here is the changed code; note the extra edges on init:
2741 //   alloc = (Allocate ...)
2742 //   rawoop = alloc.RawAddress
2743 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
2744 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
2745 //   init = (Initialize alloc.Control alloc.Memory rawoop
2746 //                      rawstore1 rawstore2)
2747 //
2748 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
2749                                     PhaseTransform* phase) {
2750   assert(stores_are_sane(phase), "");
2751 
2752   if (start < 0)  return NULL;
2753   assert(can_capture_store(st, phase) == start, "sanity");
2754 
2755   Compile* C = phase->C;
2756   int size_in_bytes = st->memory_size();
2757   int i = captured_store_insertion_point(start, size_in_bytes, phase);
2758   if (i == 0)  return NULL;     // bail out
2759   Node* prev_mem = NULL;        // raw memory for the captured store
2760   if (i > 0) {
2761     prev_mem = in(i);           // there is a pre-existing store under this one
2762     set_req(i, C->top());       // temporarily disconnect it
2763     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
2764   } else {
2765     i = -i;                     // no pre-existing store
2766     prev_mem = zero_memory();   // a slice of the newly allocated object
2767     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
2768       set_req(--i, C->top());   // reuse this edge; it has been folded away
2769     else
2770       ins_req(i, C->top());     // build a new edge
2771   }
2772   Node* new_st = st->clone();
2773   new_st->set_req(MemNode::Control, in(Control));
2774   new_st->set_req(MemNode::Memory,  prev_mem);
2775   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
2776   new_st = phase->transform(new_st);
2777 
2778   // At this point, new_st might have swallowed a pre-existing store
2779   // at the same offset, or perhaps new_st might have disappeared,
2780   // if it redundantly stored the same value (or zero to fresh memory).
2781 
2782   // In any case, wire it in:
2783   set_req(i, new_st);
2784 
2785   // The caller may now kill the old guy.
2786   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
2787   assert(check_st == new_st || check_st == NULL, "must be findable");
2788   assert(!is_complete(), "");
2789   return new_st;
2790 }
2791 
2792 static bool store_constant(jlong* tiles, int num_tiles,
2793                            intptr_t st_off, int st_size,
2794                            jlong con) {
2795   if ((st_off & (st_size-1)) != 0)
2796     return false;               // strange store offset (assume size==2**N)
2797   address addr = (address)tiles + st_off;
2798   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
2799   switch (st_size) {
2800   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
2801   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
2802   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
2803   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
2804   default: return false;        // strange store size (detect size!=2**N here)
2805   }
2806   return true;                  // return success to caller
2807 }
2808 
2809 // Coalesce subword constants into int constants and possibly
2810 // into long constants.  The goal, if the CPU permits,
2811 // is to initialize the object with a small number of 64-bit tiles.
2812 // Also, convert floating-point constants to bit patterns.
2813 // Non-constants are not relevant to this pass.
2814 //
2815 // In terms of the running example on InitializeNode::InitializeNode
2816 // and InitializeNode::capture_store, here is the transformation
2817 // of rawstore1 and rawstore2 into rawstore12:
2818 //   alloc = (Allocate ...)
2819 //   rawoop = alloc.RawAddress
2820 //   tile12 = 0x00010002
2821 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
2822 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
2823 //
2824 void
2825 InitializeNode::coalesce_subword_stores(intptr_t header_size,
2826                                         Node* size_in_bytes,
2827                                         PhaseGVN* phase) {
2828   Compile* C = phase->C;
2829 
2830   assert(stores_are_sane(phase), "");
2831   // Note:  After this pass, they are not completely sane,
2832   // since there may be some overlaps.
2833 
2834   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
2835 
2836   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
2837   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
2838   size_limit = MIN2(size_limit, ti_limit);
2839   size_limit = align_size_up(size_limit, BytesPerLong);
2840   int num_tiles = size_limit / BytesPerLong;
2841 
2842   // allocate space for the tile map:
2843   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
2844   jlong  tiles_buf[small_len];
2845   Node*  nodes_buf[small_len];
2846   jlong  inits_buf[small_len];
2847   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
2848                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
2849   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
2850                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
2851   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
2852                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
2853   // tiles: exact bitwise model of all primitive constants
2854   // nodes: last constant-storing node subsumed into the tiles model
2855   // inits: which bytes (in each tile) are touched by any initializations
2856 
2857   //// Pass A: Fill in the tile model with any relevant stores.
2858 
2859   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
2860   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
2861   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
2862   Node* zmem = zero_memory(); // initially zero memory state
2863   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
2864     Node* st = in(i);
2865     intptr_t st_off = get_store_offset(st, phase);
2866 
2867     // Figure out the store's offset and constant value:
2868     if (st_off < header_size)             continue; //skip (ignore header)
2869     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
2870     int st_size = st->as_Store()->memory_size();
2871     if (st_off + st_size > size_limit)    break;
2872 
2873     // Record which bytes are touched, whether by constant or not.
2874     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
2875       continue;                 // skip (strange store size)
2876 
2877     const Type* val = phase->type(st->in(MemNode::ValueIn));
2878     if (!val->singleton())                continue; //skip (non-con store)
2879     BasicType type = val->basic_type();
2880 
2881     jlong con = 0;
2882     switch (type) {
2883     case T_INT:    con = val->is_int()->get_con();  break;
2884     case T_LONG:   con = val->is_long()->get_con(); break;
2885     case T_FLOAT:  con = jint_cast(val->getf());    break;
2886     case T_DOUBLE: con = jlong_cast(val->getd());   break;
2887     default:                              continue; //skip (odd store type)
2888     }
2889 
2890     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
2891         st->Opcode() == Op_StoreL) {
2892       continue;                 // This StoreL is already optimal.
2893     }
2894 
2895     // Store down the constant.
2896     store_constant(tiles, num_tiles, st_off, st_size, con);
2897 
2898     intptr_t j = st_off >> LogBytesPerLong;
2899 
2900     if (type == T_INT && st_size == BytesPerInt
2901         && (st_off & BytesPerInt) == BytesPerInt) {
2902       jlong lcon = tiles[j];
2903       if (!Matcher::isSimpleConstant64(lcon) &&
2904           st->Opcode() == Op_StoreI) {
2905         // This StoreI is already optimal by itself.
2906         jint* intcon = (jint*) &tiles[j];
2907         intcon[1] = 0;  // undo the store_constant()
2908 
2909         // If the previous store is also optimal by itself, back up and
2910         // undo the action of the previous loop iteration... if we can.
2911         // But if we can't, just let the previous half take care of itself.
2912         st = nodes[j];
2913         st_off -= BytesPerInt;
2914         con = intcon[0];
2915         if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
2916           assert(st_off >= header_size, "still ignoring header");
2917           assert(get_store_offset(st, phase) == st_off, "must be");
2918           assert(in(i-1) == zmem, "must be");
2919           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
2920           assert(con == tcon->is_int()->get_con(), "must be");
2921           // Undo the effects of the previous loop trip, which swallowed st:
2922           intcon[0] = 0;        // undo store_constant()
2923           set_req(i-1, st);     // undo set_req(i, zmem)
2924           nodes[j] = NULL;      // undo nodes[j] = st
2925           --old_subword;        // undo ++old_subword
2926         }
2927         continue;               // This StoreI is already optimal.
2928       }
2929     }
2930 
2931     // This store is not needed.
2932     set_req(i, zmem);
2933     nodes[j] = st;              // record for the moment
2934     if (st_size < BytesPerLong) // something has changed
2935           ++old_subword;        // includes int/float, but who's counting...
2936     else  ++old_long;
2937   }
2938 
2939   if ((old_subword + old_long) == 0)
2940     return;                     // nothing more to do
2941 
2942   //// Pass B: Convert any non-zero tiles into optimal constant stores.
2943   // Be sure to insert them before overlapping non-constant stores.
2944   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
2945   for (int j = 0; j < num_tiles; j++) {
2946     jlong con  = tiles[j];
2947     jlong init = inits[j];
2948     if (con == 0)  continue;
2949     jint con0,  con1;           // split the constant, address-wise
2950     jint init0, init1;          // split the init map, address-wise
2951     { union { jlong con; jint intcon[2]; } u;
2952       u.con = con;
2953       con0  = u.intcon[0];
2954       con1  = u.intcon[1];
2955       u.con = init;
2956       init0 = u.intcon[0];
2957       init1 = u.intcon[1];
2958     }
2959 
2960     Node* old = nodes[j];
2961     assert(old != NULL, "need the prior store");
2962     intptr_t offset = (j * BytesPerLong);
2963 
2964     bool split = !Matcher::isSimpleConstant64(con);
2965 
2966     if (offset < header_size) {
2967       assert(offset + BytesPerInt >= header_size, "second int counts");
2968       assert(*(jint*)&tiles[j] == 0, "junk in header");
2969       split = true;             // only the second word counts
2970       // Example:  int a[] = { 42 ... }
2971     } else if (con0 == 0 && init0 == -1) {
2972       split = true;             // first word is covered by full inits
2973       // Example:  int a[] = { ... foo(), 42 ... }
2974     } else if (con1 == 0 && init1 == -1) {
2975       split = true;             // second word is covered by full inits
2976       // Example:  int a[] = { ... 42, foo() ... }
2977     }
2978 
2979     // Here's a case where init0 is neither 0 nor -1:
2980     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
2981     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
2982     // In this case the tile is not split; it is (jlong)42.
2983     // The big tile is stored down, and then the foo() value is inserted.
2984     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
2985 
2986     Node* ctl = old->in(MemNode::Control);
2987     Node* adr = make_raw_address(offset, phase);
2988     const TypePtr* atp = TypeRawPtr::BOTTOM;
2989 
2990     // One or two coalesced stores to plop down.
2991     Node*    st[2];
2992     intptr_t off[2];
2993     int  nst = 0;
2994     if (!split) {
2995       ++new_long;
2996       off[nst] = offset;
2997       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
2998                                   phase->longcon(con), T_LONG);
2999     } else {
3000       // Omit either if it is a zero.
3001       if (con0 != 0) {
3002         ++new_int;
3003         off[nst]  = offset;
3004         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3005                                     phase->intcon(con0), T_INT);
3006       }
3007       if (con1 != 0) {
3008         ++new_int;
3009         offset += BytesPerInt;
3010         adr = make_raw_address(offset, phase);
3011         off[nst]  = offset;
3012         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3013                                     phase->intcon(con1), T_INT);
3014       }
3015     }
3016 
3017     // Insert second store first, then the first before the second.
3018     // Insert each one just before any overlapping non-constant stores.
3019     while (nst > 0) {
3020       Node* st1 = st[--nst];
3021       C->copy_node_notes_to(st1, old);
3022       st1 = phase->transform(st1);
3023       offset = off[nst];
3024       assert(offset >= header_size, "do not smash header");
3025       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
3026       guarantee(ins_idx != 0, "must re-insert constant store");
3027       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
3028       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
3029         set_req(--ins_idx, st1);
3030       else
3031         ins_req(ins_idx, st1);
3032     }
3033   }
3034 
3035   if (PrintCompilation && WizardMode)
3036     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
3037                   old_subword, old_long, new_int, new_long);
3038   if (C->log() != NULL)
3039     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
3040                    old_subword, old_long, new_int, new_long);
3041 
3042   // Clean up any remaining occurrences of zmem:
3043   remove_extra_zeroes();
3044 }
3045 
3046 // Explore forward from in(start) to find the first fully initialized
3047 // word, and return its offset.  Skip groups of subword stores which
3048 // together initialize full words.  If in(start) is itself part of a
3049 // fully initialized word, return the offset of in(start).  If there
3050 // are no following full-word stores, or if something is fishy, return
3051 // a negative value.
3052 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
3053   int       int_map = 0;
3054   intptr_t  int_map_off = 0;
3055   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
3056 
3057   for (uint i = start, limit = req(); i < limit; i++) {
3058     Node* st = in(i);
3059 
3060     intptr_t st_off = get_store_offset(st, phase);
3061     if (st_off < 0)  break;  // return conservative answer
3062 
3063     int st_size = st->as_Store()->memory_size();
3064     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
3065       return st_off;            // we found a complete word init
3066     }
3067 
3068     // update the map:
3069 
3070     intptr_t this_int_off = align_size_down(st_off, BytesPerInt);
3071     if (this_int_off != int_map_off) {
3072       // reset the map:
3073       int_map = 0;
3074       int_map_off = this_int_off;
3075     }
3076 
3077     int subword_off = st_off - this_int_off;
3078     int_map |= right_n_bits(st_size) << subword_off;
3079     if ((int_map & FULL_MAP) == FULL_MAP) {
3080       return this_int_off;      // we found a complete word init
3081     }
3082 
3083     // Did this store hit or cross the word boundary?
3084     intptr_t next_int_off = align_size_down(st_off + st_size, BytesPerInt);
3085     if (next_int_off == this_int_off + BytesPerInt) {
3086       // We passed the current int, without fully initializing it.
3087       int_map_off = next_int_off;
3088       int_map >>= BytesPerInt;
3089     } else if (next_int_off > this_int_off + BytesPerInt) {
3090       // We passed the current and next int.
3091       return this_int_off + BytesPerInt;
3092     }
3093   }
3094 
3095   return -1;
3096 }
3097 
3098 
3099 // Called when the associated AllocateNode is expanded into CFG.
3100 // At this point, we may perform additional optimizations.
3101 // Linearize the stores by ascending offset, to make memory
3102 // activity as coherent as possible.
3103 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
3104                                       intptr_t header_size,
3105                                       Node* size_in_bytes,
3106                                       PhaseGVN* phase) {
3107   assert(!is_complete(), "not already complete");
3108   assert(stores_are_sane(phase), "");
3109   assert(allocation() != NULL, "must be present");
3110 
3111   remove_extra_zeroes();
3112 
3113   if (ReduceFieldZeroing || ReduceBulkZeroing)
3114     // reduce instruction count for common initialization patterns
3115     coalesce_subword_stores(header_size, size_in_bytes, phase);
3116 
3117   Node* zmem = zero_memory();   // initially zero memory state
3118   Node* inits = zmem;           // accumulating a linearized chain of inits
3119   #ifdef ASSERT
3120   intptr_t first_offset = allocation()->minimum_header_size();
3121   intptr_t last_init_off = first_offset;  // previous init offset
3122   intptr_t last_init_end = first_offset;  // previous init offset+size
3123   intptr_t last_tile_end = first_offset;  // previous tile offset+size
3124   #endif
3125   intptr_t zeroes_done = header_size;
3126 
3127   bool do_zeroing = true;       // we might give up if inits are very sparse
3128   int  big_init_gaps = 0;       // how many large gaps have we seen?
3129 
3130   if (ZeroTLAB)  do_zeroing = false;
3131   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
3132 
3133   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3134     Node* st = in(i);
3135     intptr_t st_off = get_store_offset(st, phase);
3136     if (st_off < 0)
3137       break;                    // unknown junk in the inits
3138     if (st->in(MemNode::Memory) != zmem)
3139       break;                    // complicated store chains somehow in list
3140 
3141     int st_size = st->as_Store()->memory_size();
3142     intptr_t next_init_off = st_off + st_size;
3143 
3144     if (do_zeroing && zeroes_done < next_init_off) {
3145       // See if this store needs a zero before it or under it.
3146       intptr_t zeroes_needed = st_off;
3147 
3148       if (st_size < BytesPerInt) {
3149         // Look for subword stores which only partially initialize words.
3150         // If we find some, we must lay down some word-level zeroes first,
3151         // underneath the subword stores.
3152         //
3153         // Examples:
3154         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
3155         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
3156         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
3157         //
3158         // Note:  coalesce_subword_stores may have already done this,
3159         // if it was prompted by constant non-zero subword initializers.
3160         // But this case can still arise with non-constant stores.
3161 
3162         intptr_t next_full_store = find_next_fullword_store(i, phase);
3163 
3164         // In the examples above:
3165         //   in(i)          p   q   r   s     x   y     z
3166         //   st_off        12  13  14  15    12  13    14
3167         //   st_size        1   1   1   1     1   1     1
3168         //   next_full_s.  12  16  16  16    16  16    16
3169         //   z's_done      12  16  16  16    12  16    12
3170         //   z's_needed    12  16  16  16    16  16    16
3171         //   zsize          0   0   0   0     4   0     4
3172         if (next_full_store < 0) {
3173           // Conservative tack:  Zero to end of current word.
3174           zeroes_needed = align_size_up(zeroes_needed, BytesPerInt);
3175         } else {
3176           // Zero to beginning of next fully initialized word.
3177           // Or, don't zero at all, if we are already in that word.
3178           assert(next_full_store >= zeroes_needed, "must go forward");
3179           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
3180           zeroes_needed = next_full_store;
3181         }
3182       }
3183 
3184       if (zeroes_needed > zeroes_done) {
3185         intptr_t zsize = zeroes_needed - zeroes_done;
3186         // Do some incremental zeroing on rawmem, in parallel with inits.
3187         zeroes_done = align_size_down(zeroes_done, BytesPerInt);
3188         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3189                                               zeroes_done, zeroes_needed,
3190                                               phase);
3191         zeroes_done = zeroes_needed;
3192         if (zsize > Matcher::init_array_short_size && ++big_init_gaps > 2)
3193           do_zeroing = false;   // leave the hole, next time
3194       }
3195     }
3196 
3197     // Collect the store and move on:
3198     st->set_req(MemNode::Memory, inits);
3199     inits = st;                 // put it on the linearized chain
3200     set_req(i, zmem);           // unhook from previous position
3201 
3202     if (zeroes_done == st_off)
3203       zeroes_done = next_init_off;
3204 
3205     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
3206 
3207     #ifdef ASSERT
3208     // Various order invariants.  Weaker than stores_are_sane because
3209     // a large constant tile can be filled in by smaller non-constant stores.
3210     assert(st_off >= last_init_off, "inits do not reverse");
3211     last_init_off = st_off;
3212     const Type* val = NULL;
3213     if (st_size >= BytesPerInt &&
3214         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
3215         (int)val->basic_type() < (int)T_OBJECT) {
3216       assert(st_off >= last_tile_end, "tiles do not overlap");
3217       assert(st_off >= last_init_end, "tiles do not overwrite inits");
3218       last_tile_end = MAX2(last_tile_end, next_init_off);
3219     } else {
3220       intptr_t st_tile_end = align_size_up(next_init_off, BytesPerLong);
3221       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
3222       assert(st_off      >= last_init_end, "inits do not overlap");
3223       last_init_end = next_init_off;  // it's a non-tile
3224     }
3225     #endif //ASSERT
3226   }
3227 
3228   remove_extra_zeroes();        // clear out all the zmems left over
3229   add_req(inits);
3230 
3231   if (!ZeroTLAB) {
3232     // If anything remains to be zeroed, zero it all now.
3233     zeroes_done = align_size_down(zeroes_done, BytesPerInt);
3234     // if it is the last unused 4 bytes of an instance, forget about it
3235     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
3236     if (zeroes_done + BytesPerLong >= size_limit) {
3237       assert(allocation() != NULL, "");
3238       Node* klass_node = allocation()->in(AllocateNode::KlassNode);
3239       ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
3240       if (zeroes_done == k->layout_helper())
3241         zeroes_done = size_limit;
3242     }
3243     if (zeroes_done < size_limit) {
3244       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3245                                             zeroes_done, size_in_bytes, phase);
3246     }
3247   }
3248 
3249   set_complete(phase);
3250   return rawmem;
3251 }
3252 
3253 
3254 #ifdef ASSERT
3255 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
3256   if (is_complete())
3257     return true;                // stores could be anything at this point
3258   assert(allocation() != NULL, "must be present");
3259   intptr_t last_off = allocation()->minimum_header_size();
3260   for (uint i = InitializeNode::RawStores; i < req(); i++) {
3261     Node* st = in(i);
3262     intptr_t st_off = get_store_offset(st, phase);
3263     if (st_off < 0)  continue;  // ignore dead garbage
3264     if (last_off > st_off) {
3265       tty->print_cr("*** bad store offset at %d: %d > %d", i, last_off, st_off);
3266       this->dump(2);
3267       assert(false, "ascending store offsets");
3268       return false;
3269     }
3270     last_off = st_off + st->as_Store()->memory_size();
3271   }
3272   return true;
3273 }
3274 #endif //ASSERT
3275 
3276 
3277 
3278 
3279 //============================MergeMemNode=====================================
3280 //
3281 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
3282 // contributing store or call operations.  Each contributor provides the memory
3283 // state for a particular "alias type" (see Compile::alias_type).  For example,
3284 // if a MergeMem has an input X for alias category #6, then any memory reference
3285 // to alias category #6 may use X as its memory state input, as an exact equivalent
3286 // to using the MergeMem as a whole.
3287 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
3288 //
3289 // (Here, the <N> notation gives the index of the relevant adr_type.)
3290 //
3291 // In one special case (and more cases in the future), alias categories overlap.
3292 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
3293 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
3294 // it is exactly equivalent to that state W:
3295 //   MergeMem(<Bot>: W) <==> W
3296 //
3297 // Usually, the merge has more than one input.  In that case, where inputs
3298 // overlap (i.e., one is Bot), the narrower alias type determines the memory
3299 // state for that type, and the wider alias type (Bot) fills in everywhere else:
3300 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
3301 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
3302 //
3303 // A merge can take a "wide" memory state as one of its narrow inputs.
3304 // This simply means that the merge observes out only the relevant parts of
3305 // the wide input.  That is, wide memory states arriving at narrow merge inputs
3306 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
3307 //
3308 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
3309 // and that memory slices "leak through":
3310 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
3311 //
3312 // But, in such a cascade, repeated memory slices can "block the leak":
3313 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
3314 //
3315 // In the last example, Y is not part of the combined memory state of the
3316 // outermost MergeMem.  The system must, of course, prevent unschedulable
3317 // memory states from arising, so you can be sure that the state Y is somehow
3318 // a precursor to state Y'.
3319 //
3320 //
3321 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
3322 // of each MergeMemNode array are exactly the numerical alias indexes, including
3323 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
3324 // Compile::alias_type (and kin) produce and manage these indexes.
3325 //
3326 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
3327 // (Note that this provides quick access to the top node inside MergeMem methods,
3328 // without the need to reach out via TLS to Compile::current.)
3329 //
3330 // As a consequence of what was just described, a MergeMem that represents a full
3331 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
3332 // containing all alias categories.
3333 //
3334 // MergeMem nodes never (?) have control inputs, so in(0) is NULL.
3335 //
3336 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
3337 // a memory state for the alias type <N>, or else the top node, meaning that
3338 // there is no particular input for that alias type.  Note that the length of
3339 // a MergeMem is variable, and may be extended at any time to accommodate new
3340 // memory states at larger alias indexes.  When merges grow, they are of course
3341 // filled with "top" in the unused in() positions.
3342 //
3343 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
3344 // (Top was chosen because it works smoothly with passes like GCM.)
3345 //
3346 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
3347 // the type of random VM bits like TLS references.)  Since it is always the
3348 // first non-Bot memory slice, some low-level loops use it to initialize an
3349 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
3350 //
3351 //
3352 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
3353 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
3354 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
3355 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
3356 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
3357 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
3358 //
3359 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
3360 // really that different from the other memory inputs.  An abbreviation called
3361 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
3362 //
3363 //
3364 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
3365 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
3366 // that "emerges though" the base memory will be marked as excluding the alias types
3367 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
3368 //
3369 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
3370 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
3371 //
3372 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
3373 // (It is currently unimplemented.)  As you can see, the resulting merge is
3374 // actually a disjoint union of memory states, rather than an overlay.
3375 //
3376 
3377 //------------------------------MergeMemNode-----------------------------------
3378 Node* MergeMemNode::make_empty_memory() {
3379   Node* empty_memory = (Node*) Compile::current()->top();
3380   assert(empty_memory->is_top(), "correct sentinel identity");
3381   return empty_memory;
3382 }
3383 
3384 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
3385   init_class_id(Class_MergeMem);
3386   // all inputs are nullified in Node::Node(int)
3387   // set_input(0, NULL);  // no control input
3388 
3389   // Initialize the edges uniformly to top, for starters.
3390   Node* empty_mem = make_empty_memory();
3391   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
3392     init_req(i,empty_mem);
3393   }
3394   assert(empty_memory() == empty_mem, "");
3395 
3396   if( new_base != NULL && new_base->is_MergeMem() ) {
3397     MergeMemNode* mdef = new_base->as_MergeMem();
3398     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
3399     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
3400       mms.set_memory(mms.memory2());
3401     }
3402     assert(base_memory() == mdef->base_memory(), "");
3403   } else {
3404     set_base_memory(new_base);
3405   }
3406 }
3407 
3408 // Make a new, untransformed MergeMem with the same base as 'mem'.
3409 // If mem is itself a MergeMem, populate the result with the same edges.
3410 MergeMemNode* MergeMemNode::make(Compile* C, Node* mem) {
3411   return new(C, 1+Compile::AliasIdxRaw) MergeMemNode(mem);
3412 }
3413 
3414 //------------------------------cmp--------------------------------------------
3415 uint MergeMemNode::hash() const { return NO_HASH; }
3416 uint MergeMemNode::cmp( const Node &n ) const {
3417   return (&n == this);          // Always fail except on self
3418 }
3419 
3420 //------------------------------Identity---------------------------------------
3421 Node* MergeMemNode::Identity(PhaseTransform *phase) {
3422   // Identity if this merge point does not record any interesting memory
3423   // disambiguations.
3424   Node* base_mem = base_memory();
3425   Node* empty_mem = empty_memory();
3426   if (base_mem != empty_mem) {  // Memory path is not dead?
3427     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
3428       Node* mem = in(i);
3429       if (mem != empty_mem && mem != base_mem) {
3430         return this;            // Many memory splits; no change
3431       }
3432     }
3433   }
3434   return base_mem;              // No memory splits; ID on the one true input
3435 }
3436 
3437 //------------------------------Ideal------------------------------------------
3438 // This method is invoked recursively on chains of MergeMem nodes
3439 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3440   // Remove chain'd MergeMems
3441   //
3442   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
3443   // relative to the "in(Bot)".  Since we are patching both at the same time,
3444   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
3445   // but rewrite each "in(i)" relative to the new "in(Bot)".
3446   Node *progress = NULL;
3447 
3448 
3449   Node* old_base = base_memory();
3450   Node* empty_mem = empty_memory();
3451   if (old_base == empty_mem)
3452     return NULL; // Dead memory path.
3453 
3454   MergeMemNode* old_mbase;
3455   if (old_base != NULL && old_base->is_MergeMem())
3456     old_mbase = old_base->as_MergeMem();
3457   else
3458     old_mbase = NULL;
3459   Node* new_base = old_base;
3460 
3461   // simplify stacked MergeMems in base memory
3462   if (old_mbase)  new_base = old_mbase->base_memory();
3463 
3464   // the base memory might contribute new slices beyond my req()
3465   if (old_mbase)  grow_to_match(old_mbase);
3466 
3467   // Look carefully at the base node if it is a phi.
3468   PhiNode* phi_base;
3469   if (new_base != NULL && new_base->is_Phi())
3470     phi_base = new_base->as_Phi();
3471   else
3472     phi_base = NULL;
3473 
3474   Node*    phi_reg = NULL;
3475   uint     phi_len = (uint)-1;
3476   if (phi_base != NULL && !phi_base->is_copy()) {
3477     // do not examine phi if degraded to a copy
3478     phi_reg = phi_base->region();
3479     phi_len = phi_base->req();
3480     // see if the phi is unfinished
3481     for (uint i = 1; i < phi_len; i++) {
3482       if (phi_base->in(i) == NULL) {
3483         // incomplete phi; do not look at it yet!
3484         phi_reg = NULL;
3485         phi_len = (uint)-1;
3486         break;
3487       }
3488     }
3489   }
3490 
3491   // Note:  We do not call verify_sparse on entry, because inputs
3492   // can normalize to the base_memory via subsume_node or similar
3493   // mechanisms.  This method repairs that damage.
3494 
3495   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
3496 
3497   // Look at each slice.
3498   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
3499     Node* old_in = in(i);
3500     // calculate the old memory value
3501     Node* old_mem = old_in;
3502     if (old_mem == empty_mem)  old_mem = old_base;
3503     assert(old_mem == memory_at(i), "");
3504 
3505     // maybe update (reslice) the old memory value
3506 
3507     // simplify stacked MergeMems
3508     Node* new_mem = old_mem;
3509     MergeMemNode* old_mmem;
3510     if (old_mem != NULL && old_mem->is_MergeMem())
3511       old_mmem = old_mem->as_MergeMem();
3512     else
3513       old_mmem = NULL;
3514     if (old_mmem == this) {
3515       // This can happen if loops break up and safepoints disappear.
3516       // A merge of BotPtr (default) with a RawPtr memory derived from a
3517       // safepoint can be rewritten to a merge of the same BotPtr with
3518       // the BotPtr phi coming into the loop.  If that phi disappears
3519       // also, we can end up with a self-loop of the mergemem.
3520       // In general, if loops degenerate and memory effects disappear,
3521       // a mergemem can be left looking at itself.  This simply means
3522       // that the mergemem's default should be used, since there is
3523       // no longer any apparent effect on this slice.
3524       // Note: If a memory slice is a MergeMem cycle, it is unreachable
3525       //       from start.  Update the input to TOP.
3526       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
3527     }
3528     else if (old_mmem != NULL) {
3529       new_mem = old_mmem->memory_at(i);
3530     }
3531     // else preceeding memory was not a MergeMem
3532 
3533     // replace equivalent phis (unfortunately, they do not GVN together)
3534     if (new_mem != NULL && new_mem != new_base &&
3535         new_mem->req() == phi_len && new_mem->in(0) == phi_reg) {
3536       if (new_mem->is_Phi()) {
3537         PhiNode* phi_mem = new_mem->as_Phi();
3538         for (uint i = 1; i < phi_len; i++) {
3539           if (phi_base->in(i) != phi_mem->in(i)) {
3540             phi_mem = NULL;
3541             break;
3542           }
3543         }
3544         if (phi_mem != NULL) {
3545           // equivalent phi nodes; revert to the def
3546           new_mem = new_base;
3547         }
3548       }
3549     }
3550 
3551     // maybe store down a new value
3552     Node* new_in = new_mem;
3553     if (new_in == new_base)  new_in = empty_mem;
3554 
3555     if (new_in != old_in) {
3556       // Warning:  Do not combine this "if" with the previous "if"
3557       // A memory slice might have be be rewritten even if it is semantically
3558       // unchanged, if the base_memory value has changed.
3559       set_req(i, new_in);
3560       progress = this;          // Report progress
3561     }
3562   }
3563 
3564   if (new_base != old_base) {
3565     set_req(Compile::AliasIdxBot, new_base);
3566     // Don't use set_base_memory(new_base), because we need to update du.
3567     assert(base_memory() == new_base, "");
3568     progress = this;
3569   }
3570 
3571   if( base_memory() == this ) {
3572     // a self cycle indicates this memory path is dead
3573     set_req(Compile::AliasIdxBot, empty_mem);
3574   }
3575 
3576   // Resolve external cycles by calling Ideal on a MergeMem base_memory
3577   // Recursion must occur after the self cycle check above
3578   if( base_memory()->is_MergeMem() ) {
3579     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
3580     Node *m = phase->transform(new_mbase);  // Rollup any cycles
3581     if( m != NULL && (m->is_top() ||
3582         m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem) ) {
3583       // propagate rollup of dead cycle to self
3584       set_req(Compile::AliasIdxBot, empty_mem);
3585     }
3586   }
3587 
3588   if( base_memory() == empty_mem ) {
3589     progress = this;
3590     // Cut inputs during Parse phase only.
3591     // During Optimize phase a dead MergeMem node will be subsumed by Top.
3592     if( !can_reshape ) {
3593       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
3594         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
3595       }
3596     }
3597   }
3598 
3599   if( !progress && base_memory()->is_Phi() && can_reshape ) {
3600     // Check if PhiNode::Ideal's "Split phis through memory merges"
3601     // transform should be attempted. Look for this->phi->this cycle.
3602     uint merge_width = req();
3603     if (merge_width > Compile::AliasIdxRaw) {
3604       PhiNode* phi = base_memory()->as_Phi();
3605       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
3606         if (phi->in(i) == this) {
3607           phase->is_IterGVN()->_worklist.push(phi);
3608           break;
3609         }
3610       }
3611     }
3612   }
3613 
3614   assert(progress || verify_sparse(), "please, no dups of base");
3615   return progress;
3616 }
3617 
3618 //-------------------------set_base_memory-------------------------------------
3619 void MergeMemNode::set_base_memory(Node *new_base) {
3620   Node* empty_mem = empty_memory();
3621   set_req(Compile::AliasIdxBot, new_base);
3622   assert(memory_at(req()) == new_base, "must set default memory");
3623   // Clear out other occurrences of new_base:
3624   if (new_base != empty_mem) {
3625     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
3626       if (in(i) == new_base)  set_req(i, empty_mem);
3627     }
3628   }
3629 }
3630 
3631 //------------------------------out_RegMask------------------------------------
3632 const RegMask &MergeMemNode::out_RegMask() const {
3633   return RegMask::Empty;
3634 }
3635 
3636 //------------------------------dump_spec--------------------------------------
3637 #ifndef PRODUCT
3638 void MergeMemNode::dump_spec(outputStream *st) const {
3639   st->print(" {");
3640   Node* base_mem = base_memory();
3641   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
3642     Node* mem = memory_at(i);
3643     if (mem == base_mem) { st->print(" -"); continue; }
3644     st->print( " N%d:", mem->_idx );
3645     Compile::current()->get_adr_type(i)->dump_on(st);
3646   }
3647   st->print(" }");
3648 }
3649 #endif // !PRODUCT
3650 
3651 
3652 #ifdef ASSERT
3653 static bool might_be_same(Node* a, Node* b) {
3654   if (a == b)  return true;
3655   if (!(a->is_Phi() || b->is_Phi()))  return false;
3656   // phis shift around during optimization
3657   return true;  // pretty stupid...
3658 }
3659 
3660 // verify a narrow slice (either incoming or outgoing)
3661 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
3662   if (!VerifyAliases)       return;  // don't bother to verify unless requested
3663   if (is_error_reported())  return;  // muzzle asserts when debugging an error
3664   if (Node::in_dump())      return;  // muzzle asserts when printing
3665   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
3666   assert(n != NULL, "");
3667   // Elide intervening MergeMem's
3668   while (n->is_MergeMem()) {
3669     n = n->as_MergeMem()->memory_at(alias_idx);
3670   }
3671   Compile* C = Compile::current();
3672   const TypePtr* n_adr_type = n->adr_type();
3673   if (n == m->empty_memory()) {
3674     // Implicit copy of base_memory()
3675   } else if (n_adr_type != TypePtr::BOTTOM) {
3676     assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
3677     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
3678   } else {
3679     // A few places like make_runtime_call "know" that VM calls are narrow,
3680     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
3681     bool expected_wide_mem = false;
3682     if (n == m->base_memory()) {
3683       expected_wide_mem = true;
3684     } else if (alias_idx == Compile::AliasIdxRaw ||
3685                n == m->memory_at(Compile::AliasIdxRaw)) {
3686       expected_wide_mem = true;
3687     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
3688       // memory can "leak through" calls on channels that
3689       // are write-once.  Allow this also.
3690       expected_wide_mem = true;
3691     }
3692     assert(expected_wide_mem, "expected narrow slice replacement");
3693   }
3694 }
3695 #else // !ASSERT
3696 #define verify_memory_slice(m,i,n) (0)  // PRODUCT version is no-op
3697 #endif
3698 
3699 
3700 //-----------------------------memory_at---------------------------------------
3701 Node* MergeMemNode::memory_at(uint alias_idx) const {
3702   assert(alias_idx >= Compile::AliasIdxRaw ||
3703          alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
3704          "must avoid base_memory and AliasIdxTop");
3705 
3706   // Otherwise, it is a narrow slice.
3707   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
3708   Compile *C = Compile::current();
3709   if (is_empty_memory(n)) {
3710     // the array is sparse; empty slots are the "top" node
3711     n = base_memory();
3712     assert(Node::in_dump()
3713            || n == NULL || n->bottom_type() == Type::TOP
3714            || n->adr_type() == TypePtr::BOTTOM
3715            || n->adr_type() == TypeRawPtr::BOTTOM
3716            || Compile::current()->AliasLevel() == 0,
3717            "must be a wide memory");
3718     // AliasLevel == 0 if we are organizing the memory states manually.
3719     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
3720   } else {
3721     // make sure the stored slice is sane
3722     #ifdef ASSERT
3723     if (is_error_reported() || Node::in_dump()) {
3724     } else if (might_be_same(n, base_memory())) {
3725       // Give it a pass:  It is a mostly harmless repetition of the base.
3726       // This can arise normally from node subsumption during optimization.
3727     } else {
3728       verify_memory_slice(this, alias_idx, n);
3729     }
3730     #endif
3731   }
3732   return n;
3733 }
3734 
3735 //---------------------------set_memory_at-------------------------------------
3736 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
3737   verify_memory_slice(this, alias_idx, n);
3738   Node* empty_mem = empty_memory();
3739   if (n == base_memory())  n = empty_mem;  // collapse default
3740   uint need_req = alias_idx+1;
3741   if (req() < need_req) {
3742     if (n == empty_mem)  return;  // already the default, so do not grow me
3743     // grow the sparse array
3744     do {
3745       add_req(empty_mem);
3746     } while (req() < need_req);
3747   }
3748   set_req( alias_idx, n );
3749 }
3750 
3751 
3752 
3753 //--------------------------iteration_setup------------------------------------
3754 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
3755   if (other != NULL) {
3756     grow_to_match(other);
3757     // invariant:  the finite support of mm2 is within mm->req()
3758     #ifdef ASSERT
3759     for (uint i = req(); i < other->req(); i++) {
3760       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
3761     }
3762     #endif
3763   }
3764   // Replace spurious copies of base_memory by top.
3765   Node* base_mem = base_memory();
3766   if (base_mem != NULL && !base_mem->is_top()) {
3767     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
3768       if (in(i) == base_mem)
3769         set_req(i, empty_memory());
3770     }
3771   }
3772 }
3773 
3774 //---------------------------grow_to_match-------------------------------------
3775 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
3776   Node* empty_mem = empty_memory();
3777   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
3778   // look for the finite support of the other memory
3779   for (uint i = other->req(); --i >= req(); ) {
3780     if (other->in(i) != empty_mem) {
3781       uint new_len = i+1;
3782       while (req() < new_len)  add_req(empty_mem);
3783       break;
3784     }
3785   }
3786 }
3787 
3788 //---------------------------verify_sparse-------------------------------------
3789 #ifndef PRODUCT
3790 bool MergeMemNode::verify_sparse() const {
3791   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
3792   Node* base_mem = base_memory();
3793   // The following can happen in degenerate cases, since empty==top.
3794   if (is_empty_memory(base_mem))  return true;
3795   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
3796     assert(in(i) != NULL, "sane slice");
3797     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
3798   }
3799   return true;
3800 }
3801 
3802 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
3803   Node* n;
3804   n = mm->in(idx);
3805   if (mem == n)  return true;  // might be empty_memory()
3806   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
3807   if (mem == n)  return true;
3808   while (n->is_Phi() && (n = n->as_Phi()->is_copy()) != NULL) {
3809     if (mem == n)  return true;
3810     if (n == NULL)  break;
3811   }
3812   return false;
3813 }
3814 #endif // !PRODUCT