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