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