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