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