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