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