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