1 /*
   2  * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/systemDictionary.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "memory/allocation.inline.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "oops/objArrayKlass.hpp"
  31 #include "opto/addnode.hpp"
  32 #include "opto/arraycopynode.hpp"
  33 #include "opto/cfgnode.hpp"
  34 #include "opto/compile.hpp"
  35 #include "opto/connode.hpp"
  36 #include "opto/convertnode.hpp"
  37 #include "opto/loopnode.hpp"
  38 #include "opto/machnode.hpp"
  39 #include "opto/matcher.hpp"
  40 #include "opto/memnode.hpp"
  41 #include "opto/mulnode.hpp"
  42 #include "opto/narrowptrnode.hpp"
  43 #include "opto/phaseX.hpp"
  44 #include "opto/regmask.hpp"
  45 #include "utilities/copy.hpp"
  46 
  47 // Portions of code courtesy of Clifford Click
  48 
  49 // Optimization - Graph Style
  50 
  51 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
  52 
  53 //=============================================================================
  54 uint MemNode::size_of() const { return sizeof(*this); }
  55 
  56 const TypePtr *MemNode::adr_type() const {
  57   Node* adr = in(Address);
  58   if (adr == NULL)  return NULL; // node is dead
  59   const TypePtr* cross_check = NULL;
  60   DEBUG_ONLY(cross_check = _adr_type);
  61   return calculate_adr_type(adr->bottom_type(), cross_check);
  62 }
  63 
  64 #ifndef PRODUCT
  65 void MemNode::dump_spec(outputStream *st) const {
  66   if (in(Address) == NULL)  return; // node is dead
  67 #ifndef ASSERT
  68   // fake the missing field
  69   const TypePtr* _adr_type = NULL;
  70   if (in(Address) != NULL)
  71     _adr_type = in(Address)->bottom_type()->isa_ptr();
  72 #endif
  73   dump_adr_type(this, _adr_type, st);
  74 
  75   Compile* C = Compile::current();
  76   if (C->alias_type(_adr_type)->is_volatile()) {
  77     st->print(" Volatile!");
  78   }
  79   if (_unaligned_access) {
  80     st->print(" unaligned");
  81   }
  82   if (_mismatched_access) {
  83     st->print(" mismatched");
  84   }
  85 }
  86 
  87 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
  88   st->print(" @");
  89   if (adr_type == NULL) {
  90     st->print("NULL");
  91   } else {
  92     adr_type->dump_on(st);
  93     Compile* C = Compile::current();
  94     Compile::AliasType* atp = NULL;
  95     if (C->have_alias_type(adr_type))  atp = C->alias_type(adr_type);
  96     if (atp == NULL)
  97       st->print(", idx=?\?;");
  98     else if (atp->index() == Compile::AliasIdxBot)
  99       st->print(", idx=Bot;");
 100     else if (atp->index() == Compile::AliasIdxTop)
 101       st->print(", idx=Top;");
 102     else if (atp->index() == Compile::AliasIdxRaw)
 103       st->print(", idx=Raw;");
 104     else {
 105       ciField* field = atp->field();
 106       if (field) {
 107         st->print(", name=");
 108         field->print_name_on(st);
 109       }
 110       st->print(", idx=%d;", atp->index());
 111     }
 112   }
 113 }
 114 
 115 extern void print_alias_types();
 116 
 117 #endif
 118 
 119 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) {
 120   assert((t_oop != NULL), "sanity");
 121   bool is_instance = t_oop->is_known_instance_field();
 122   bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() &&
 123                              (load != NULL) && load->is_Load() &&
 124                              (phase->is_IterGVN() != NULL);
 125   if (!(is_instance || is_boxed_value_load))
 126     return mchain;  // don't try to optimize non-instance types
 127   uint instance_id = t_oop->instance_id();
 128   Node *start_mem = phase->C->start()->proj_out(TypeFunc::Memory);
 129   Node *prev = NULL;
 130   Node *result = mchain;
 131   while (prev != result) {
 132     prev = result;
 133     if (result == start_mem)
 134       break;  // hit one of our sentinels
 135     // skip over a call which does not affect this memory slice
 136     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
 137       Node *proj_in = result->in(0);
 138       if (proj_in->is_Allocate() && proj_in->_idx == instance_id) {
 139         break;  // hit one of our sentinels
 140       } else if (proj_in->is_Call()) {
 141         // ArrayCopyNodes processed here as well
 142         CallNode *call = proj_in->as_Call();
 143         if (!call->may_modify(t_oop, phase)) { // returns false for instances
 144           result = call->in(TypeFunc::Memory);
 145         }
 146       } else if (proj_in->is_Initialize()) {
 147         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
 148         // Stop if this is the initialization for the object instance which
 149         // contains this memory slice, otherwise skip over it.
 150         if ((alloc == NULL) || (alloc->_idx == instance_id)) {
 151           break;
 152         }
 153         if (is_instance) {
 154           result = proj_in->in(TypeFunc::Memory);
 155         } else if (is_boxed_value_load) {
 156           Node* klass = alloc->in(AllocateNode::KlassNode);
 157           const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr();
 158           if (tklass->klass_is_exact() && !tklass->klass()->equals(t_oop->klass())) {
 159             result = proj_in->in(TypeFunc::Memory); // not related allocation
 160           }
 161         }
 162       } else if (proj_in->is_MemBar()) {
 163         ArrayCopyNode* ac = NULL;
 164         if (ArrayCopyNode::may_modify(t_oop, proj_in->as_MemBar(), phase, ac)) {
 165           break;
 166         }
 167         result = proj_in->in(TypeFunc::Memory);
 168       } else {
 169         assert(false, "unexpected projection");
 170       }
 171     } else if (result->is_ClearArray()) {
 172       if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) {
 173         // Can not bypass initialization of the instance
 174         // we are looking for.
 175         break;
 176       }
 177       // Otherwise skip it (the call updated 'result' value).
 178     } else if (result->is_MergeMem()) {
 179       result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, NULL, tty);
 180     }
 181   }
 182   return result;
 183 }
 184 
 185 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) {
 186   const TypeOopPtr* t_oop = t_adr->isa_oopptr();
 187   if (t_oop == NULL)
 188     return mchain;  // don't try to optimize non-oop types
 189   Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase);
 190   bool is_instance = t_oop->is_known_instance_field();
 191   PhaseIterGVN *igvn = phase->is_IterGVN();
 192   if (is_instance && igvn != NULL  && result->is_Phi()) {
 193     PhiNode *mphi = result->as_Phi();
 194     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
 195     const TypePtr *t = mphi->adr_type();
 196     if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ||
 197         t->isa_oopptr() && !t->is_oopptr()->is_known_instance() &&
 198         t->is_oopptr()->cast_to_exactness(true)
 199          ->is_oopptr()->cast_to_ptr_type(t_oop->ptr())
 200          ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop) {
 201       // clone the Phi with our address type
 202       result = mphi->split_out_instance(t_adr, igvn);
 203     } else {
 204       assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
 205     }
 206   }
 207   return result;
 208 }
 209 
 210 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
 211   uint alias_idx = phase->C->get_alias_index(tp);
 212   Node *mem = mmem;
 213 #ifdef ASSERT
 214   {
 215     // Check that current type is consistent with the alias index used during graph construction
 216     assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
 217     bool consistent =  adr_check == NULL || adr_check->empty() ||
 218                        phase->C->must_alias(adr_check, alias_idx );
 219     // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
 220     if( !consistent && adr_check != NULL && !adr_check->empty() &&
 221                tp->isa_aryptr() &&        tp->offset() == Type::OffsetBot &&
 222         adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
 223         ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
 224           adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
 225           adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
 226       // don't assert if it is dead code.
 227       consistent = true;
 228     }
 229     if( !consistent ) {
 230       st->print("alias_idx==%d, adr_check==", alias_idx);
 231       if( adr_check == NULL ) {
 232         st->print("NULL");
 233       } else {
 234         adr_check->dump();
 235       }
 236       st->cr();
 237       print_alias_types();
 238       assert(consistent, "adr_check must match alias idx");
 239     }
 240   }
 241 #endif
 242   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
 243   // means an array I have not precisely typed yet.  Do not do any
 244   // alias stuff with it any time soon.
 245   const TypeOopPtr *toop = tp->isa_oopptr();
 246   if( tp->base() != Type::AnyPtr &&
 247       !(toop &&
 248         toop->klass() != NULL &&
 249         toop->klass()->is_java_lang_Object() &&
 250         toop->offset() == Type::OffsetBot) ) {
 251     // compress paths and change unreachable cycles to TOP
 252     // If not, we can update the input infinitely along a MergeMem cycle
 253     // Equivalent code in PhiNode::Ideal
 254     Node* m  = phase->transform(mmem);
 255     // If transformed to a MergeMem, get the desired slice
 256     // Otherwise the returned node represents memory for every slice
 257     mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
 258     // Update input if it is progress over what we have now
 259   }
 260   return mem;
 261 }
 262 
 263 //--------------------------Ideal_common---------------------------------------
 264 // Look for degenerate control and memory inputs.  Bypass MergeMem inputs.
 265 // Unhook non-raw memories from complete (macro-expanded) initializations.
 266 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
 267   // If our control input is a dead region, kill all below the region
 268   Node *ctl = in(MemNode::Control);
 269   if (ctl && remove_dead_region(phase, can_reshape))
 270     return this;
 271   ctl = in(MemNode::Control);
 272   // Don't bother trying to transform a dead node
 273   if (ctl && ctl->is_top())  return NodeSentinel;
 274 
 275   PhaseIterGVN *igvn = phase->is_IterGVN();
 276   // Wait if control on the worklist.
 277   if (ctl && can_reshape && igvn != NULL) {
 278     Node* bol = NULL;
 279     Node* cmp = NULL;
 280     if (ctl->in(0)->is_If()) {
 281       assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity");
 282       bol = ctl->in(0)->in(1);
 283       if (bol->is_Bool())
 284         cmp = ctl->in(0)->in(1)->in(1);
 285     }
 286     if (igvn->_worklist.member(ctl) ||
 287         (bol != NULL && igvn->_worklist.member(bol)) ||
 288         (cmp != NULL && igvn->_worklist.member(cmp)) ) {
 289       // This control path may be dead.
 290       // Delay this memory node transformation until the control is processed.
 291       phase->is_IterGVN()->_worklist.push(this);
 292       return NodeSentinel; // caller will return NULL
 293     }
 294   }
 295   // Ignore if memory is dead, or self-loop
 296   Node *mem = in(MemNode::Memory);
 297   if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return NULL
 298   assert(mem != this, "dead loop in MemNode::Ideal");
 299 
 300   if (can_reshape && igvn != NULL && igvn->_worklist.member(mem)) {
 301     // This memory slice may be dead.
 302     // Delay this mem node transformation until the memory is processed.
 303     phase->is_IterGVN()->_worklist.push(this);
 304     return NodeSentinel; // caller will return NULL
 305   }
 306 
 307   Node *address = in(MemNode::Address);
 308   const Type *t_adr = phase->type(address);
 309   if (t_adr == Type::TOP)              return NodeSentinel; // caller will return NULL
 310 
 311   if (can_reshape && igvn != NULL &&
 312       (igvn->_worklist.member(address) ||
 313        igvn->_worklist.size() > 0 && (t_adr != adr_type())) ) {
 314     // The address's base and type may change when the address is processed.
 315     // Delay this mem node transformation until the address is processed.
 316     phase->is_IterGVN()->_worklist.push(this);
 317     return NodeSentinel; // caller will return NULL
 318   }
 319 
 320   // Do NOT remove or optimize the next lines: ensure a new alias index
 321   // is allocated for an oop pointer type before Escape Analysis.
 322   // Note: C++ will not remove it since the call has side effect.
 323   if (t_adr->isa_oopptr()) {
 324     int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
 325   }
 326 
 327   Node* base = NULL;
 328   if (address->is_AddP()) {
 329     base = address->in(AddPNode::Base);
 330   }
 331   if (base != NULL && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
 332       !t_adr->isa_rawptr()) {
 333     // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
 334     // Skip this node optimization if its address has TOP base.
 335     return NodeSentinel; // caller will return NULL
 336   }
 337 
 338   // Avoid independent memory operations
 339   Node* old_mem = mem;
 340 
 341   // The code which unhooks non-raw memories from complete (macro-expanded)
 342   // initializations was removed. After macro-expansion all stores catched
 343   // by Initialize node became raw stores and there is no information
 344   // which memory slices they modify. So it is unsafe to move any memory
 345   // operation above these stores. Also in most cases hooked non-raw memories
 346   // were already unhooked by using information from detect_ptr_independence()
 347   // and find_previous_store().
 348 
 349   if (mem->is_MergeMem()) {
 350     MergeMemNode* mmem = mem->as_MergeMem();
 351     const TypePtr *tp = t_adr->is_ptr();
 352 
 353     mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
 354   }
 355 
 356   if (mem != old_mem) {
 357     set_req(MemNode::Memory, mem);
 358     if (can_reshape && old_mem->outcnt() == 0) {
 359         igvn->_worklist.push(old_mem);
 360     }
 361     if (phase->type( mem ) == Type::TOP) return NodeSentinel;
 362     return this;
 363   }
 364 
 365   // let the subclass continue analyzing...
 366   return NULL;
 367 }
 368 
 369 // Helper function for proving some simple control dominations.
 370 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
 371 // Already assumes that 'dom' is available at 'sub', and that 'sub'
 372 // is not a constant (dominated by the method's StartNode).
 373 // Used by MemNode::find_previous_store to prove that the
 374 // control input of a memory operation predates (dominates)
 375 // an allocation it wants to look past.
 376 bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
 377   if (dom == NULL || dom->is_top() || sub == NULL || sub->is_top())
 378     return false; // Conservative answer for dead code
 379 
 380   // Check 'dom'. Skip Proj and CatchProj nodes.
 381   dom = dom->find_exact_control(dom);
 382   if (dom == NULL || dom->is_top())
 383     return false; // Conservative answer for dead code
 384 
 385   if (dom == sub) {
 386     // For the case when, for example, 'sub' is Initialize and the original
 387     // 'dom' is Proj node of the 'sub'.
 388     return false;
 389   }
 390 
 391   if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub)
 392     return true;
 393 
 394   // 'dom' dominates 'sub' if its control edge and control edges
 395   // of all its inputs dominate or equal to sub's control edge.
 396 
 397   // Currently 'sub' is either Allocate, Initialize or Start nodes.
 398   // Or Region for the check in LoadNode::Ideal();
 399   // 'sub' should have sub->in(0) != NULL.
 400   assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() ||
 401          sub->is_Region() || sub->is_Call(), "expecting only these nodes");
 402 
 403   // Get control edge of 'sub'.
 404   Node* orig_sub = sub;
 405   sub = sub->find_exact_control(sub->in(0));
 406   if (sub == NULL || sub->is_top())
 407     return false; // Conservative answer for dead code
 408 
 409   assert(sub->is_CFG(), "expecting control");
 410 
 411   if (sub == dom)
 412     return true;
 413 
 414   if (sub->is_Start() || sub->is_Root())
 415     return false;
 416 
 417   {
 418     // Check all control edges of 'dom'.
 419 
 420     ResourceMark rm;
 421     Arena* arena = Thread::current()->resource_area();
 422     Node_List nlist(arena);
 423     Unique_Node_List dom_list(arena);
 424 
 425     dom_list.push(dom);
 426     bool only_dominating_controls = false;
 427 
 428     for (uint next = 0; next < dom_list.size(); next++) {
 429       Node* n = dom_list.at(next);
 430       if (n == orig_sub)
 431         return false; // One of dom's inputs dominated by sub.
 432       if (!n->is_CFG() && n->pinned()) {
 433         // Check only own control edge for pinned non-control nodes.
 434         n = n->find_exact_control(n->in(0));
 435         if (n == NULL || n->is_top())
 436           return false; // Conservative answer for dead code
 437         assert(n->is_CFG(), "expecting control");
 438         dom_list.push(n);
 439       } else if (n->is_Con() || n->is_Start() || n->is_Root()) {
 440         only_dominating_controls = true;
 441       } else if (n->is_CFG()) {
 442         if (n->dominates(sub, nlist))
 443           only_dominating_controls = true;
 444         else
 445           return false;
 446       } else {
 447         // First, own control edge.
 448         Node* m = n->find_exact_control(n->in(0));
 449         if (m != NULL) {
 450           if (m->is_top())
 451             return false; // Conservative answer for dead code
 452           dom_list.push(m);
 453         }
 454         // Now, the rest of edges.
 455         uint cnt = n->req();
 456         for (uint i = 1; i < cnt; i++) {
 457           m = n->find_exact_control(n->in(i));
 458           if (m == NULL || m->is_top())
 459             continue;
 460           dom_list.push(m);
 461         }
 462       }
 463     }
 464     return only_dominating_controls;
 465   }
 466 }
 467 
 468 //---------------------detect_ptr_independence---------------------------------
 469 // Used by MemNode::find_previous_store to prove that two base
 470 // pointers are never equal.
 471 // The pointers are accompanied by their associated allocations,
 472 // if any, which have been previously discovered by the caller.
 473 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
 474                                       Node* p2, AllocateNode* a2,
 475                                       PhaseTransform* phase) {
 476   // Attempt to prove that these two pointers cannot be aliased.
 477   // They may both manifestly be allocations, and they should differ.
 478   // Or, if they are not both allocations, they can be distinct constants.
 479   // Otherwise, one is an allocation and the other a pre-existing value.
 480   if (a1 == NULL && a2 == NULL) {           // neither an allocation
 481     return (p1 != p2) && p1->is_Con() && p2->is_Con();
 482   } else if (a1 != NULL && a2 != NULL) {    // both allocations
 483     return (a1 != a2);
 484   } else if (a1 != NULL) {                  // one allocation a1
 485     // (Note:  p2->is_Con implies p2->in(0)->is_Root, which dominates.)
 486     return all_controls_dominate(p2, a1);
 487   } else { //(a2 != NULL)                   // one allocation a2
 488     return all_controls_dominate(p1, a2);
 489   }
 490   return false;
 491 }
 492 
 493 
 494 // Find an arraycopy that must have set (can_see_stored_value=true) or
 495 // could have set (can_see_stored_value=false) the value for this load
 496 Node* LoadNode::find_previous_arraycopy(PhaseTransform* phase, Node* ld_alloc, Node*& mem, bool can_see_stored_value) const {
 497   if (mem->is_Proj() && mem->in(0) != NULL && (mem->in(0)->Opcode() == Op_MemBarStoreStore ||
 498                                                mem->in(0)->Opcode() == Op_MemBarCPUOrder)) {
 499     Node* mb = mem->in(0);
 500     if (mb->in(0) != NULL && mb->in(0)->is_Proj() &&
 501         mb->in(0)->in(0) != NULL && mb->in(0)->in(0)->is_ArrayCopy()) {
 502       ArrayCopyNode* ac = mb->in(0)->in(0)->as_ArrayCopy();
 503       if (ac->is_clonebasic()) {
 504         intptr_t offset;
 505         AllocateNode* alloc = AllocateNode::Ideal_allocation(ac->in(ArrayCopyNode::Dest), phase, offset);
 506         assert(alloc != NULL && (!ReduceBulkZeroing || alloc->initialization()->is_complete_with_arraycopy()), "broken allocation");
 507         if (alloc == ld_alloc) {
 508           return ac;
 509         }
 510       }
 511     }
 512   } else if (mem->is_Proj() && mem->in(0) != NULL && mem->in(0)->is_ArrayCopy()) {
 513     ArrayCopyNode* ac = mem->in(0)->as_ArrayCopy();
 514 
 515     if (ac->is_arraycopy_validated() ||
 516         ac->is_copyof_validated() ||
 517         ac->is_copyofrange_validated()) {
 518       Node* ld_addp = in(MemNode::Address);
 519       if (ld_addp->is_AddP()) {
 520         Node* ld_base = ld_addp->in(AddPNode::Address);
 521         Node* ld_offs = ld_addp->in(AddPNode::Offset);
 522 
 523         Node* dest = ac->in(ArrayCopyNode::Dest);
 524 
 525         if (dest == ld_base) {
 526           const TypeX *ld_offs_t = phase->type(ld_offs)->isa_intptr_t();
 527           if (ac->modifies(ld_offs_t->_lo, ld_offs_t->_hi, phase, can_see_stored_value)) {
 528             return ac;
 529           }
 530           if (!can_see_stored_value) {
 531             mem = ac->in(TypeFunc::Memory);
 532           }
 533         }
 534       }
 535     }
 536   }
 537   return NULL;
 538 }
 539 
 540 // The logic for reordering loads and stores uses four steps:
 541 // (a) Walk carefully past stores and initializations which we
 542 //     can prove are independent of this load.
 543 // (b) Observe that the next memory state makes an exact match
 544 //     with self (load or store), and locate the relevant store.
 545 // (c) Ensure that, if we were to wire self directly to the store,
 546 //     the optimizer would fold it up somehow.
 547 // (d) Do the rewiring, and return, depending on some other part of
 548 //     the optimizer to fold up the load.
 549 // This routine handles steps (a) and (b).  Steps (c) and (d) are
 550 // specific to loads and stores, so they are handled by the callers.
 551 // (Currently, only LoadNode::Ideal has steps (c), (d).  More later.)
 552 //
 553 Node* MemNode::find_previous_store(PhaseTransform* phase) {
 554   Node*         ctrl   = in(MemNode::Control);
 555   Node*         adr    = in(MemNode::Address);
 556   intptr_t      offset = 0;
 557   Node*         base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
 558   AllocateNode* alloc  = AllocateNode::Ideal_allocation(base, phase);
 559 
 560   if (offset == Type::OffsetBot)
 561     return NULL;            // cannot unalias unless there are precise offsets
 562 
 563   const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
 564 
 565   intptr_t size_in_bytes = memory_size();
 566 
 567   Node* mem = in(MemNode::Memory);   // start searching here...
 568 
 569   int cnt = 50;             // Cycle limiter
 570   for (;;) {                // While we can dance past unrelated stores...
 571     if (--cnt < 0)  break;  // Caught in cycle or a complicated dance?
 572 
 573     Node* prev = mem;
 574     if (mem->is_Store()) {
 575       Node* st_adr = mem->in(MemNode::Address);
 576       intptr_t st_offset = 0;
 577       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
 578       if (st_base == NULL)
 579         break;              // inscrutable pointer
 580       if (st_offset != offset && st_offset != Type::OffsetBot) {
 581         const int MAX_STORE = BytesPerLong;
 582         if (st_offset >= offset + size_in_bytes ||
 583             st_offset <= offset - MAX_STORE ||
 584             st_offset <= offset - mem->as_Store()->memory_size()) {
 585           // Success:  The offsets are provably independent.
 586           // (You may ask, why not just test st_offset != offset and be done?
 587           // The answer is that stores of different sizes can co-exist
 588           // in the same sequence of RawMem effects.  We sometimes initialize
 589           // a whole 'tile' of array elements with a single jint or jlong.)
 590           mem = mem->in(MemNode::Memory);
 591           continue;           // (a) advance through independent store memory
 592         }
 593       }
 594       if (st_base != base &&
 595           detect_ptr_independence(base, alloc,
 596                                   st_base,
 597                                   AllocateNode::Ideal_allocation(st_base, phase),
 598                                   phase)) {
 599         // Success:  The bases are provably independent.
 600         mem = mem->in(MemNode::Memory);
 601         continue;           // (a) advance through independent store memory
 602       }
 603 
 604       // (b) At this point, if the bases or offsets do not agree, we lose,
 605       // since we have not managed to prove 'this' and 'mem' independent.
 606       if (st_base == base && st_offset == offset) {
 607         return mem;         // let caller handle steps (c), (d)
 608       }
 609 
 610     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
 611       InitializeNode* st_init = mem->in(0)->as_Initialize();
 612       AllocateNode*  st_alloc = st_init->allocation();
 613       if (st_alloc == NULL)
 614         break;              // something degenerated
 615       bool known_identical = false;
 616       bool known_independent = false;
 617       if (alloc == st_alloc)
 618         known_identical = true;
 619       else if (alloc != NULL)
 620         known_independent = true;
 621       else if (all_controls_dominate(this, st_alloc))
 622         known_independent = true;
 623 
 624       if (known_independent) {
 625         // The bases are provably independent: Either they are
 626         // manifestly distinct allocations, or else the control
 627         // of this load dominates the store's allocation.
 628         int alias_idx = phase->C->get_alias_index(adr_type());
 629         if (alias_idx == Compile::AliasIdxRaw) {
 630           mem = st_alloc->in(TypeFunc::Memory);
 631         } else {
 632           mem = st_init->memory(alias_idx);
 633         }
 634         continue;           // (a) advance through independent store memory
 635       }
 636 
 637       // (b) at this point, if we are not looking at a store initializing
 638       // the same allocation we are loading from, we lose.
 639       if (known_identical) {
 640         // From caller, can_see_stored_value will consult find_captured_store.
 641         return mem;         // let caller handle steps (c), (d)
 642       }
 643 
 644     } else if (find_previous_arraycopy(phase, alloc, mem, false) != NULL) {
 645       if (prev != mem) {
 646         // Found an arraycopy but it doesn't affect that load
 647         continue;
 648       }
 649       // Found an arraycopy that may affect that load
 650       return mem;
 651     } else if (addr_t != NULL && addr_t->is_known_instance_field()) {
 652       // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
 653       if (mem->is_Proj() && mem->in(0)->is_Call()) {
 654         // ArrayCopyNodes processed here as well.
 655         CallNode *call = mem->in(0)->as_Call();
 656         if (!call->may_modify(addr_t, phase)) {
 657           mem = call->in(TypeFunc::Memory);
 658           continue;         // (a) advance through independent call memory
 659         }
 660       } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
 661         ArrayCopyNode* ac = NULL;
 662         if (ArrayCopyNode::may_modify(addr_t, mem->in(0)->as_MemBar(), phase, ac)) {
 663           break;
 664         }
 665         mem = mem->in(0)->in(TypeFunc::Memory);
 666         continue;           // (a) advance through independent MemBar memory
 667       } else if (mem->is_ClearArray()) {
 668         if (ClearArrayNode::step_through(&mem, (uint)addr_t->instance_id(), phase)) {
 669           // (the call updated 'mem' value)
 670           continue;         // (a) advance through independent allocation memory
 671         } else {
 672           // Can not bypass initialization of the instance
 673           // we are looking for.
 674           return mem;
 675         }
 676       } else if (mem->is_MergeMem()) {
 677         int alias_idx = phase->C->get_alias_index(adr_type());
 678         mem = mem->as_MergeMem()->memory_at(alias_idx);
 679         continue;           // (a) advance through independent MergeMem memory
 680       }
 681     }
 682 
 683     // Unless there is an explicit 'continue', we must bail out here,
 684     // because 'mem' is an inscrutable memory state (e.g., a call).
 685     break;
 686   }
 687 
 688   return NULL;              // bail out
 689 }
 690 
 691 //----------------------calculate_adr_type-------------------------------------
 692 // Helper function.  Notices when the given type of address hits top or bottom.
 693 // Also, asserts a cross-check of the type against the expected address type.
 694 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
 695   if (t == Type::TOP)  return NULL; // does not touch memory any more?
 696   #ifdef PRODUCT
 697   cross_check = NULL;
 698   #else
 699   if (!VerifyAliases || is_error_reported() || Node::in_dump())  cross_check = NULL;
 700   #endif
 701   const TypePtr* tp = t->isa_ptr();
 702   if (tp == NULL) {
 703     assert(cross_check == NULL || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
 704     return TypePtr::BOTTOM;           // touches lots of memory
 705   } else {
 706     #ifdef ASSERT
 707     // %%%% [phh] We don't check the alias index if cross_check is
 708     //            TypeRawPtr::BOTTOM.  Needs to be investigated.
 709     if (cross_check != NULL &&
 710         cross_check != TypePtr::BOTTOM &&
 711         cross_check != TypeRawPtr::BOTTOM) {
 712       // Recheck the alias index, to see if it has changed (due to a bug).
 713       Compile* C = Compile::current();
 714       assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
 715              "must stay in the original alias category");
 716       // The type of the address must be contained in the adr_type,
 717       // disregarding "null"-ness.
 718       // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
 719       const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
 720       assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(),
 721              "real address must not escape from expected memory type");
 722     }
 723     #endif
 724     return tp;
 725   }
 726 }
 727 
 728 //=============================================================================
 729 // Should LoadNode::Ideal() attempt to remove control edges?
 730 bool LoadNode::can_remove_control() const {
 731   return true;
 732 }
 733 uint LoadNode::size_of() const { return sizeof(*this); }
 734 uint LoadNode::cmp( const Node &n ) const
 735 { return !Type::cmp( _type, ((LoadNode&)n)._type ); }
 736 const Type *LoadNode::bottom_type() const { return _type; }
 737 uint LoadNode::ideal_reg() const {
 738   return _type->ideal_reg();
 739 }
 740 
 741 #ifndef PRODUCT
 742 void LoadNode::dump_spec(outputStream *st) const {
 743   MemNode::dump_spec(st);
 744   if( !Verbose && !WizardMode ) {
 745     // standard dump does this in Verbose and WizardMode
 746     st->print(" #"); _type->dump_on(st);
 747   }
 748   if (!depends_only_on_test()) {
 749     st->print(" (does not depend only on test)");
 750   }
 751 }
 752 #endif
 753 
 754 #ifdef ASSERT
 755 //----------------------------is_immutable_value-------------------------------
 756 // Helper function to allow a raw load without control edge for some cases
 757 bool LoadNode::is_immutable_value(Node* adr) {
 758   return (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() &&
 759           adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
 760           (adr->in(AddPNode::Offset)->find_intptr_t_con(-1) ==
 761            in_bytes(JavaThread::osthread_offset())));
 762 }
 763 #endif
 764 
 765 //----------------------------LoadNode::make-----------------------------------
 766 // Polymorphic factory method:
 767 Node *LoadNode::make(PhaseGVN& gvn, Node *ctl, Node *mem, Node *adr, const TypePtr* adr_type, const Type *rt, BasicType bt, MemOrd mo,
 768                      ControlDependency control_dependency, bool unaligned, bool mismatched) {
 769   Compile* C = gvn.C;
 770 
 771   // sanity check the alias category against the created node type
 772   assert(!(adr_type->isa_oopptr() &&
 773            adr_type->offset() == oopDesc::klass_offset_in_bytes()),
 774          "use LoadKlassNode instead");
 775   assert(!(adr_type->isa_aryptr() &&
 776            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
 777          "use LoadRangeNode instead");
 778   // Check control edge of raw loads
 779   assert( ctl != NULL || C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
 780           // oop will be recorded in oop map if load crosses safepoint
 781           rt->isa_oopptr() || is_immutable_value(adr),
 782           "raw memory operations should have control edge");
 783   LoadNode* load = NULL;
 784   switch (bt) {
 785   case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 786   case T_BYTE:    load = new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 787   case T_INT:     load = new LoadINode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 788   case T_CHAR:    load = new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 789   case T_SHORT:   load = new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 790   case T_LONG:    load = new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency); break;
 791   case T_FLOAT:   load = new LoadFNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency); break;
 792   case T_DOUBLE:  load = new LoadDNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency); break;
 793   case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(),  mo, control_dependency); break;
 794   case T_OBJECT:
 795 #ifdef _LP64
 796     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 797       load = new LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency);
 798     } else
 799 #endif
 800     {
 801       assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop");
 802       load = new LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency);
 803     }
 804     break;
 805   }
 806   assert(load != NULL, "LoadNode should have been created");
 807   if (unaligned) {
 808     load->set_unaligned_access();
 809   }
 810   if (mismatched) {
 811     load->set_mismatched_access();
 812   }
 813   if (load->Opcode() == Op_LoadN) {
 814     Node* ld = gvn.transform(load);
 815     return new DecodeNNode(ld, ld->bottom_type()->make_ptr());
 816   }
 817 
 818   return load;
 819 }
 820 
 821 LoadLNode* LoadLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo,
 822                                   ControlDependency control_dependency, bool unaligned, bool mismatched) {
 823   bool require_atomic = true;
 824   LoadLNode* load = new LoadLNode(ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic);
 825   if (unaligned) {
 826     load->set_unaligned_access();
 827   }
 828   if (mismatched) {
 829     load->set_mismatched_access();
 830   }
 831   return load;
 832 }
 833 
 834 LoadDNode* LoadDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo,
 835                                   ControlDependency control_dependency, bool unaligned, bool mismatched) {
 836   bool require_atomic = true;
 837   LoadDNode* load = new LoadDNode(ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic);
 838   if (unaligned) {
 839     load->set_unaligned_access();
 840   }
 841   if (mismatched) {
 842     load->set_mismatched_access();
 843   }
 844   return load;
 845 }
 846 
 847 
 848 
 849 //------------------------------hash-------------------------------------------
 850 uint LoadNode::hash() const {
 851   // unroll addition of interesting fields
 852   return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
 853 }
 854 
 855 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) {
 856   if ((atp != NULL) && (atp->index() >= Compile::AliasIdxRaw)) {
 857     bool non_volatile = (atp->field() != NULL) && !atp->field()->is_volatile();
 858     bool is_stable_ary = FoldStableValues &&
 859                          (tp != NULL) && (tp->isa_aryptr() != NULL) &&
 860                          tp->isa_aryptr()->is_stable();
 861 
 862     return (eliminate_boxing && non_volatile) || is_stable_ary;
 863   }
 864 
 865   return false;
 866 }
 867 
 868 // Is the value loaded previously stored by an arraycopy? If so return
 869 // a load node that reads from the source array so we may be able to
 870 // optimize out the ArrayCopy node later.
 871 Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseTransform* phase) const {
 872   Node* ld_adr = in(MemNode::Address);
 873   intptr_t ld_off = 0;
 874   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
 875   Node* ac = find_previous_arraycopy(phase, ld_alloc, st, true);
 876   if (ac != NULL) {
 877     assert(ac->is_ArrayCopy(), "what kind of node can this be?");
 878 
 879     Node* ld = clone();
 880     if (ac->as_ArrayCopy()->is_clonebasic()) {
 881       assert(ld_alloc != NULL, "need an alloc");
 882       Node* addp = in(MemNode::Address)->clone();
 883       assert(addp->is_AddP(), "address must be addp");
 884       assert(addp->in(AddPNode::Base) == ac->in(ArrayCopyNode::Dest)->in(AddPNode::Base), "strange pattern");
 885       assert(addp->in(AddPNode::Address) == ac->in(ArrayCopyNode::Dest)->in(AddPNode::Address), "strange pattern");
 886       addp->set_req(AddPNode::Base, ac->in(ArrayCopyNode::Src)->in(AddPNode::Base));
 887       addp->set_req(AddPNode::Address, ac->in(ArrayCopyNode::Src)->in(AddPNode::Address));
 888       ld->set_req(MemNode::Address, phase->transform(addp));
 889       if (in(0) != NULL) {
 890         assert(ld_alloc->in(0) != NULL, "alloc must have control");
 891         ld->set_req(0, ld_alloc->in(0));
 892       }
 893     } else {
 894       Node* addp = in(MemNode::Address)->clone();
 895       assert(addp->in(AddPNode::Base) == addp->in(AddPNode::Address), "should be");
 896       addp->set_req(AddPNode::Base, ac->in(ArrayCopyNode::Src));
 897       addp->set_req(AddPNode::Address, ac->in(ArrayCopyNode::Src));
 898 
 899       const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr();
 900       BasicType ary_elem  = ary_t->klass()->as_array_klass()->element_type()->basic_type();
 901       uint header = arrayOopDesc::base_offset_in_bytes(ary_elem);
 902       uint shift  = exact_log2(type2aelembytes(ary_elem));
 903 
 904       Node* diff = phase->transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 905 #ifdef _LP64
 906       diff = phase->transform(new ConvI2LNode(diff));
 907 #endif
 908       diff = phase->transform(new LShiftXNode(diff, phase->intcon(shift)));
 909 
 910       Node* offset = phase->transform(new AddXNode(addp->in(AddPNode::Offset), diff));
 911       addp->set_req(AddPNode::Offset, offset);
 912       ld->set_req(MemNode::Address, phase->transform(addp));
 913 
 914       if (in(0) != NULL) {
 915         assert(ac->in(0) != NULL, "alloc must have control");
 916         ld->set_req(0, ac->in(0));
 917       }
 918     }
 919     // load depends on the tests that validate the arraycopy
 920     ld->as_Load()->_control_dependency = Pinned;
 921     return ld;
 922   }
 923   return NULL;
 924 }
 925 
 926 
 927 //---------------------------can_see_stored_value------------------------------
 928 // This routine exists to make sure this set of tests is done the same
 929 // everywhere.  We need to make a coordinated change: first LoadNode::Ideal
 930 // will change the graph shape in a way which makes memory alive twice at the
 931 // same time (uses the Oracle model of aliasing), then some
 932 // LoadXNode::Identity will fold things back to the equivalence-class model
 933 // of aliasing.
 934 Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
 935   Node* ld_adr = in(MemNode::Address);
 936   intptr_t ld_off = 0;
 937   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
 938   const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
 939   Compile::AliasType* atp = (tp != NULL) ? phase->C->alias_type(tp) : NULL;
 940   // This is more general than load from boxing objects.
 941   if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) {
 942     uint alias_idx = atp->index();
 943     bool final = !atp->is_rewritable();
 944     Node* result = NULL;
 945     Node* current = st;
 946     // Skip through chains of MemBarNodes checking the MergeMems for
 947     // new states for the slice of this load.  Stop once any other
 948     // kind of node is encountered.  Loads from final memory can skip
 949     // through any kind of MemBar but normal loads shouldn't skip
 950     // through MemBarAcquire since the could allow them to move out of
 951     // a synchronized region.
 952     while (current->is_Proj()) {
 953       int opc = current->in(0)->Opcode();
 954       if ((final && (opc == Op_MemBarAcquire ||
 955                      opc == Op_MemBarAcquireLock ||
 956                      opc == Op_LoadFence)) ||
 957           opc == Op_MemBarRelease ||
 958           opc == Op_StoreFence ||
 959           opc == Op_MemBarReleaseLock ||
 960           opc == Op_MemBarStoreStore ||
 961           opc == Op_MemBarCPUOrder) {
 962         Node* mem = current->in(0)->in(TypeFunc::Memory);
 963         if (mem->is_MergeMem()) {
 964           MergeMemNode* merge = mem->as_MergeMem();
 965           Node* new_st = merge->memory_at(alias_idx);
 966           if (new_st == merge->base_memory()) {
 967             // Keep searching
 968             current = new_st;
 969             continue;
 970           }
 971           // Save the new memory state for the slice and fall through
 972           // to exit.
 973           result = new_st;
 974         }
 975       }
 976       break;
 977     }
 978     if (result != NULL) {
 979       st = result;
 980     }
 981   }
 982 
 983   // Loop around twice in the case Load -> Initialize -> Store.
 984   // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
 985   for (int trip = 0; trip <= 1; trip++) {
 986 
 987     if (st->is_Store()) {
 988       Node* st_adr = st->in(MemNode::Address);
 989       if (!phase->eqv(st_adr, ld_adr)) {
 990         // Try harder before giving up...  Match raw and non-raw pointers.
 991         intptr_t st_off = 0;
 992         AllocateNode* alloc = AllocateNode::Ideal_allocation(st_adr, phase, st_off);
 993         if (alloc == NULL)       return NULL;
 994         if (alloc != ld_alloc)   return NULL;
 995         if (ld_off != st_off)    return NULL;
 996         // At this point we have proven something like this setup:
 997         //  A = Allocate(...)
 998         //  L = LoadQ(,  AddP(CastPP(, A.Parm),, #Off))
 999         //  S = StoreQ(, AddP(,        A.Parm  , #Off), V)
1000         // (Actually, we haven't yet proven the Q's are the same.)
1001         // In other words, we are loading from a casted version of
1002         // the same pointer-and-offset that we stored to.
1003         // Thus, we are able to replace L by V.
1004       }
1005       // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
1006       if (store_Opcode() != st->Opcode())
1007         return NULL;
1008       return st->in(MemNode::ValueIn);
1009     }
1010 
1011     // A load from a freshly-created object always returns zero.
1012     // (This can happen after LoadNode::Ideal resets the load's memory input
1013     // to find_captured_store, which returned InitializeNode::zero_memory.)
1014     if (st->is_Proj() && st->in(0)->is_Allocate() &&
1015         (st->in(0) == ld_alloc) &&
1016         (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) {
1017       // return a zero value for the load's basic type
1018       // (This is one of the few places where a generic PhaseTransform
1019       // can create new nodes.  Think of it as lazily manifesting
1020       // virtually pre-existing constants.)
1021       return phase->zerocon(memory_type());
1022     }
1023 
1024     // A load from an initialization barrier can match a captured store.
1025     if (st->is_Proj() && st->in(0)->is_Initialize()) {
1026       InitializeNode* init = st->in(0)->as_Initialize();
1027       AllocateNode* alloc = init->allocation();
1028       if ((alloc != NULL) && (alloc == ld_alloc)) {
1029         // examine a captured store value
1030         st = init->find_captured_store(ld_off, memory_size(), phase);
1031         if (st != NULL) {
1032           continue;             // take one more trip around
1033         }
1034       }
1035     }
1036 
1037     // Load boxed value from result of valueOf() call is input parameter.
1038     if (this->is_Load() && ld_adr->is_AddP() &&
1039         (tp != NULL) && tp->is_ptr_to_boxed_value()) {
1040       intptr_t ignore = 0;
1041       Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore);
1042       if (base != NULL && base->is_Proj() &&
1043           base->as_Proj()->_con == TypeFunc::Parms &&
1044           base->in(0)->is_CallStaticJava() &&
1045           base->in(0)->as_CallStaticJava()->is_boxing_method()) {
1046         return base->in(0)->in(TypeFunc::Parms);
1047       }
1048     }
1049 
1050     break;
1051   }
1052 
1053   return NULL;
1054 }
1055 
1056 //----------------------is_instance_field_load_with_local_phi------------------
1057 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
1058   if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl &&
1059       in(Address)->is_AddP() ) {
1060     const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr();
1061     // Only instances and boxed values.
1062     if( t_oop != NULL &&
1063         (t_oop->is_ptr_to_boxed_value() ||
1064          t_oop->is_known_instance_field()) &&
1065         t_oop->offset() != Type::OffsetBot &&
1066         t_oop->offset() != Type::OffsetTop) {
1067       return true;
1068     }
1069   }
1070   return false;
1071 }
1072 
1073 //------------------------------Identity---------------------------------------
1074 // Loads are identity if previous store is to same address
1075 Node* LoadNode::Identity(PhaseGVN* phase) {
1076   // If the previous store-maker is the right kind of Store, and the store is
1077   // to the same address, then we are equal to the value stored.
1078   Node* mem = in(Memory);
1079   Node* value = can_see_stored_value(mem, phase);
1080   if( value ) {
1081     // byte, short & char stores truncate naturally.
1082     // A load has to load the truncated value which requires
1083     // some sort of masking operation and that requires an
1084     // Ideal call instead of an Identity call.
1085     if (memory_size() < BytesPerInt) {
1086       // If the input to the store does not fit with the load's result type,
1087       // it must be truncated via an Ideal call.
1088       if (!phase->type(value)->higher_equal(phase->type(this)))
1089         return this;
1090     }
1091     // (This works even when value is a Con, but LoadNode::Value
1092     // usually runs first, producing the singleton type of the Con.)
1093     return value;
1094   }
1095 
1096   // Search for an existing data phi which was generated before for the same
1097   // instance's field to avoid infinite generation of phis in a loop.
1098   Node *region = mem->in(0);
1099   if (is_instance_field_load_with_local_phi(region)) {
1100     const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr();
1101     int this_index  = phase->C->get_alias_index(addr_t);
1102     int this_offset = addr_t->offset();
1103     int this_iid    = addr_t->instance_id();
1104     if (!addr_t->is_known_instance() &&
1105          addr_t->is_ptr_to_boxed_value()) {
1106       // Use _idx of address base (could be Phi node) for boxed values.
1107       intptr_t   ignore = 0;
1108       Node*      base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1109       this_iid = base->_idx;
1110     }
1111     const Type* this_type = bottom_type();
1112     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1113       Node* phi = region->fast_out(i);
1114       if (phi->is_Phi() && phi != mem &&
1115           phi->as_Phi()->is_same_inst_field(this_type, this_iid, this_index, this_offset)) {
1116         return phi;
1117       }
1118     }
1119   }
1120 
1121   return this;
1122 }
1123 
1124 // Construct an equivalent unsigned load.
1125 Node* LoadNode::convert_to_unsigned_load(PhaseGVN& gvn) {
1126   BasicType bt = T_ILLEGAL;
1127   const Type* rt = NULL;
1128   switch (Opcode()) {
1129     case Op_LoadUB: return this;
1130     case Op_LoadUS: return this;
1131     case Op_LoadB: bt = T_BOOLEAN; rt = TypeInt::UBYTE; break;
1132     case Op_LoadS: bt = T_CHAR;    rt = TypeInt::CHAR;  break;
1133     default:
1134       assert(false, "no unsigned variant: %s", Name());
1135       return NULL;
1136   }
1137   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1138                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1139                         is_unaligned_access(), is_mismatched_access());
1140 }
1141 
1142 // Construct an equivalent signed load.
1143 Node* LoadNode::convert_to_signed_load(PhaseGVN& gvn) {
1144   BasicType bt = T_ILLEGAL;
1145   const Type* rt = NULL;
1146   switch (Opcode()) {
1147     case Op_LoadUB: bt = T_BYTE;  rt = TypeInt::BYTE;  break;
1148     case Op_LoadUS: bt = T_SHORT; rt = TypeInt::SHORT; break;
1149     case Op_LoadB: // fall through
1150     case Op_LoadS: // fall through
1151     case Op_LoadI: // fall through
1152     case Op_LoadL: return this;
1153     default:
1154       assert(false, "no signed variant: %s", Name());
1155       return NULL;
1156   }
1157   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1158                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1159                         is_unaligned_access(), is_mismatched_access());
1160 }
1161 
1162 // We're loading from an object which has autobox behaviour.
1163 // If this object is result of a valueOf call we'll have a phi
1164 // merging a newly allocated object and a load from the cache.
1165 // We want to replace this load with the original incoming
1166 // argument to the valueOf call.
1167 Node* LoadNode::eliminate_autobox(PhaseGVN* phase) {
1168   assert(phase->C->eliminate_boxing(), "sanity");
1169   intptr_t ignore = 0;
1170   Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1171   if ((base == NULL) || base->is_Phi()) {
1172     // Push the loads from the phi that comes from valueOf up
1173     // through it to allow elimination of the loads and the recovery
1174     // of the original value. It is done in split_through_phi().
1175     return NULL;
1176   } else if (base->is_Load() ||
1177              base->is_DecodeN() && base->in(1)->is_Load()) {
1178     // Eliminate the load of boxed value for integer types from the cache
1179     // array by deriving the value from the index into the array.
1180     // Capture the offset of the load and then reverse the computation.
1181 
1182     // Get LoadN node which loads a boxing object from 'cache' array.
1183     if (base->is_DecodeN()) {
1184       base = base->in(1);
1185     }
1186     if (!base->in(Address)->is_AddP()) {
1187       return NULL; // Complex address
1188     }
1189     AddPNode* address = base->in(Address)->as_AddP();
1190     Node* cache_base = address->in(AddPNode::Base);
1191     if ((cache_base != NULL) && cache_base->is_DecodeN()) {
1192       // Get ConP node which is static 'cache' field.
1193       cache_base = cache_base->in(1);
1194     }
1195     if ((cache_base != NULL) && cache_base->is_Con()) {
1196       const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr();
1197       if ((base_type != NULL) && base_type->is_autobox_cache()) {
1198         Node* elements[4];
1199         int shift = exact_log2(type2aelembytes(T_OBJECT));
1200         int count = address->unpack_offsets(elements, ARRAY_SIZE(elements));
1201         if ((count >  0) && elements[0]->is_Con() &&
1202             ((count == 1) ||
1203              (count == 2) && elements[1]->Opcode() == Op_LShiftX &&
1204                              elements[1]->in(2) == phase->intcon(shift))) {
1205           ciObjArray* array = base_type->const_oop()->as_obj_array();
1206           // Fetch the box object cache[0] at the base of the array and get its value
1207           ciInstance* box = array->obj_at(0)->as_instance();
1208           ciInstanceKlass* ik = box->klass()->as_instance_klass();
1209           assert(ik->is_box_klass(), "sanity");
1210           assert(ik->nof_nonstatic_fields() == 1, "change following code");
1211           if (ik->nof_nonstatic_fields() == 1) {
1212             // This should be true nonstatic_field_at requires calling
1213             // nof_nonstatic_fields so check it anyway
1214             ciConstant c = box->field_value(ik->nonstatic_field_at(0));
1215             BasicType bt = c.basic_type();
1216             // Only integer types have boxing cache.
1217             assert(bt == T_BOOLEAN || bt == T_CHAR  ||
1218                    bt == T_BYTE    || bt == T_SHORT ||
1219                    bt == T_INT     || bt == T_LONG, "wrong type = %s", type2name(bt));
1220             jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int();
1221             if (cache_low != (int)cache_low) {
1222               return NULL; // should not happen since cache is array indexed by value
1223             }
1224             jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift);
1225             if (offset != (int)offset) {
1226               return NULL; // should not happen since cache is array indexed by value
1227             }
1228            // Add up all the offsets making of the address of the load
1229             Node* result = elements[0];
1230             for (int i = 1; i < count; i++) {
1231               result = phase->transform(new AddXNode(result, elements[i]));
1232             }
1233             // Remove the constant offset from the address and then
1234             result = phase->transform(new AddXNode(result, phase->MakeConX(-(int)offset)));
1235             // remove the scaling of the offset to recover the original index.
1236             if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) {
1237               // Peel the shift off directly but wrap it in a dummy node
1238               // since Ideal can't return existing nodes
1239               result = new RShiftXNode(result->in(1), phase->intcon(0));
1240             } else if (result->is_Add() && result->in(2)->is_Con() &&
1241                        result->in(1)->Opcode() == Op_LShiftX &&
1242                        result->in(1)->in(2) == phase->intcon(shift)) {
1243               // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z)
1244               // but for boxing cache access we know that X<<Z will not overflow
1245               // (there is range check) so we do this optimizatrion by hand here.
1246               Node* add_con = new RShiftXNode(result->in(2), phase->intcon(shift));
1247               result = new AddXNode(result->in(1)->in(1), phase->transform(add_con));
1248             } else {
1249               result = new RShiftXNode(result, phase->intcon(shift));
1250             }
1251 #ifdef _LP64
1252             if (bt != T_LONG) {
1253               result = new ConvL2INode(phase->transform(result));
1254             }
1255 #else
1256             if (bt == T_LONG) {
1257               result = new ConvI2LNode(phase->transform(result));
1258             }
1259 #endif
1260             // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
1261             // Need to preserve unboxing load type if it is unsigned.
1262             switch(this->Opcode()) {
1263               case Op_LoadUB:
1264                 result = new AndINode(phase->transform(result), phase->intcon(0xFF));
1265                 break;
1266               case Op_LoadUS:
1267                 result = new AndINode(phase->transform(result), phase->intcon(0xFFFF));
1268                 break;
1269             }
1270             return result;
1271           }
1272         }
1273       }
1274     }
1275   }
1276   return NULL;
1277 }
1278 
1279 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) {
1280   Node* region = phi->in(0);
1281   if (region == NULL) {
1282     return false; // Wait stable graph
1283   }
1284   uint cnt = phi->req();
1285   for (uint i = 1; i < cnt; i++) {
1286     Node* rc = region->in(i);
1287     if (rc == NULL || phase->type(rc) == Type::TOP)
1288       return false; // Wait stable graph
1289     Node* in = phi->in(i);
1290     if (in == NULL || phase->type(in) == Type::TOP)
1291       return false; // Wait stable graph
1292   }
1293   return true;
1294 }
1295 //------------------------------split_through_phi------------------------------
1296 // Split instance or boxed field load through Phi.
1297 Node *LoadNode::split_through_phi(PhaseGVN *phase) {
1298   Node* mem     = in(Memory);
1299   Node* address = in(Address);
1300   const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr();
1301 
1302   assert((t_oop != NULL) &&
1303          (t_oop->is_known_instance_field() ||
1304           t_oop->is_ptr_to_boxed_value()), "invalide conditions");
1305 
1306   Compile* C = phase->C;
1307   intptr_t ignore = 0;
1308   Node*    base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1309   bool base_is_phi = (base != NULL) && base->is_Phi();
1310   bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() &&
1311                            (base != NULL) && (base == address->in(AddPNode::Base)) &&
1312                            phase->type(base)->higher_equal(TypePtr::NOTNULL);
1313 
1314   if (!((mem->is_Phi() || base_is_phi) &&
1315         (load_boxed_values || t_oop->is_known_instance_field()))) {
1316     return NULL; // memory is not Phi
1317   }
1318 
1319   if (mem->is_Phi()) {
1320     if (!stable_phi(mem->as_Phi(), phase)) {
1321       return NULL; // Wait stable graph
1322     }
1323     uint cnt = mem->req();
1324     // Check for loop invariant memory.
1325     if (cnt == 3) {
1326       for (uint i = 1; i < cnt; i++) {
1327         Node* in = mem->in(i);
1328         Node*  m = optimize_memory_chain(in, t_oop, this, phase);
1329         if (m == mem) {
1330           set_req(Memory, mem->in(cnt - i));
1331           return this; // made change
1332         }
1333       }
1334     }
1335   }
1336   if (base_is_phi) {
1337     if (!stable_phi(base->as_Phi(), phase)) {
1338       return NULL; // Wait stable graph
1339     }
1340     uint cnt = base->req();
1341     // Check for loop invariant memory.
1342     if (cnt == 3) {
1343       for (uint i = 1; i < cnt; i++) {
1344         if (base->in(i) == base) {
1345           return NULL; // Wait stable graph
1346         }
1347       }
1348     }
1349   }
1350 
1351   bool load_boxed_phi = load_boxed_values && base_is_phi && (base->in(0) == mem->in(0));
1352 
1353   // Split through Phi (see original code in loopopts.cpp).
1354   assert(C->have_alias_type(t_oop), "instance should have alias type");
1355 
1356   // Do nothing here if Identity will find a value
1357   // (to avoid infinite chain of value phis generation).
1358   if (!phase->eqv(this, this->Identity(phase)))
1359     return NULL;
1360 
1361   // Select Region to split through.
1362   Node* region;
1363   if (!base_is_phi) {
1364     assert(mem->is_Phi(), "sanity");
1365     region = mem->in(0);
1366     // Skip if the region dominates some control edge of the address.
1367     if (!MemNode::all_controls_dominate(address, region))
1368       return NULL;
1369   } else if (!mem->is_Phi()) {
1370     assert(base_is_phi, "sanity");
1371     region = base->in(0);
1372     // Skip if the region dominates some control edge of the memory.
1373     if (!MemNode::all_controls_dominate(mem, region))
1374       return NULL;
1375   } else if (base->in(0) != mem->in(0)) {
1376     assert(base_is_phi && mem->is_Phi(), "sanity");
1377     if (MemNode::all_controls_dominate(mem, base->in(0))) {
1378       region = base->in(0);
1379     } else if (MemNode::all_controls_dominate(address, mem->in(0))) {
1380       region = mem->in(0);
1381     } else {
1382       return NULL; // complex graph
1383     }
1384   } else {
1385     assert(base->in(0) == mem->in(0), "sanity");
1386     region = mem->in(0);
1387   }
1388 
1389   const Type* this_type = this->bottom_type();
1390   int this_index  = C->get_alias_index(t_oop);
1391   int this_offset = t_oop->offset();
1392   int this_iid    = t_oop->instance_id();
1393   if (!t_oop->is_known_instance() && load_boxed_values) {
1394     // Use _idx of address base for boxed values.
1395     this_iid = base->_idx;
1396   }
1397   PhaseIterGVN* igvn = phase->is_IterGVN();
1398   Node* phi = new PhiNode(region, this_type, NULL, this_iid, this_index, this_offset);
1399   for (uint i = 1; i < region->req(); i++) {
1400     Node* x;
1401     Node* the_clone = NULL;
1402     if (region->in(i) == C->top()) {
1403       x = C->top();      // Dead path?  Use a dead data op
1404     } else {
1405       x = this->clone();        // Else clone up the data op
1406       the_clone = x;            // Remember for possible deletion.
1407       // Alter data node to use pre-phi inputs
1408       if (this->in(0) == region) {
1409         x->set_req(0, region->in(i));
1410       } else {
1411         x->set_req(0, NULL);
1412       }
1413       if (mem->is_Phi() && (mem->in(0) == region)) {
1414         x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone.
1415       }
1416       if (address->is_Phi() && address->in(0) == region) {
1417         x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone
1418       }
1419       if (base_is_phi && (base->in(0) == region)) {
1420         Node* base_x = base->in(i); // Clone address for loads from boxed objects.
1421         Node* adr_x = phase->transform(new AddPNode(base_x,base_x,address->in(AddPNode::Offset)));
1422         x->set_req(Address, adr_x);
1423       }
1424     }
1425     // Check for a 'win' on some paths
1426     const Type *t = x->Value(igvn);
1427 
1428     bool singleton = t->singleton();
1429 
1430     // See comments in PhaseIdealLoop::split_thru_phi().
1431     if (singleton && t == Type::TOP) {
1432       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
1433     }
1434 
1435     if (singleton) {
1436       x = igvn->makecon(t);
1437     } else {
1438       // We now call Identity to try to simplify the cloned node.
1439       // Note that some Identity methods call phase->type(this).
1440       // Make sure that the type array is big enough for
1441       // our new node, even though we may throw the node away.
1442       // (This tweaking with igvn only works because x is a new node.)
1443       igvn->set_type(x, t);
1444       // If x is a TypeNode, capture any more-precise type permanently into Node
1445       // otherwise it will be not updated during igvn->transform since
1446       // igvn->type(x) is set to x->Value() already.
1447       x->raise_bottom_type(t);
1448       Node *y = x->Identity(igvn);
1449       if (y != x) {
1450         x = y;
1451       } else {
1452         y = igvn->hash_find_insert(x);
1453         if (y) {
1454           x = y;
1455         } else {
1456           // Else x is a new node we are keeping
1457           // We do not need register_new_node_with_optimizer
1458           // because set_type has already been called.
1459           igvn->_worklist.push(x);
1460         }
1461       }
1462     }
1463     if (x != the_clone && the_clone != NULL) {
1464       igvn->remove_dead_node(the_clone);
1465     }
1466     phi->set_req(i, x);
1467   }
1468   // Record Phi
1469   igvn->register_new_node_with_optimizer(phi);
1470   return phi;
1471 }
1472 
1473 //------------------------------Ideal------------------------------------------
1474 // If the load is from Field memory and the pointer is non-null, it might be possible to
1475 // zero out the control input.
1476 // If the offset is constant and the base is an object allocation,
1477 // try to hook me up to the exact initializing store.
1478 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1479   Node* p = MemNode::Ideal_common(phase, can_reshape);
1480   if (p)  return (p == NodeSentinel) ? NULL : p;
1481 
1482   Node* ctrl    = in(MemNode::Control);
1483   Node* address = in(MemNode::Address);
1484   bool progress = false;
1485 
1486   // Skip up past a SafePoint control.  Cannot do this for Stores because
1487   // pointer stores & cardmarks must stay on the same side of a SafePoint.
1488   if( ctrl != NULL && ctrl->Opcode() == Op_SafePoint &&
1489       phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw ) {
1490     ctrl = ctrl->in(0);
1491     set_req(MemNode::Control,ctrl);
1492     progress = true;
1493   }
1494 
1495   intptr_t ignore = 0;
1496   Node*    base   = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1497   if (base != NULL
1498       && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) {
1499     // Check for useless control edge in some common special cases
1500     if (in(MemNode::Control) != NULL
1501         && can_remove_control()
1502         && phase->type(base)->higher_equal(TypePtr::NOTNULL)
1503         && all_controls_dominate(base, phase->C->start())) {
1504       // A method-invariant, non-null address (constant or 'this' argument).
1505       set_req(MemNode::Control, NULL);
1506       progress = true;
1507     }
1508   }
1509 
1510   Node* mem = in(MemNode::Memory);
1511   const TypePtr *addr_t = phase->type(address)->isa_ptr();
1512 
1513   if (can_reshape && (addr_t != NULL)) {
1514     // try to optimize our memory input
1515     Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase);
1516     if (opt_mem != mem) {
1517       set_req(MemNode::Memory, opt_mem);
1518       if (phase->type( opt_mem ) == Type::TOP) return NULL;
1519       return this;
1520     }
1521     const TypeOopPtr *t_oop = addr_t->isa_oopptr();
1522     if ((t_oop != NULL) &&
1523         (t_oop->is_known_instance_field() ||
1524          t_oop->is_ptr_to_boxed_value())) {
1525       PhaseIterGVN *igvn = phase->is_IterGVN();
1526       if (igvn != NULL && igvn->_worklist.member(opt_mem)) {
1527         // Delay this transformation until memory Phi is processed.
1528         phase->is_IterGVN()->_worklist.push(this);
1529         return NULL;
1530       }
1531       // Split instance field load through Phi.
1532       Node* result = split_through_phi(phase);
1533       if (result != NULL) return result;
1534 
1535       if (t_oop->is_ptr_to_boxed_value()) {
1536         Node* result = eliminate_autobox(phase);
1537         if (result != NULL) return result;
1538       }
1539     }
1540   }
1541 
1542   // Is there a dominating load that loads the same value?  Leave
1543   // anything that is not a load of a field/array element (like
1544   // barriers etc.) alone
1545   if (in(0) != NULL && adr_type() != TypeRawPtr::BOTTOM && can_reshape) {
1546     for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
1547       Node *use = mem->fast_out(i);
1548       if (use != this &&
1549           use->Opcode() == Opcode() &&
1550           use->in(0) != NULL &&
1551           use->in(0) != in(0) &&
1552           use->in(Address) == in(Address)) {
1553         Node* ctl = in(0);
1554         for (int i = 0; i < 10 && ctl != NULL; i++) {
1555           ctl = IfNode::up_one_dom(ctl);
1556           if (ctl == use->in(0)) {
1557             set_req(0, use->in(0));
1558             return this;
1559           }
1560         }
1561       }
1562     }
1563   }
1564 
1565   // Check for prior store with a different base or offset; make Load
1566   // independent.  Skip through any number of them.  Bail out if the stores
1567   // are in an endless dead cycle and report no progress.  This is a key
1568   // transform for Reflection.  However, if after skipping through the Stores
1569   // we can't then fold up against a prior store do NOT do the transform as
1570   // this amounts to using the 'Oracle' model of aliasing.  It leaves the same
1571   // array memory alive twice: once for the hoisted Load and again after the
1572   // bypassed Store.  This situation only works if EVERYBODY who does
1573   // anti-dependence work knows how to bypass.  I.e. we need all
1574   // anti-dependence checks to ask the same Oracle.  Right now, that Oracle is
1575   // the alias index stuff.  So instead, peek through Stores and IFF we can
1576   // fold up, do so.
1577   Node* prev_mem = find_previous_store(phase);
1578   if (prev_mem != NULL) {
1579     Node* value = can_see_arraycopy_value(prev_mem, phase);
1580     if (value != NULL) {
1581       return value;
1582     }
1583   }
1584   // Steps (a), (b):  Walk past independent stores to find an exact match.
1585   if (prev_mem != NULL && prev_mem != in(MemNode::Memory)) {
1586     // (c) See if we can fold up on the spot, but don't fold up here.
1587     // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or
1588     // just return a prior value, which is done by Identity calls.
1589     if (can_see_stored_value(prev_mem, phase)) {
1590       // Make ready for step (d):
1591       set_req(MemNode::Memory, prev_mem);
1592       return this;
1593     }
1594   }
1595 
1596   return progress ? this : NULL;
1597 }
1598 
1599 // Helper to recognize certain Klass fields which are invariant across
1600 // some group of array types (e.g., int[] or all T[] where T < Object).
1601 const Type*
1602 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
1603                                  ciKlass* klass) const {
1604   if (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) {
1605     // The field is Klass::_modifier_flags.  Return its (constant) value.
1606     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
1607     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
1608     return TypeInt::make(klass->modifier_flags());
1609   }
1610   if (tkls->offset() == in_bytes(Klass::access_flags_offset())) {
1611     // The field is Klass::_access_flags.  Return its (constant) value.
1612     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
1613     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
1614     return TypeInt::make(klass->access_flags());
1615   }
1616   if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
1617     // The field is Klass::_layout_helper.  Return its constant value if known.
1618     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
1619     return TypeInt::make(klass->layout_helper());
1620   }
1621 
1622   // No match.
1623   return NULL;
1624 }
1625 
1626 //------------------------------Value-----------------------------------------
1627 const Type* LoadNode::Value(PhaseGVN* phase) const {
1628   // Either input is TOP ==> the result is TOP
1629   Node* mem = in(MemNode::Memory);
1630   const Type *t1 = phase->type(mem);
1631   if (t1 == Type::TOP)  return Type::TOP;
1632   Node* adr = in(MemNode::Address);
1633   const TypePtr* tp = phase->type(adr)->isa_ptr();
1634   if (tp == NULL || tp->empty())  return Type::TOP;
1635   int off = tp->offset();
1636   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
1637   Compile* C = phase->C;
1638 
1639   // Try to guess loaded type from pointer type
1640   if (tp->isa_aryptr()) {
1641     const TypeAryPtr* ary = tp->is_aryptr();
1642     const Type* t = ary->elem();
1643 
1644     // Determine whether the reference is beyond the header or not, by comparing
1645     // the offset against the offset of the start of the array's data.
1646     // Different array types begin at slightly different offsets (12 vs. 16).
1647     // We choose T_BYTE as an example base type that is least restrictive
1648     // as to alignment, which will therefore produce the smallest
1649     // possible base offset.
1650     const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1651     const bool off_beyond_header = ((uint)off >= (uint)min_base_off);
1652 
1653     // Try to constant-fold a stable array element.
1654     if (FoldStableValues && !is_mismatched_access() && ary->is_stable()) {
1655       // Make sure the reference is not into the header and the offset is constant
1656       ciObject* aobj = ary->const_oop();
1657       if (aobj != NULL && off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
1658         int stable_dimension = (ary->stable_dimension() > 0 ? ary->stable_dimension() - 1 : 0);
1659         const Type* con_type = Type::make_constant_from_array_element(aobj->as_array(), off,
1660                                                                       stable_dimension,
1661                                                                       memory_type(), is_unsigned());
1662         if (con_type != NULL) {
1663           return con_type;
1664         }
1665       }
1666     }
1667 
1668     // Don't do this for integer types. There is only potential profit if
1669     // the element type t is lower than _type; that is, for int types, if _type is
1670     // more restrictive than t.  This only happens here if one is short and the other
1671     // char (both 16 bits), and in those cases we've made an intentional decision
1672     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
1673     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
1674     //
1675     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
1676     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
1677     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
1678     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
1679     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
1680     // In fact, that could have been the original type of p1, and p1 could have
1681     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
1682     // expression (LShiftL quux 3) independently optimized to the constant 8.
1683     if ((t->isa_int() == NULL) && (t->isa_long() == NULL)
1684         && (_type->isa_vect() == NULL)
1685         && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
1686       // t might actually be lower than _type, if _type is a unique
1687       // concrete subclass of abstract class t.
1688       if (off_beyond_header) {  // is the offset beyond the header?
1689         const Type* jt = t->join_speculative(_type);
1690         // In any case, do not allow the join, per se, to empty out the type.
1691         if (jt->empty() && !t->empty()) {
1692           // This can happen if a interface-typed array narrows to a class type.
1693           jt = _type;
1694         }
1695 #ifdef ASSERT
1696         if (phase->C->eliminate_boxing() && adr->is_AddP()) {
1697           // The pointers in the autobox arrays are always non-null
1698           Node* base = adr->in(AddPNode::Base);
1699           if ((base != NULL) && base->is_DecodeN()) {
1700             // Get LoadN node which loads IntegerCache.cache field
1701             base = base->in(1);
1702           }
1703           if ((base != NULL) && base->is_Con()) {
1704             const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
1705             if ((base_type != NULL) && base_type->is_autobox_cache()) {
1706               // It could be narrow oop
1707               assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
1708             }
1709           }
1710         }
1711 #endif
1712         return jt;
1713       }
1714     }
1715   } else if (tp->base() == Type::InstPtr) {



1716     assert( off != Type::OffsetBot ||
1717             // arrays can be cast to Objects
1718             tp->is_oopptr()->klass()->is_java_lang_Object() ||
1719             // unsafe field access may not have a constant offset
1720             C->has_unsafe_access(),
1721             "Field accesses must be precise" );
1722     // For oop loads, we expect the _type to be precise.
1723 
1724     // Optimize loads from constant fields.
1725     const TypeInstPtr* tinst = tp->is_instptr();
1726     ciObject* const_oop = tinst->const_oop();
1727     if (!is_mismatched_access() && off != Type::OffsetBot && const_oop != NULL && const_oop->is_instance()) {
1728       const Type* con_type = Type::make_constant_from_field(const_oop->as_instance(), off, is_unsigned(), memory_type());
1729       if (con_type != NULL) {
1730         return con_type;
1731       }
1732     }
1733   } else if (tp->base() == Type::KlassPtr) {
1734     assert( off != Type::OffsetBot ||
1735             // arrays can be cast to Objects
1736             tp->is_klassptr()->klass()->is_java_lang_Object() ||
1737             // also allow array-loading from the primary supertype
1738             // array during subtype checks
1739             Opcode() == Op_LoadKlass,
1740             "Field accesses must be precise" );
1741     // For klass/static loads, we expect the _type to be precise
1742   }
1743 
1744   const TypeKlassPtr *tkls = tp->isa_klassptr();
1745   if (tkls != NULL && !StressReflectiveCode) {
1746     ciKlass* klass = tkls->klass();
1747     if (klass->is_loaded() && tkls->klass_is_exact()) {
1748       // We are loading a field from a Klass metaobject whose identity
1749       // is known at compile time (the type is "exact" or "precise").
1750       // Check for fields we know are maintained as constants by the VM.
1751       if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
1752         // The field is Klass::_super_check_offset.  Return its (constant) value.
1753         // (Folds up type checking code.)
1754         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
1755         return TypeInt::make(klass->super_check_offset());
1756       }
1757       // Compute index into primary_supers array
1758       juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
1759       // Check for overflowing; use unsigned compare to handle the negative case.
1760       if( depth < ciKlass::primary_super_limit() ) {
1761         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
1762         // (Folds up type checking code.)
1763         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1764         ciKlass *ss = klass->super_of_depth(depth);
1765         return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1766       }
1767       const Type* aift = load_array_final_field(tkls, klass);
1768       if (aift != NULL)  return aift;
1769       if (tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
1770         // The field is Klass::_java_mirror.  Return its (constant) value.
1771         // (Folds up the 2nd indirection in anObjConstant.getClass().)
1772         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
1773         return TypeInstPtr::make(klass->java_mirror());
1774       }
1775     }
1776 
1777     // We can still check if we are loading from the primary_supers array at a
1778     // shallow enough depth.  Even though the klass is not exact, entries less
1779     // than or equal to its super depth are correct.
1780     if (klass->is_loaded() ) {
1781       ciType *inner = klass;
1782       while( inner->is_obj_array_klass() )
1783         inner = inner->as_obj_array_klass()->base_element_type();
1784       if( inner->is_instance_klass() &&
1785           !inner->as_instance_klass()->flags().is_interface() ) {
1786         // Compute index into primary_supers array
1787         juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
1788         // Check for overflowing; use unsigned compare to handle the negative case.
1789         if( depth < ciKlass::primary_super_limit() &&
1790             depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
1791           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
1792           // (Folds up type checking code.)
1793           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1794           ciKlass *ss = klass->super_of_depth(depth);
1795           return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1796         }
1797       }
1798     }
1799 
1800     // If the type is enough to determine that the thing is not an array,
1801     // we can give the layout_helper a positive interval type.
1802     // This will help short-circuit some reflective code.
1803     if (tkls->offset() == in_bytes(Klass::layout_helper_offset())
1804         && !klass->is_array_klass() // not directly typed as an array
1805         && !klass->is_interface()  // specifically not Serializable & Cloneable
1806         && !klass->is_java_lang_Object()   // not the supertype of all T[]
1807         ) {
1808       // Note:  When interfaces are reliable, we can narrow the interface
1809       // test to (klass != Serializable && klass != Cloneable).
1810       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
1811       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
1812       // The key property of this type is that it folds up tests
1813       // for array-ness, since it proves that the layout_helper is positive.
1814       // Thus, a generic value like the basic object layout helper works fine.
1815       return TypeInt::make(min_size, max_jint, Type::WidenMin);
1816     }
1817   }
1818 
1819   // If we are loading from a freshly-allocated object, produce a zero,
1820   // if the load is provably beyond the header of the object.
1821   // (Also allow a variable load from a fresh array to produce zero.)
1822   const TypeOopPtr *tinst = tp->isa_oopptr();
1823   bool is_instance = (tinst != NULL) && tinst->is_known_instance_field();
1824   bool is_boxed_value = (tinst != NULL) && tinst->is_ptr_to_boxed_value();
1825   if (ReduceFieldZeroing || is_instance || is_boxed_value) {
1826     Node* value = can_see_stored_value(mem,phase);
1827     if (value != NULL && value->is_Con()) {
1828       assert(value->bottom_type()->higher_equal(_type),"sanity");
1829       return value->bottom_type();
1830     }
1831   }
1832 
1833   if (is_instance) {
1834     // If we have an instance type and our memory input is the
1835     // programs's initial memory state, there is no matching store,
1836     // so just return a zero of the appropriate type
1837     Node *mem = in(MemNode::Memory);
1838     if (mem->is_Parm() && mem->in(0)->is_Start()) {
1839       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
1840       return Type::get_zero_type(_type->basic_type());
1841     }
1842   }
1843   return _type;
1844 }
1845 
1846 //------------------------------match_edge-------------------------------------
1847 // Do we Match on this edge index or not?  Match only the address.
1848 uint LoadNode::match_edge(uint idx) const {
1849   return idx == MemNode::Address;
1850 }
1851 
1852 //--------------------------LoadBNode::Ideal--------------------------------------
1853 //
1854 //  If the previous store is to the same address as this load,
1855 //  and the value stored was larger than a byte, replace this load
1856 //  with the value stored truncated to a byte.  If no truncation is
1857 //  needed, the replacement is done in LoadNode::Identity().
1858 //
1859 Node *LoadBNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1860   Node* mem = in(MemNode::Memory);
1861   Node* value = can_see_stored_value(mem,phase);
1862   if( value && !phase->type(value)->higher_equal( _type ) ) {
1863     Node *result = phase->transform( new LShiftINode(value, phase->intcon(24)) );
1864     return new RShiftINode(result, phase->intcon(24));
1865   }
1866   // Identity call will handle the case where truncation is not needed.
1867   return LoadNode::Ideal(phase, can_reshape);
1868 }
1869 
1870 const Type* LoadBNode::Value(PhaseGVN* phase) const {
1871   Node* mem = in(MemNode::Memory);
1872   Node* value = can_see_stored_value(mem,phase);
1873   if (value != NULL && value->is_Con() &&
1874       !value->bottom_type()->higher_equal(_type)) {
1875     // If the input to the store does not fit with the load's result type,
1876     // it must be truncated. We can't delay until Ideal call since
1877     // a singleton Value is needed for split_thru_phi optimization.
1878     int con = value->get_int();
1879     return TypeInt::make((con << 24) >> 24);
1880   }
1881   return LoadNode::Value(phase);
1882 }
1883 
1884 //--------------------------LoadUBNode::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* LoadUBNode::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     return new AndINode(value, phase->intcon(0xFF));
1896   // Identity call will handle the case where truncation is not needed.
1897   return LoadNode::Ideal(phase, can_reshape);
1898 }
1899 
1900 const Type* LoadUBNode::Value(PhaseGVN* phase) const {
1901   Node* mem = in(MemNode::Memory);
1902   Node* value = can_see_stored_value(mem,phase);
1903   if (value != NULL && value->is_Con() &&
1904       !value->bottom_type()->higher_equal(_type)) {
1905     // If the input to the store does not fit with the load's result type,
1906     // it must be truncated. We can't delay until Ideal call since
1907     // a singleton Value is needed for split_thru_phi optimization.
1908     int con = value->get_int();
1909     return TypeInt::make(con & 0xFF);
1910   }
1911   return LoadNode::Value(phase);
1912 }
1913 
1914 //--------------------------LoadUSNode::Ideal-------------------------------------
1915 //
1916 //  If the previous store is to the same address as this load,
1917 //  and the value stored was larger than a char, replace this load
1918 //  with the value stored truncated to a char.  If no truncation is
1919 //  needed, the replacement is done in LoadNode::Identity().
1920 //
1921 Node *LoadUSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1922   Node* mem = in(MemNode::Memory);
1923   Node* value = can_see_stored_value(mem,phase);
1924   if( value && !phase->type(value)->higher_equal( _type ) )
1925     return new AndINode(value,phase->intcon(0xFFFF));
1926   // Identity call will handle the case where truncation is not needed.
1927   return LoadNode::Ideal(phase, can_reshape);
1928 }
1929 
1930 const Type* LoadUSNode::Value(PhaseGVN* phase) const {
1931   Node* mem = in(MemNode::Memory);
1932   Node* value = can_see_stored_value(mem,phase);
1933   if (value != NULL && value->is_Con() &&
1934       !value->bottom_type()->higher_equal(_type)) {
1935     // If the input to the store does not fit with the load's result type,
1936     // it must be truncated. We can't delay until Ideal call since
1937     // a singleton Value is needed for split_thru_phi optimization.
1938     int con = value->get_int();
1939     return TypeInt::make(con & 0xFFFF);
1940   }
1941   return LoadNode::Value(phase);
1942 }
1943 
1944 //--------------------------LoadSNode::Ideal--------------------------------------
1945 //
1946 //  If the previous store is to the same address as this load,
1947 //  and the value stored was larger than a short, replace this load
1948 //  with the value stored truncated to a short.  If no truncation is
1949 //  needed, the replacement is done in LoadNode::Identity().
1950 //
1951 Node *LoadSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1952   Node* mem = in(MemNode::Memory);
1953   Node* value = can_see_stored_value(mem,phase);
1954   if( value && !phase->type(value)->higher_equal( _type ) ) {
1955     Node *result = phase->transform( new LShiftINode(value, phase->intcon(16)) );
1956     return new RShiftINode(result, phase->intcon(16));
1957   }
1958   // Identity call will handle the case where truncation is not needed.
1959   return LoadNode::Ideal(phase, can_reshape);
1960 }
1961 
1962 const Type* LoadSNode::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 << 16) >> 16);
1972   }
1973   return LoadNode::Value(phase);
1974 }
1975 
1976 //=============================================================================
1977 //----------------------------LoadKlassNode::make------------------------------
1978 // Polymorphic factory method:
1979 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) {
1980   // sanity check the alias category against the created node type
1981   const TypePtr *adr_type = adr->bottom_type()->isa_ptr();
1982   assert(adr_type != NULL, "expecting TypeKlassPtr");
1983 #ifdef _LP64
1984   if (adr_type->is_ptr_to_narrowklass()) {
1985     assert(UseCompressedClassPointers, "no compressed klasses");
1986     Node* load_klass = gvn.transform(new LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
1987     return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
1988   }
1989 #endif
1990   assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
1991   return new LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered);
1992 }
1993 
1994 //------------------------------Value------------------------------------------
1995 const Type* LoadKlassNode::Value(PhaseGVN* phase) const {
1996   return klass_value_common(phase);
1997 }
1998 
1999 // In most cases, LoadKlassNode does not have the control input set. If the control
2000 // input is set, it must not be removed (by LoadNode::Ideal()).
2001 bool LoadKlassNode::can_remove_control() const {
2002   return false;
2003 }
2004 
2005 const Type* LoadNode::klass_value_common(PhaseGVN* phase) const {
2006   // Either input is TOP ==> the result is TOP
2007   const Type *t1 = phase->type( in(MemNode::Memory) );
2008   if (t1 == Type::TOP)  return Type::TOP;
2009   Node *adr = in(MemNode::Address);
2010   const Type *t2 = phase->type( adr );
2011   if (t2 == Type::TOP)  return Type::TOP;
2012   const TypePtr *tp = t2->is_ptr();
2013   if (TypePtr::above_centerline(tp->ptr()) ||
2014       tp->ptr() == TypePtr::Null)  return Type::TOP;
2015 
2016   // Return a more precise klass, if possible
2017   const TypeInstPtr *tinst = tp->isa_instptr();
2018   if (tinst != NULL) {
2019     ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
2020     int offset = tinst->offset();
2021     if (ik == phase->C->env()->Class_klass()
2022         && (offset == java_lang_Class::klass_offset_in_bytes() ||
2023             offset == java_lang_Class::array_klass_offset_in_bytes())) {
2024       // We are loading a special hidden field from a Class mirror object,
2025       // the field which points to the VM's Klass metaobject.
2026       ciType* t = tinst->java_mirror_type();
2027       // java_mirror_type returns non-null for compile-time Class constants.
2028       if (t != NULL) {
2029         // constant oop => constant klass
2030         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
2031           if (t->is_void()) {
2032             // We cannot create a void array.  Since void is a primitive type return null
2033             // klass.  Users of this result need to do a null check on the returned klass.
2034             return TypePtr::NULL_PTR;
2035           }
2036           return TypeKlassPtr::make(ciArrayKlass::make(t));
2037         }
2038         if (!t->is_klass()) {
2039           // a primitive Class (e.g., int.class) has NULL for a klass field
2040           return TypePtr::NULL_PTR;
2041         }
2042         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
2043         return TypeKlassPtr::make(t->as_klass());
2044       }
2045       // non-constant mirror, so we can't tell what's going on
2046     }
2047     if( !ik->is_loaded() )
2048       return _type;             // Bail out if not loaded
2049     if (offset == oopDesc::klass_offset_in_bytes()) {
2050       if (tinst->klass_is_exact()) {
2051         return TypeKlassPtr::make(ik);
2052       }
2053       // See if we can become precise: no subklasses and no interface
2054       // (Note:  We need to support verified interfaces.)
2055       if (!ik->is_interface() && !ik->has_subklass()) {
2056         //assert(!UseExactTypes, "this code should be useless with exact types");
2057         // Add a dependence; if any subclass added we need to recompile
2058         if (!ik->is_final()) {
2059           // %%% should use stronger assert_unique_concrete_subtype instead
2060           phase->C->dependencies()->assert_leaf_type(ik);
2061         }
2062         // Return precise klass
2063         return TypeKlassPtr::make(ik);
2064       }
2065 
2066       // Return root of possible klass
2067       return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
2068     }
2069   }
2070 
2071   // Check for loading klass from an array
2072   const TypeAryPtr *tary = tp->isa_aryptr();
2073   if( tary != NULL ) {
2074     ciKlass *tary_klass = tary->klass();
2075     if (tary_klass != NULL   // can be NULL when at BOTTOM or TOP
2076         && tary->offset() == oopDesc::klass_offset_in_bytes()) {
2077       if (tary->klass_is_exact()) {
2078         return TypeKlassPtr::make(tary_klass);
2079       }
2080       ciArrayKlass *ak = tary->klass()->as_array_klass();
2081       // If the klass is an object array, we defer the question to the
2082       // array component klass.
2083       if( ak->is_obj_array_klass() ) {
2084         assert( ak->is_loaded(), "" );
2085         ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
2086         if( base_k->is_loaded() && base_k->is_instance_klass() ) {
2087           ciInstanceKlass* ik = base_k->as_instance_klass();
2088           // See if we can become precise: no subklasses and no interface
2089           if (!ik->is_interface() && !ik->has_subklass()) {
2090             //assert(!UseExactTypes, "this code should be useless with exact types");
2091             // Add a dependence; if any subclass added we need to recompile
2092             if (!ik->is_final()) {
2093               phase->C->dependencies()->assert_leaf_type(ik);
2094             }
2095             // Return precise array klass
2096             return TypeKlassPtr::make(ak);
2097           }
2098         }
2099         return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
2100       } else {                  // Found a type-array?
2101         //assert(!UseExactTypes, "this code should be useless with exact types");
2102         assert( ak->is_type_array_klass(), "" );
2103         return TypeKlassPtr::make(ak); // These are always precise
2104       }
2105     }
2106   }
2107 
2108   // Check for loading klass from an array klass
2109   const TypeKlassPtr *tkls = tp->isa_klassptr();
2110   if (tkls != NULL && !StressReflectiveCode) {
2111     ciKlass* klass = tkls->klass();
2112     if( !klass->is_loaded() )
2113       return _type;             // Bail out if not loaded
2114     if( klass->is_obj_array_klass() &&
2115         tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
2116       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
2117       // // Always returning precise element type is incorrect,
2118       // // e.g., element type could be object and array may contain strings
2119       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
2120 
2121       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
2122       // according to the element type's subclassing.
2123       return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
2124     }
2125     if( klass->is_instance_klass() && tkls->klass_is_exact() &&
2126         tkls->offset() == in_bytes(Klass::super_offset())) {
2127       ciKlass* sup = klass->as_instance_klass()->super();
2128       // The field is Klass::_super.  Return its (constant) value.
2129       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
2130       return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
2131     }
2132   }
2133 
2134   // Bailout case
2135   return LoadNode::Value(phase);
2136 }
2137 
2138 //------------------------------Identity---------------------------------------
2139 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
2140 // Also feed through the klass in Allocate(...klass...)._klass.
2141 Node* LoadKlassNode::Identity(PhaseGVN* phase) {
2142   return klass_identity_common(phase);
2143 }
2144 
2145 Node* LoadNode::klass_identity_common(PhaseGVN* phase) {
2146   Node* x = LoadNode::Identity(phase);
2147   if (x != this)  return x;
2148 
2149   // Take apart the address into an oop and and offset.
2150   // Return 'this' if we cannot.
2151   Node*    adr    = in(MemNode::Address);
2152   intptr_t offset = 0;
2153   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2154   if (base == NULL)     return this;
2155   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
2156   if (toop == NULL)     return this;
2157 
2158   // We can fetch the klass directly through an AllocateNode.
2159   // This works even if the klass is not constant (clone or newArray).
2160   if (offset == oopDesc::klass_offset_in_bytes()) {
2161     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
2162     if (allocated_klass != NULL) {
2163       return allocated_klass;
2164     }
2165   }
2166 
2167   // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
2168   // See inline_native_Class_query for occurrences of these patterns.
2169   // Java Example:  x.getClass().isAssignableFrom(y)
2170   //
2171   // This improves reflective code, often making the Class
2172   // mirror go completely dead.  (Current exception:  Class
2173   // mirrors may appear in debug info, but we could clean them out by
2174   // introducing a new debug info operator for Klass*.java_mirror).
2175   if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
2176       && offset == java_lang_Class::klass_offset_in_bytes()) {
2177     // We are loading a special hidden field from a Class mirror,
2178     // the field which points to its Klass or ArrayKlass metaobject.
2179     if (base->is_Load()) {
2180       Node* adr2 = base->in(MemNode::Address);
2181       const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2182       if (tkls != NULL && !tkls->empty()
2183           && (tkls->klass()->is_instance_klass() ||
2184               tkls->klass()->is_array_klass())
2185           && adr2->is_AddP()
2186           ) {
2187         int mirror_field = in_bytes(Klass::java_mirror_offset());
2188         if (tkls->offset() == mirror_field) {
2189           return adr2->in(AddPNode::Base);
2190         }
2191       }
2192     }
2193   }
2194 
2195   return this;
2196 }
2197 
2198 
2199 //------------------------------Value------------------------------------------
2200 const Type* LoadNKlassNode::Value(PhaseGVN* phase) const {
2201   const Type *t = klass_value_common(phase);
2202   if (t == Type::TOP)
2203     return t;
2204 
2205   return t->make_narrowklass();
2206 }
2207 
2208 //------------------------------Identity---------------------------------------
2209 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
2210 // Also feed through the klass in Allocate(...klass...)._klass.
2211 Node* LoadNKlassNode::Identity(PhaseGVN* phase) {
2212   Node *x = klass_identity_common(phase);
2213 
2214   const Type *t = phase->type( x );
2215   if( t == Type::TOP ) return x;
2216   if( t->isa_narrowklass()) return x;
2217   assert (!t->isa_narrowoop(), "no narrow oop here");
2218 
2219   return phase->transform(new EncodePKlassNode(x, t->make_narrowklass()));
2220 }
2221 
2222 //------------------------------Value-----------------------------------------
2223 const Type* LoadRangeNode::Value(PhaseGVN* phase) const {
2224   // Either input is TOP ==> the result is TOP
2225   const Type *t1 = phase->type( in(MemNode::Memory) );
2226   if( t1 == Type::TOP ) return Type::TOP;
2227   Node *adr = in(MemNode::Address);
2228   const Type *t2 = phase->type( adr );
2229   if( t2 == Type::TOP ) return Type::TOP;
2230   const TypePtr *tp = t2->is_ptr();
2231   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
2232   const TypeAryPtr *tap = tp->isa_aryptr();
2233   if( !tap ) return _type;
2234   return tap->size();
2235 }
2236 
2237 //-------------------------------Ideal---------------------------------------
2238 // Feed through the length in AllocateArray(...length...)._length.
2239 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2240   Node* p = MemNode::Ideal_common(phase, can_reshape);
2241   if (p)  return (p == NodeSentinel) ? NULL : p;
2242 
2243   // Take apart the address into an oop and and offset.
2244   // Return 'this' if we cannot.
2245   Node*    adr    = in(MemNode::Address);
2246   intptr_t offset = 0;
2247   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase,  offset);
2248   if (base == NULL)     return NULL;
2249   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2250   if (tary == NULL)     return NULL;
2251 
2252   // We can fetch the length directly through an AllocateArrayNode.
2253   // This works even if the length is not constant (clone or newArray).
2254   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2255     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2256     if (alloc != NULL) {
2257       Node* allocated_length = alloc->Ideal_length();
2258       Node* len = alloc->make_ideal_length(tary, phase);
2259       if (allocated_length != len) {
2260         // New CastII improves on this.
2261         return len;
2262       }
2263     }
2264   }
2265 
2266   return NULL;
2267 }
2268 
2269 //------------------------------Identity---------------------------------------
2270 // Feed through the length in AllocateArray(...length...)._length.
2271 Node* LoadRangeNode::Identity(PhaseGVN* phase) {
2272   Node* x = LoadINode::Identity(phase);
2273   if (x != this)  return x;
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 this;
2281   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2282   if (tary == NULL)     return this;
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       // Do not allow make_ideal_length to allocate a CastII node.
2291       Node* len = alloc->make_ideal_length(tary, phase, false);
2292       if (allocated_length == len) {
2293         // Return allocated_length only if it would not be improved by a CastII.
2294         return allocated_length;
2295       }
2296     }
2297   }
2298 
2299   return this;
2300 
2301 }
2302 
2303 //=============================================================================
2304 //---------------------------StoreNode::make-----------------------------------
2305 // Polymorphic factory method:
2306 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo) {
2307   assert((mo == unordered || mo == release), "unexpected");
2308   Compile* C = gvn.C;
2309   assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
2310          ctl != NULL, "raw memory operations should have control edge");
2311 
2312   switch (bt) {
2313   case T_BOOLEAN: val = gvn.transform(new AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case
2314   case T_BYTE:    return new StoreBNode(ctl, mem, adr, adr_type, val, mo);
2315   case T_INT:     return new StoreINode(ctl, mem, adr, adr_type, val, mo);
2316   case T_CHAR:
2317   case T_SHORT:   return new StoreCNode(ctl, mem, adr, adr_type, val, mo);
2318   case T_LONG:    return new StoreLNode(ctl, mem, adr, adr_type, val, mo);
2319   case T_FLOAT:   return new StoreFNode(ctl, mem, adr, adr_type, val, mo);
2320   case T_DOUBLE:  return new StoreDNode(ctl, mem, adr, adr_type, val, mo);
2321   case T_METADATA:
2322   case T_ADDRESS:
2323   case T_OBJECT:
2324 #ifdef _LP64
2325     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2326       val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop()));
2327       return new StoreNNode(ctl, mem, adr, adr_type, val, mo);
2328     } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
2329                (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
2330                 adr->bottom_type()->isa_rawptr())) {
2331       val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
2332       return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
2333     }
2334 #endif
2335     {
2336       return new StorePNode(ctl, mem, adr, adr_type, val, mo);
2337     }
2338   }
2339   ShouldNotReachHere();
2340   return (StoreNode*)NULL;
2341 }
2342 
2343 StoreLNode* StoreLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2344   bool require_atomic = true;
2345   return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2346 }
2347 
2348 StoreDNode* StoreDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2349   bool require_atomic = true;
2350   return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2351 }
2352 
2353 
2354 //--------------------------bottom_type----------------------------------------
2355 const Type *StoreNode::bottom_type() const {
2356   return Type::MEMORY;
2357 }
2358 
2359 //------------------------------hash-------------------------------------------
2360 uint StoreNode::hash() const {
2361   // unroll addition of interesting fields
2362   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
2363 
2364   // Since they are not commoned, do not hash them:
2365   return NO_HASH;
2366 }
2367 
2368 //------------------------------Ideal------------------------------------------
2369 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
2370 // When a store immediately follows a relevant allocation/initialization,
2371 // try to capture it into the initialization, or hoist it above.
2372 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2373   Node* p = MemNode::Ideal_common(phase, can_reshape);
2374   if (p)  return (p == NodeSentinel) ? NULL : p;
2375 
2376   Node* mem     = in(MemNode::Memory);
2377   Node* address = in(MemNode::Address);
2378   // Back-to-back stores to same address?  Fold em up.  Generally
2379   // unsafe if I have intervening uses...  Also disallowed for StoreCM
2380   // since they must follow each StoreP operation.  Redundant StoreCMs
2381   // are eliminated just before matching in final_graph_reshape.
2382   {
2383     Node* st = mem;
2384     // If Store 'st' has more than one use, we cannot fold 'st' away.
2385     // For example, 'st' might be the final state at a conditional
2386     // return.  Or, 'st' might be used by some node which is live at
2387     // the same time 'st' is live, which might be unschedulable.  So,
2388     // require exactly ONE user until such time as we clone 'mem' for
2389     // each of 'mem's uses (thus making the exactly-1-user-rule hold
2390     // true).
2391     while (st->is_Store() && st->outcnt() == 1 && st->Opcode() != Op_StoreCM) {
2392       // Looking at a dead closed cycle of memory?
2393       assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
2394       assert(Opcode() == st->Opcode() ||
2395              st->Opcode() == Op_StoreVector ||
2396              Opcode() == Op_StoreVector ||
2397              phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw ||
2398              (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode
2399              (is_mismatched_access() || st->as_Store()->is_mismatched_access()),
2400              "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]);
2401 
2402       if (st->in(MemNode::Address)->eqv_uncast(address) &&
2403           st->as_Store()->memory_size() <= this->memory_size()) {
2404         Node* use = st->raw_out(0);
2405         phase->igvn_rehash_node_delayed(use);
2406         if (can_reshape) {
2407           use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase->is_IterGVN());
2408         } else {
2409           // It's OK to do this in the parser, since DU info is always accurate,
2410           // and the parser always refers to nodes via SafePointNode maps.
2411           use->set_req(MemNode::Memory, st->in(MemNode::Memory));
2412         }
2413         return this;
2414       }
2415       st = st->in(MemNode::Memory);
2416     }
2417   }
2418 
2419 
2420   // Capture an unaliased, unconditional, simple store into an initializer.
2421   // Or, if it is independent of the allocation, hoist it above the allocation.
2422   if (ReduceFieldZeroing && /*can_reshape &&*/
2423       mem->is_Proj() && mem->in(0)->is_Initialize()) {
2424     InitializeNode* init = mem->in(0)->as_Initialize();
2425     intptr_t offset = init->can_capture_store(this, phase, can_reshape);
2426     if (offset > 0) {
2427       Node* moved = init->capture_store(this, offset, phase, can_reshape);
2428       // If the InitializeNode captured me, it made a raw copy of me,
2429       // and I need to disappear.
2430       if (moved != NULL) {
2431         // %%% hack to ensure that Ideal returns a new node:
2432         mem = MergeMemNode::make(mem);
2433         return mem;             // fold me away
2434       }
2435     }
2436   }
2437 
2438   return NULL;                  // No further progress
2439 }
2440 
2441 //------------------------------Value-----------------------------------------
2442 const Type* StoreNode::Value(PhaseGVN* phase) const {
2443   // Either input is TOP ==> the result is TOP
2444   const Type *t1 = phase->type( in(MemNode::Memory) );
2445   if( t1 == Type::TOP ) return Type::TOP;
2446   const Type *t2 = phase->type( in(MemNode::Address) );
2447   if( t2 == Type::TOP ) return Type::TOP;
2448   const Type *t3 = phase->type( in(MemNode::ValueIn) );
2449   if( t3 == Type::TOP ) return Type::TOP;
2450   return Type::MEMORY;
2451 }
2452 
2453 //------------------------------Identity---------------------------------------
2454 // Remove redundant stores:
2455 //   Store(m, p, Load(m, p)) changes to m.
2456 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
2457 Node* StoreNode::Identity(PhaseGVN* phase) {
2458   Node* mem = in(MemNode::Memory);
2459   Node* adr = in(MemNode::Address);
2460   Node* val = in(MemNode::ValueIn);
2461 
2462   // Load then Store?  Then the Store is useless
2463   if (val->is_Load() &&
2464       val->in(MemNode::Address)->eqv_uncast(adr) &&
2465       val->in(MemNode::Memory )->eqv_uncast(mem) &&
2466       val->as_Load()->store_Opcode() == Opcode()) {
2467     return mem;
2468   }
2469 
2470   // Two stores in a row of the same value?
2471   if (mem->is_Store() &&
2472       mem->in(MemNode::Address)->eqv_uncast(adr) &&
2473       mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
2474       mem->Opcode() == Opcode()) {
2475     return mem;
2476   }
2477 
2478   // Store of zero anywhere into a freshly-allocated object?
2479   // Then the store is useless.
2480   // (It must already have been captured by the InitializeNode.)
2481   if (ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
2482     // a newly allocated object is already all-zeroes everywhere
2483     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
2484       return mem;
2485     }
2486 
2487     // the store may also apply to zero-bits in an earlier object
2488     Node* prev_mem = find_previous_store(phase);
2489     // Steps (a), (b):  Walk past independent stores to find an exact match.
2490     if (prev_mem != NULL) {
2491       Node* prev_val = can_see_stored_value(prev_mem, phase);
2492       if (prev_val != NULL && phase->eqv(prev_val, val)) {
2493         // prev_val and val might differ by a cast; it would be good
2494         // to keep the more informative of the two.
2495         return mem;
2496       }
2497     }
2498   }
2499 
2500   return this;
2501 }
2502 
2503 //------------------------------match_edge-------------------------------------
2504 // Do we Match on this edge index or not?  Match only memory & value
2505 uint StoreNode::match_edge(uint idx) const {
2506   return idx == MemNode::Address || idx == MemNode::ValueIn;
2507 }
2508 
2509 //------------------------------cmp--------------------------------------------
2510 // Do not common stores up together.  They generally have to be split
2511 // back up anyways, so do not bother.
2512 uint StoreNode::cmp( const Node &n ) const {
2513   return (&n == this);          // Always fail except on self
2514 }
2515 
2516 //------------------------------Ideal_masked_input-----------------------------
2517 // Check for a useless mask before a partial-word store
2518 // (StoreB ... (AndI valIn conIa) )
2519 // If (conIa & mask == mask) this simplifies to
2520 // (StoreB ... (valIn) )
2521 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
2522   Node *val = in(MemNode::ValueIn);
2523   if( val->Opcode() == Op_AndI ) {
2524     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2525     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
2526       set_req(MemNode::ValueIn, val->in(1));
2527       return this;
2528     }
2529   }
2530   return NULL;
2531 }
2532 
2533 
2534 //------------------------------Ideal_sign_extended_input----------------------
2535 // Check for useless sign-extension before a partial-word store
2536 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
2537 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
2538 // (StoreB ... (valIn) )
2539 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
2540   Node *val = in(MemNode::ValueIn);
2541   if( val->Opcode() == Op_RShiftI ) {
2542     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2543     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
2544       Node *shl = val->in(1);
2545       if( shl->Opcode() == Op_LShiftI ) {
2546         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
2547         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
2548           set_req(MemNode::ValueIn, shl->in(1));
2549           return this;
2550         }
2551       }
2552     }
2553   }
2554   return NULL;
2555 }
2556 
2557 //------------------------------value_never_loaded-----------------------------------
2558 // Determine whether there are any possible loads of the value stored.
2559 // For simplicity, we actually check if there are any loads from the
2560 // address stored to, not just for loads of the value stored by this node.
2561 //
2562 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
2563   Node *adr = in(Address);
2564   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
2565   if (adr_oop == NULL)
2566     return false;
2567   if (!adr_oop->is_known_instance_field())
2568     return false; // if not a distinct instance, there may be aliases of the address
2569   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
2570     Node *use = adr->fast_out(i);
2571     if (use->is_Load() || use->is_LoadStore()) {
2572       return false;
2573     }
2574   }
2575   return true;
2576 }
2577 
2578 //=============================================================================
2579 //------------------------------Ideal------------------------------------------
2580 // If the store is from an AND mask that leaves the low bits untouched, then
2581 // we can skip the AND operation.  If the store is from a sign-extension
2582 // (a left shift, then right shift) we can skip both.
2583 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
2584   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
2585   if( progress != NULL ) return progress;
2586 
2587   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
2588   if( progress != NULL ) return progress;
2589 
2590   // Finally check the default case
2591   return StoreNode::Ideal(phase, can_reshape);
2592 }
2593 
2594 //=============================================================================
2595 //------------------------------Ideal------------------------------------------
2596 // If the store is from an AND mask that leaves the low bits untouched, then
2597 // we can skip the AND operation
2598 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
2599   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
2600   if( progress != NULL ) return progress;
2601 
2602   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
2603   if( progress != NULL ) return progress;
2604 
2605   // Finally check the default case
2606   return StoreNode::Ideal(phase, can_reshape);
2607 }
2608 
2609 //=============================================================================
2610 //------------------------------Identity---------------------------------------
2611 Node* StoreCMNode::Identity(PhaseGVN* phase) {
2612   // No need to card mark when storing a null ptr
2613   Node* my_store = in(MemNode::OopStore);
2614   if (my_store->is_Store()) {
2615     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
2616     if( t1 == TypePtr::NULL_PTR ) {
2617       return in(MemNode::Memory);
2618     }
2619   }
2620   return this;
2621 }
2622 
2623 //=============================================================================
2624 //------------------------------Ideal---------------------------------------
2625 Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
2626   Node* progress = StoreNode::Ideal(phase, can_reshape);
2627   if (progress != NULL) return progress;
2628 
2629   Node* my_store = in(MemNode::OopStore);
2630   if (my_store->is_MergeMem()) {
2631     Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
2632     set_req(MemNode::OopStore, mem);
2633     return this;
2634   }
2635 
2636   return NULL;
2637 }
2638 
2639 //------------------------------Value-----------------------------------------
2640 const Type* StoreCMNode::Value(PhaseGVN* phase) const {
2641   // Either input is TOP ==> the result is TOP
2642   const Type *t = phase->type( in(MemNode::Memory) );
2643   if( t == Type::TOP ) return Type::TOP;
2644   t = phase->type( in(MemNode::Address) );
2645   if( t == Type::TOP ) return Type::TOP;
2646   t = phase->type( in(MemNode::ValueIn) );
2647   if( t == Type::TOP ) return Type::TOP;
2648   // If extra input is TOP ==> the result is TOP
2649   t = phase->type( in(MemNode::OopStore) );
2650   if( t == Type::TOP ) return Type::TOP;
2651 
2652   return StoreNode::Value( phase );
2653 }
2654 
2655 
2656 //=============================================================================
2657 //----------------------------------SCMemProjNode------------------------------
2658 const Type* SCMemProjNode::Value(PhaseGVN* phase) const
2659 {
2660   return bottom_type();
2661 }
2662 
2663 //=============================================================================
2664 //----------------------------------LoadStoreNode------------------------------
2665 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
2666   : Node(required),
2667     _type(rt),
2668     _adr_type(at)
2669 {
2670   init_req(MemNode::Control, c  );
2671   init_req(MemNode::Memory , mem);
2672   init_req(MemNode::Address, adr);
2673   init_req(MemNode::ValueIn, val);
2674   init_class_id(Class_LoadStore);
2675 }
2676 
2677 uint LoadStoreNode::ideal_reg() const {
2678   return _type->ideal_reg();
2679 }
2680 
2681 bool LoadStoreNode::result_not_used() const {
2682   for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
2683     Node *x = fast_out(i);
2684     if (x->Opcode() == Op_SCMemProj) continue;
2685     return false;
2686   }
2687   return true;
2688 }
2689 
2690 uint LoadStoreNode::size_of() const { return sizeof(*this); }
2691 
2692 //=============================================================================
2693 //----------------------------------LoadStoreConditionalNode--------------------
2694 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, NULL, TypeInt::BOOL, 5) {
2695   init_req(ExpectedIn, ex );
2696 }
2697 
2698 //=============================================================================
2699 //-------------------------------adr_type--------------------------------------
2700 const TypePtr* ClearArrayNode::adr_type() const {
2701   Node *adr = in(3);
2702   if (adr == NULL)  return NULL; // node is dead
2703   return MemNode::calculate_adr_type(adr->bottom_type());
2704 }
2705 
2706 //------------------------------match_edge-------------------------------------
2707 // Do we Match on this edge index or not?  Do not match memory
2708 uint ClearArrayNode::match_edge(uint idx) const {
2709   return idx > 1;
2710 }
2711 
2712 //------------------------------Identity---------------------------------------
2713 // Clearing a zero length array does nothing
2714 Node* ClearArrayNode::Identity(PhaseGVN* phase) {
2715   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
2716 }
2717 
2718 //------------------------------Idealize---------------------------------------
2719 // Clearing a short array is faster with stores
2720 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape){
2721   // Already know this is a large node, do not try to ideal it
2722   if (_is_large) return NULL;
2723 
2724   const int unit = BytesPerLong;
2725   const TypeX* t = phase->type(in(2))->isa_intptr_t();
2726   if (!t)  return NULL;
2727   if (!t->is_con())  return NULL;
2728   intptr_t raw_count = t->get_con();
2729   intptr_t size = raw_count;
2730   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
2731   // Clearing nothing uses the Identity call.
2732   // Negative clears are possible on dead ClearArrays
2733   // (see jck test stmt114.stmt11402.val).
2734   if (size <= 0 || size % unit != 0)  return NULL;
2735   intptr_t count = size / unit;
2736   // Length too long; communicate this to matchers and assemblers.
2737   // Assemblers are responsible to produce fast hardware clears for it.
2738   if (size > InitArrayShortSize) {
2739     return new ClearArrayNode(in(0), in(1), in(2), in(3), true);
2740   }
2741   Node *mem = in(1);
2742   if( phase->type(mem)==Type::TOP ) return NULL;
2743   Node *adr = in(3);
2744   const Type* at = phase->type(adr);
2745   if( at==Type::TOP ) return NULL;
2746   const TypePtr* atp = at->isa_ptr();
2747   // adjust atp to be the correct array element address type
2748   if (atp == NULL)  atp = TypePtr::BOTTOM;
2749   else              atp = atp->add_offset(Type::OffsetBot);
2750   // Get base for derived pointer purposes
2751   if( adr->Opcode() != Op_AddP ) Unimplemented();
2752   Node *base = adr->in(1);
2753 
2754   Node *zero = phase->makecon(TypeLong::ZERO);
2755   Node *off  = phase->MakeConX(BytesPerLong);
2756   mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
2757   count--;
2758   while( count-- ) {
2759     mem = phase->transform(mem);
2760     adr = phase->transform(new AddPNode(base,adr,off));
2761     mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
2762   }
2763   return mem;
2764 }
2765 
2766 //----------------------------step_through----------------------------------
2767 // Return allocation input memory edge if it is different instance
2768 // or itself if it is the one we are looking for.
2769 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseTransform* phase) {
2770   Node* n = *np;
2771   assert(n->is_ClearArray(), "sanity");
2772   intptr_t offset;
2773   AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
2774   // This method is called only before Allocate nodes are expanded
2775   // during macro nodes expansion. Before that ClearArray nodes are
2776   // only generated in PhaseMacroExpand::generate_arraycopy() (before
2777   // Allocate nodes are expanded) which follows allocations.
2778   assert(alloc != NULL, "should have allocation");
2779   if (alloc->_idx == instance_id) {
2780     // Can not bypass initialization of the instance we are looking for.
2781     return false;
2782   }
2783   // Otherwise skip it.
2784   InitializeNode* init = alloc->initialization();
2785   if (init != NULL)
2786     *np = init->in(TypeFunc::Memory);
2787   else
2788     *np = alloc->in(TypeFunc::Memory);
2789   return true;
2790 }
2791 
2792 //----------------------------clear_memory-------------------------------------
2793 // Generate code to initialize object storage to zero.
2794 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2795                                    intptr_t start_offset,
2796                                    Node* end_offset,
2797                                    PhaseGVN* phase) {
2798   intptr_t offset = start_offset;
2799 
2800   int unit = BytesPerLong;
2801   if ((offset % unit) != 0) {
2802     Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset));
2803     adr = phase->transform(adr);
2804     const TypePtr* atp = TypeRawPtr::BOTTOM;
2805     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
2806     mem = phase->transform(mem);
2807     offset += BytesPerInt;
2808   }
2809   assert((offset % unit) == 0, "");
2810 
2811   // Initialize the remaining stuff, if any, with a ClearArray.
2812   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
2813 }
2814 
2815 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2816                                    Node* start_offset,
2817                                    Node* end_offset,
2818                                    PhaseGVN* phase) {
2819   if (start_offset == end_offset) {
2820     // nothing to do
2821     return mem;
2822   }
2823 
2824   int unit = BytesPerLong;
2825   Node* zbase = start_offset;
2826   Node* zend  = end_offset;
2827 
2828   // Scale to the unit required by the CPU:
2829   if (!Matcher::init_array_count_is_in_bytes) {
2830     Node* shift = phase->intcon(exact_log2(unit));
2831     zbase = phase->transform(new URShiftXNode(zbase, shift) );
2832     zend  = phase->transform(new URShiftXNode(zend,  shift) );
2833   }
2834 
2835   // Bulk clear double-words
2836   Node* zsize = phase->transform(new SubXNode(zend, zbase) );
2837   Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) );
2838   mem = new ClearArrayNode(ctl, mem, zsize, adr, false);
2839   return phase->transform(mem);
2840 }
2841 
2842 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2843                                    intptr_t start_offset,
2844                                    intptr_t end_offset,
2845                                    PhaseGVN* phase) {
2846   if (start_offset == end_offset) {
2847     // nothing to do
2848     return mem;
2849   }
2850 
2851   assert((end_offset % BytesPerInt) == 0, "odd end offset");
2852   intptr_t done_offset = end_offset;
2853   if ((done_offset % BytesPerLong) != 0) {
2854     done_offset -= BytesPerInt;
2855   }
2856   if (done_offset > start_offset) {
2857     mem = clear_memory(ctl, mem, dest,
2858                        start_offset, phase->MakeConX(done_offset), phase);
2859   }
2860   if (done_offset < end_offset) { // emit the final 32-bit store
2861     Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset));
2862     adr = phase->transform(adr);
2863     const TypePtr* atp = TypeRawPtr::BOTTOM;
2864     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
2865     mem = phase->transform(mem);
2866     done_offset += BytesPerInt;
2867   }
2868   assert(done_offset == end_offset, "");
2869   return mem;
2870 }
2871 
2872 //=============================================================================
2873 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
2874   : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
2875     _adr_type(C->get_adr_type(alias_idx))
2876 {
2877   init_class_id(Class_MemBar);
2878   Node* top = C->top();
2879   init_req(TypeFunc::I_O,top);
2880   init_req(TypeFunc::FramePtr,top);
2881   init_req(TypeFunc::ReturnAdr,top);
2882   if (precedent != NULL)
2883     init_req(TypeFunc::Parms, precedent);
2884 }
2885 
2886 //------------------------------cmp--------------------------------------------
2887 uint MemBarNode::hash() const { return NO_HASH; }
2888 uint MemBarNode::cmp( const Node &n ) const {
2889   return (&n == this);          // Always fail except on self
2890 }
2891 
2892 //------------------------------make-------------------------------------------
2893 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
2894   switch (opcode) {
2895   case Op_MemBarAcquire:     return new MemBarAcquireNode(C, atp, pn);
2896   case Op_LoadFence:         return new LoadFenceNode(C, atp, pn);
2897   case Op_MemBarRelease:     return new MemBarReleaseNode(C, atp, pn);
2898   case Op_StoreFence:        return new StoreFenceNode(C, atp, pn);
2899   case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn);
2900   case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn);
2901   case Op_MemBarVolatile:    return new MemBarVolatileNode(C, atp, pn);
2902   case Op_MemBarCPUOrder:    return new MemBarCPUOrderNode(C, atp, pn);
2903   case Op_OnSpinWait:        return new OnSpinWaitNode(C, atp, pn);
2904   case Op_Initialize:        return new InitializeNode(C, atp, pn);
2905   case Op_MemBarStoreStore:  return new MemBarStoreStoreNode(C, atp, pn);
2906   default: ShouldNotReachHere(); return NULL;
2907   }
2908 }
2909 
2910 //------------------------------Ideal------------------------------------------
2911 // Return a node which is more "ideal" than the current node.  Strip out
2912 // control copies
2913 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2914   if (remove_dead_region(phase, can_reshape)) return this;
2915   // Don't bother trying to transform a dead node
2916   if (in(0) && in(0)->is_top()) {
2917     return NULL;
2918   }
2919 
2920   bool progress = false;
2921   // Eliminate volatile MemBars for scalar replaced objects.
2922   if (can_reshape && req() == (Precedent+1)) {
2923     bool eliminate = false;
2924     int opc = Opcode();
2925     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
2926       // Volatile field loads and stores.
2927       Node* my_mem = in(MemBarNode::Precedent);
2928       // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
2929       if ((my_mem != NULL) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
2930         // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
2931         // replace this Precedent (decodeN) with the Load instead.
2932         if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1))  {
2933           Node* load_node = my_mem->in(1);
2934           set_req(MemBarNode::Precedent, load_node);
2935           phase->is_IterGVN()->_worklist.push(my_mem);
2936           my_mem = load_node;
2937         } else {
2938           assert(my_mem->unique_out() == this, "sanity");
2939           del_req(Precedent);
2940           phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
2941           my_mem = NULL;
2942         }
2943         progress = true;
2944       }
2945       if (my_mem != NULL && my_mem->is_Mem()) {
2946         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
2947         // Check for scalar replaced object reference.
2948         if( t_oop != NULL && t_oop->is_known_instance_field() &&
2949             t_oop->offset() != Type::OffsetBot &&
2950             t_oop->offset() != Type::OffsetTop) {
2951           eliminate = true;
2952         }
2953       }
2954     } else if (opc == Op_MemBarRelease) {
2955       // Final field stores.
2956       Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent), phase);
2957       if ((alloc != NULL) && alloc->is_Allocate() &&
2958           alloc->as_Allocate()->does_not_escape_thread()) {
2959         // The allocated object does not escape.
2960         eliminate = true;
2961       }
2962     }
2963     if (eliminate) {
2964       // Replace MemBar projections by its inputs.
2965       PhaseIterGVN* igvn = phase->is_IterGVN();
2966       igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
2967       igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
2968       // Must return either the original node (now dead) or a new node
2969       // (Do not return a top here, since that would break the uniqueness of top.)
2970       return new ConINode(TypeInt::ZERO);
2971     }
2972   }
2973   return progress ? this : NULL;
2974 }
2975 
2976 //------------------------------Value------------------------------------------
2977 const Type* MemBarNode::Value(PhaseGVN* phase) const {
2978   if( !in(0) ) return Type::TOP;
2979   if( phase->type(in(0)) == Type::TOP )
2980     return Type::TOP;
2981   return TypeTuple::MEMBAR;
2982 }
2983 
2984 //------------------------------match------------------------------------------
2985 // Construct projections for memory.
2986 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
2987   switch (proj->_con) {
2988   case TypeFunc::Control:
2989   case TypeFunc::Memory:
2990     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
2991   }
2992   ShouldNotReachHere();
2993   return NULL;
2994 }
2995 
2996 //===========================InitializeNode====================================
2997 // SUMMARY:
2998 // This node acts as a memory barrier on raw memory, after some raw stores.
2999 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
3000 // The Initialize can 'capture' suitably constrained stores as raw inits.
3001 // It can coalesce related raw stores into larger units (called 'tiles').
3002 // It can avoid zeroing new storage for memory units which have raw inits.
3003 // At macro-expansion, it is marked 'complete', and does not optimize further.
3004 //
3005 // EXAMPLE:
3006 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
3007 //   ctl = incoming control; mem* = incoming memory
3008 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
3009 // First allocate uninitialized memory and fill in the header:
3010 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
3011 //   ctl := alloc.Control; mem* := alloc.Memory*
3012 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
3013 // Then initialize to zero the non-header parts of the raw memory block:
3014 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
3015 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
3016 // After the initialize node executes, the object is ready for service:
3017 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
3018 // Suppose its body is immediately initialized as {1,2}:
3019 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3020 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3021 //   mem.SLICE(#short[*]) := store2
3022 //
3023 // DETAILS:
3024 // An InitializeNode collects and isolates object initialization after
3025 // an AllocateNode and before the next possible safepoint.  As a
3026 // memory barrier (MemBarNode), it keeps critical stores from drifting
3027 // down past any safepoint or any publication of the allocation.
3028 // Before this barrier, a newly-allocated object may have uninitialized bits.
3029 // After this barrier, it may be treated as a real oop, and GC is allowed.
3030 //
3031 // The semantics of the InitializeNode include an implicit zeroing of
3032 // the new object from object header to the end of the object.
3033 // (The object header and end are determined by the AllocateNode.)
3034 //
3035 // Certain stores may be added as direct inputs to the InitializeNode.
3036 // These stores must update raw memory, and they must be to addresses
3037 // derived from the raw address produced by AllocateNode, and with
3038 // a constant offset.  They must be ordered by increasing offset.
3039 // The first one is at in(RawStores), the last at in(req()-1).
3040 // Unlike most memory operations, they are not linked in a chain,
3041 // but are displayed in parallel as users of the rawmem output of
3042 // the allocation.
3043 //
3044 // (See comments in InitializeNode::capture_store, which continue
3045 // the example given above.)
3046 //
3047 // When the associated Allocate is macro-expanded, the InitializeNode
3048 // may be rewritten to optimize collected stores.  A ClearArrayNode
3049 // may also be created at that point to represent any required zeroing.
3050 // The InitializeNode is then marked 'complete', prohibiting further
3051 // capturing of nearby memory operations.
3052 //
3053 // During macro-expansion, all captured initializations which store
3054 // constant values of 32 bits or smaller are coalesced (if advantageous)
3055 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
3056 // initialized in fewer memory operations.  Memory words which are
3057 // covered by neither tiles nor non-constant stores are pre-zeroed
3058 // by explicit stores of zero.  (The code shape happens to do all
3059 // zeroing first, then all other stores, with both sequences occurring
3060 // in order of ascending offsets.)
3061 //
3062 // Alternatively, code may be inserted between an AllocateNode and its
3063 // InitializeNode, to perform arbitrary initialization of the new object.
3064 // E.g., the object copying intrinsics insert complex data transfers here.
3065 // The initialization must then be marked as 'complete' disable the
3066 // built-in zeroing semantics and the collection of initializing stores.
3067 //
3068 // While an InitializeNode is incomplete, reads from the memory state
3069 // produced by it are optimizable if they match the control edge and
3070 // new oop address associated with the allocation/initialization.
3071 // They return a stored value (if the offset matches) or else zero.
3072 // A write to the memory state, if it matches control and address,
3073 // and if it is to a constant offset, may be 'captured' by the
3074 // InitializeNode.  It is cloned as a raw memory operation and rewired
3075 // inside the initialization, to the raw oop produced by the allocation.
3076 // Operations on addresses which are provably distinct (e.g., to
3077 // other AllocateNodes) are allowed to bypass the initialization.
3078 //
3079 // The effect of all this is to consolidate object initialization
3080 // (both arrays and non-arrays, both piecewise and bulk) into a
3081 // single location, where it can be optimized as a unit.
3082 //
3083 // Only stores with an offset less than TrackedInitializationLimit words
3084 // will be considered for capture by an InitializeNode.  This puts a
3085 // reasonable limit on the complexity of optimized initializations.
3086 
3087 //---------------------------InitializeNode------------------------------------
3088 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
3089   : _is_complete(Incomplete), _does_not_escape(false),
3090     MemBarNode(C, adr_type, rawoop)
3091 {
3092   init_class_id(Class_Initialize);
3093 
3094   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
3095   assert(in(RawAddress) == rawoop, "proper init");
3096   // Note:  allocation() can be NULL, for secondary initialization barriers
3097 }
3098 
3099 // Since this node is not matched, it will be processed by the
3100 // register allocator.  Declare that there are no constraints
3101 // on the allocation of the RawAddress edge.
3102 const RegMask &InitializeNode::in_RegMask(uint idx) const {
3103   // This edge should be set to top, by the set_complete.  But be conservative.
3104   if (idx == InitializeNode::RawAddress)
3105     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
3106   return RegMask::Empty;
3107 }
3108 
3109 Node* InitializeNode::memory(uint alias_idx) {
3110   Node* mem = in(Memory);
3111   if (mem->is_MergeMem()) {
3112     return mem->as_MergeMem()->memory_at(alias_idx);
3113   } else {
3114     // incoming raw memory is not split
3115     return mem;
3116   }
3117 }
3118 
3119 bool InitializeNode::is_non_zero() {
3120   if (is_complete())  return false;
3121   remove_extra_zeroes();
3122   return (req() > RawStores);
3123 }
3124 
3125 void InitializeNode::set_complete(PhaseGVN* phase) {
3126   assert(!is_complete(), "caller responsibility");
3127   _is_complete = Complete;
3128 
3129   // After this node is complete, it contains a bunch of
3130   // raw-memory initializations.  There is no need for
3131   // it to have anything to do with non-raw memory effects.
3132   // Therefore, tell all non-raw users to re-optimize themselves,
3133   // after skipping the memory effects of this initialization.
3134   PhaseIterGVN* igvn = phase->is_IterGVN();
3135   if (igvn)  igvn->add_users_to_worklist(this);
3136 }
3137 
3138 // convenience function
3139 // return false if the init contains any stores already
3140 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
3141   InitializeNode* init = initialization();
3142   if (init == NULL || init->is_complete())  return false;
3143   init->remove_extra_zeroes();
3144   // for now, if this allocation has already collected any inits, bail:
3145   if (init->is_non_zero())  return false;
3146   init->set_complete(phase);
3147   return true;
3148 }
3149 
3150 void InitializeNode::remove_extra_zeroes() {
3151   if (req() == RawStores)  return;
3152   Node* zmem = zero_memory();
3153   uint fill = RawStores;
3154   for (uint i = fill; i < req(); i++) {
3155     Node* n = in(i);
3156     if (n->is_top() || n == zmem)  continue;  // skip
3157     if (fill < i)  set_req(fill, n);          // compact
3158     ++fill;
3159   }
3160   // delete any empty spaces created:
3161   while (fill < req()) {
3162     del_req(fill);
3163   }
3164 }
3165 
3166 // Helper for remembering which stores go with which offsets.
3167 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
3168   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
3169   intptr_t offset = -1;
3170   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
3171                                                phase, offset);
3172   if (base == NULL)     return -1;  // something is dead,
3173   if (offset < 0)       return -1;  //        dead, dead
3174   return offset;
3175 }
3176 
3177 // Helper for proving that an initialization expression is
3178 // "simple enough" to be folded into an object initialization.
3179 // Attempts to prove that a store's initial value 'n' can be captured
3180 // within the initialization without creating a vicious cycle, such as:
3181 //     { Foo p = new Foo(); p.next = p; }
3182 // True for constants and parameters and small combinations thereof.
3183 bool InitializeNode::detect_init_independence(Node* n, int& count) {
3184   if (n == NULL)      return true;   // (can this really happen?)
3185   if (n->is_Proj())   n = n->in(0);
3186   if (n == this)      return false;  // found a cycle
3187   if (n->is_Con())    return true;
3188   if (n->is_Start())  return true;   // params, etc., are OK
3189   if (n->is_Root())   return true;   // even better
3190 
3191   Node* ctl = n->in(0);
3192   if (ctl != NULL && !ctl->is_top()) {
3193     if (ctl->is_Proj())  ctl = ctl->in(0);
3194     if (ctl == this)  return false;
3195 
3196     // If we already know that the enclosing memory op is pinned right after
3197     // the init, then any control flow that the store has picked up
3198     // must have preceded the init, or else be equal to the init.
3199     // Even after loop optimizations (which might change control edges)
3200     // a store is never pinned *before* the availability of its inputs.
3201     if (!MemNode::all_controls_dominate(n, this))
3202       return false;                  // failed to prove a good control
3203   }
3204 
3205   // Check data edges for possible dependencies on 'this'.
3206   if ((count += 1) > 20)  return false;  // complexity limit
3207   for (uint i = 1; i < n->req(); i++) {
3208     Node* m = n->in(i);
3209     if (m == NULL || m == n || m->is_top())  continue;
3210     uint first_i = n->find_edge(m);
3211     if (i != first_i)  continue;  // process duplicate edge just once
3212     if (!detect_init_independence(m, count)) {
3213       return false;
3214     }
3215   }
3216 
3217   return true;
3218 }
3219 
3220 // Here are all the checks a Store must pass before it can be moved into
3221 // an initialization.  Returns zero if a check fails.
3222 // On success, returns the (constant) offset to which the store applies,
3223 // within the initialized memory.
3224 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase, bool can_reshape) {
3225   const int FAIL = 0;
3226   if (st->is_unaligned_access()) {
3227     return FAIL;
3228   }
3229   if (st->req() != MemNode::ValueIn + 1)
3230     return FAIL;                // an inscrutable StoreNode (card mark?)
3231   Node* ctl = st->in(MemNode::Control);
3232   if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
3233     return FAIL;                // must be unconditional after the initialization
3234   Node* mem = st->in(MemNode::Memory);
3235   if (!(mem->is_Proj() && mem->in(0) == this))
3236     return FAIL;                // must not be preceded by other stores
3237   Node* adr = st->in(MemNode::Address);
3238   intptr_t offset;
3239   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
3240   if (alloc == NULL)
3241     return FAIL;                // inscrutable address
3242   if (alloc != allocation())
3243     return FAIL;                // wrong allocation!  (store needs to float up)
3244   Node* val = st->in(MemNode::ValueIn);
3245   int complexity_count = 0;
3246   if (!detect_init_independence(val, complexity_count))
3247     return FAIL;                // stored value must be 'simple enough'
3248 
3249   // The Store can be captured only if nothing after the allocation
3250   // and before the Store is using the memory location that the store
3251   // overwrites.
3252   bool failed = false;
3253   // If is_complete_with_arraycopy() is true the shape of the graph is
3254   // well defined and is safe so no need for extra checks.
3255   if (!is_complete_with_arraycopy()) {
3256     // We are going to look at each use of the memory state following
3257     // the allocation to make sure nothing reads the memory that the
3258     // Store writes.
3259     const TypePtr* t_adr = phase->type(adr)->isa_ptr();
3260     int alias_idx = phase->C->get_alias_index(t_adr);
3261     ResourceMark rm;
3262     Unique_Node_List mems;
3263     mems.push(mem);
3264     Node* unique_merge = NULL;
3265     for (uint next = 0; next < mems.size(); ++next) {
3266       Node *m  = mems.at(next);
3267       for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
3268         Node *n = m->fast_out(j);
3269         if (n->outcnt() == 0) {
3270           continue;
3271         }
3272         if (n == st) {
3273           continue;
3274         } else if (n->in(0) != NULL && n->in(0) != ctl) {
3275           // If the control of this use is different from the control
3276           // of the Store which is right after the InitializeNode then
3277           // this node cannot be between the InitializeNode and the
3278           // Store.
3279           continue;
3280         } else if (n->is_MergeMem()) {
3281           if (n->as_MergeMem()->memory_at(alias_idx) == m) {
3282             // We can hit a MergeMemNode (that will likely go away
3283             // later) that is a direct use of the memory state
3284             // following the InitializeNode on the same slice as the
3285             // store node that we'd like to capture. We need to check
3286             // the uses of the MergeMemNode.
3287             mems.push(n);
3288           }
3289         } else if (n->is_Mem()) {
3290           Node* other_adr = n->in(MemNode::Address);
3291           if (other_adr == adr) {
3292             failed = true;
3293             break;
3294           } else {
3295             const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
3296             if (other_t_adr != NULL) {
3297               int other_alias_idx = phase->C->get_alias_index(other_t_adr);
3298               if (other_alias_idx == alias_idx) {
3299                 // A load from the same memory slice as the store right
3300                 // after the InitializeNode. We check the control of the
3301                 // object/array that is loaded from. If it's the same as
3302                 // the store control then we cannot capture the store.
3303                 assert(!n->is_Store(), "2 stores to same slice on same control?");
3304                 Node* base = other_adr;
3305                 assert(base->is_AddP(), "should be addp but is %s", base->Name());
3306                 base = base->in(AddPNode::Base);
3307                 if (base != NULL) {
3308                   base = base->uncast();
3309                   if (base->is_Proj() && base->in(0) == alloc) {
3310                     failed = true;
3311                     break;
3312                   }
3313                 }
3314               }
3315             }
3316           }
3317         } else {
3318           failed = true;
3319           break;
3320         }
3321       }
3322     }
3323   }
3324   if (failed) {
3325     if (!can_reshape) {
3326       // We decided we couldn't capture the store during parsing. We
3327       // should try again during the next IGVN once the graph is
3328       // cleaner.
3329       phase->C->record_for_igvn(st);
3330     }
3331     return FAIL;
3332   }
3333 
3334   return offset;                // success
3335 }
3336 
3337 // Find the captured store in(i) which corresponds to the range
3338 // [start..start+size) in the initialized object.
3339 // If there is one, return its index i.  If there isn't, return the
3340 // negative of the index where it should be inserted.
3341 // Return 0 if the queried range overlaps an initialization boundary
3342 // or if dead code is encountered.
3343 // If size_in_bytes is zero, do not bother with overlap checks.
3344 int InitializeNode::captured_store_insertion_point(intptr_t start,
3345                                                    int size_in_bytes,
3346                                                    PhaseTransform* phase) {
3347   const int FAIL = 0, MAX_STORE = BytesPerLong;
3348 
3349   if (is_complete())
3350     return FAIL;                // arraycopy got here first; punt
3351 
3352   assert(allocation() != NULL, "must be present");
3353 
3354   // no negatives, no header fields:
3355   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
3356 
3357   // after a certain size, we bail out on tracking all the stores:
3358   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3359   if (start >= ti_limit)  return FAIL;
3360 
3361   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
3362     if (i >= limit)  return -(int)i; // not found; here is where to put it
3363 
3364     Node*    st     = in(i);
3365     intptr_t st_off = get_store_offset(st, phase);
3366     if (st_off < 0) {
3367       if (st != zero_memory()) {
3368         return FAIL;            // bail out if there is dead garbage
3369       }
3370     } else if (st_off > start) {
3371       // ...we are done, since stores are ordered
3372       if (st_off < start + size_in_bytes) {
3373         return FAIL;            // the next store overlaps
3374       }
3375       return -(int)i;           // not found; here is where to put it
3376     } else if (st_off < start) {
3377       if (size_in_bytes != 0 &&
3378           start < st_off + MAX_STORE &&
3379           start < st_off + st->as_Store()->memory_size()) {
3380         return FAIL;            // the previous store overlaps
3381       }
3382     } else {
3383       if (size_in_bytes != 0 &&
3384           st->as_Store()->memory_size() != size_in_bytes) {
3385         return FAIL;            // mismatched store size
3386       }
3387       return i;
3388     }
3389 
3390     ++i;
3391   }
3392 }
3393 
3394 // Look for a captured store which initializes at the offset 'start'
3395 // with the given size.  If there is no such store, and no other
3396 // initialization interferes, then return zero_memory (the memory
3397 // projection of the AllocateNode).
3398 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
3399                                           PhaseTransform* phase) {
3400   assert(stores_are_sane(phase), "");
3401   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3402   if (i == 0) {
3403     return NULL;                // something is dead
3404   } else if (i < 0) {
3405     return zero_memory();       // just primordial zero bits here
3406   } else {
3407     Node* st = in(i);           // here is the store at this position
3408     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
3409     return st;
3410   }
3411 }
3412 
3413 // Create, as a raw pointer, an address within my new object at 'offset'.
3414 Node* InitializeNode::make_raw_address(intptr_t offset,
3415                                        PhaseTransform* phase) {
3416   Node* addr = in(RawAddress);
3417   if (offset != 0) {
3418     Compile* C = phase->C;
3419     addr = phase->transform( new AddPNode(C->top(), addr,
3420                                                  phase->MakeConX(offset)) );
3421   }
3422   return addr;
3423 }
3424 
3425 // Clone the given store, converting it into a raw store
3426 // initializing a field or element of my new object.
3427 // Caller is responsible for retiring the original store,
3428 // with subsume_node or the like.
3429 //
3430 // From the example above InitializeNode::InitializeNode,
3431 // here are the old stores to be captured:
3432 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3433 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3434 //
3435 // Here is the changed code; note the extra edges on init:
3436 //   alloc = (Allocate ...)
3437 //   rawoop = alloc.RawAddress
3438 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
3439 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
3440 //   init = (Initialize alloc.Control alloc.Memory rawoop
3441 //                      rawstore1 rawstore2)
3442 //
3443 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
3444                                     PhaseTransform* phase, bool can_reshape) {
3445   assert(stores_are_sane(phase), "");
3446 
3447   if (start < 0)  return NULL;
3448   assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
3449 
3450   Compile* C = phase->C;
3451   int size_in_bytes = st->memory_size();
3452   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3453   if (i == 0)  return NULL;     // bail out
3454   Node* prev_mem = NULL;        // raw memory for the captured store
3455   if (i > 0) {
3456     prev_mem = in(i);           // there is a pre-existing store under this one
3457     set_req(i, C->top());       // temporarily disconnect it
3458     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
3459   } else {
3460     i = -i;                     // no pre-existing store
3461     prev_mem = zero_memory();   // a slice of the newly allocated object
3462     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
3463       set_req(--i, C->top());   // reuse this edge; it has been folded away
3464     else
3465       ins_req(i, C->top());     // build a new edge
3466   }
3467   Node* new_st = st->clone();
3468   new_st->set_req(MemNode::Control, in(Control));
3469   new_st->set_req(MemNode::Memory,  prev_mem);
3470   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
3471   new_st = phase->transform(new_st);
3472 
3473   // At this point, new_st might have swallowed a pre-existing store
3474   // at the same offset, or perhaps new_st might have disappeared,
3475   // if it redundantly stored the same value (or zero to fresh memory).
3476 
3477   // In any case, wire it in:
3478   phase->igvn_rehash_node_delayed(this);
3479   set_req(i, new_st);
3480 
3481   // The caller may now kill the old guy.
3482   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
3483   assert(check_st == new_st || check_st == NULL, "must be findable");
3484   assert(!is_complete(), "");
3485   return new_st;
3486 }
3487 
3488 static bool store_constant(jlong* tiles, int num_tiles,
3489                            intptr_t st_off, int st_size,
3490                            jlong con) {
3491   if ((st_off & (st_size-1)) != 0)
3492     return false;               // strange store offset (assume size==2**N)
3493   address addr = (address)tiles + st_off;
3494   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
3495   switch (st_size) {
3496   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
3497   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
3498   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
3499   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
3500   default: return false;        // strange store size (detect size!=2**N here)
3501   }
3502   return true;                  // return success to caller
3503 }
3504 
3505 // Coalesce subword constants into int constants and possibly
3506 // into long constants.  The goal, if the CPU permits,
3507 // is to initialize the object with a small number of 64-bit tiles.
3508 // Also, convert floating-point constants to bit patterns.
3509 // Non-constants are not relevant to this pass.
3510 //
3511 // In terms of the running example on InitializeNode::InitializeNode
3512 // and InitializeNode::capture_store, here is the transformation
3513 // of rawstore1 and rawstore2 into rawstore12:
3514 //   alloc = (Allocate ...)
3515 //   rawoop = alloc.RawAddress
3516 //   tile12 = 0x00010002
3517 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
3518 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
3519 //
3520 void
3521 InitializeNode::coalesce_subword_stores(intptr_t header_size,
3522                                         Node* size_in_bytes,
3523                                         PhaseGVN* phase) {
3524   Compile* C = phase->C;
3525 
3526   assert(stores_are_sane(phase), "");
3527   // Note:  After this pass, they are not completely sane,
3528   // since there may be some overlaps.
3529 
3530   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
3531 
3532   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3533   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
3534   size_limit = MIN2(size_limit, ti_limit);
3535   size_limit = align_size_up(size_limit, BytesPerLong);
3536   int num_tiles = size_limit / BytesPerLong;
3537 
3538   // allocate space for the tile map:
3539   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
3540   jlong  tiles_buf[small_len];
3541   Node*  nodes_buf[small_len];
3542   jlong  inits_buf[small_len];
3543   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
3544                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3545   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
3546                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
3547   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
3548                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3549   // tiles: exact bitwise model of all primitive constants
3550   // nodes: last constant-storing node subsumed into the tiles model
3551   // inits: which bytes (in each tile) are touched by any initializations
3552 
3553   //// Pass A: Fill in the tile model with any relevant stores.
3554 
3555   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
3556   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
3557   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
3558   Node* zmem = zero_memory(); // initially zero memory state
3559   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3560     Node* st = in(i);
3561     intptr_t st_off = get_store_offset(st, phase);
3562 
3563     // Figure out the store's offset and constant value:
3564     if (st_off < header_size)             continue; //skip (ignore header)
3565     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
3566     int st_size = st->as_Store()->memory_size();
3567     if (st_off + st_size > size_limit)    break;
3568 
3569     // Record which bytes are touched, whether by constant or not.
3570     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
3571       continue;                 // skip (strange store size)
3572 
3573     const Type* val = phase->type(st->in(MemNode::ValueIn));
3574     if (!val->singleton())                continue; //skip (non-con store)
3575     BasicType type = val->basic_type();
3576 
3577     jlong con = 0;
3578     switch (type) {
3579     case T_INT:    con = val->is_int()->get_con();  break;
3580     case T_LONG:   con = val->is_long()->get_con(); break;
3581     case T_FLOAT:  con = jint_cast(val->getf());    break;
3582     case T_DOUBLE: con = jlong_cast(val->getd());   break;
3583     default:                              continue; //skip (odd store type)
3584     }
3585 
3586     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
3587         st->Opcode() == Op_StoreL) {
3588       continue;                 // This StoreL is already optimal.
3589     }
3590 
3591     // Store down the constant.
3592     store_constant(tiles, num_tiles, st_off, st_size, con);
3593 
3594     intptr_t j = st_off >> LogBytesPerLong;
3595 
3596     if (type == T_INT && st_size == BytesPerInt
3597         && (st_off & BytesPerInt) == BytesPerInt) {
3598       jlong lcon = tiles[j];
3599       if (!Matcher::isSimpleConstant64(lcon) &&
3600           st->Opcode() == Op_StoreI) {
3601         // This StoreI is already optimal by itself.
3602         jint* intcon = (jint*) &tiles[j];
3603         intcon[1] = 0;  // undo the store_constant()
3604 
3605         // If the previous store is also optimal by itself, back up and
3606         // undo the action of the previous loop iteration... if we can.
3607         // But if we can't, just let the previous half take care of itself.
3608         st = nodes[j];
3609         st_off -= BytesPerInt;
3610         con = intcon[0];
3611         if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
3612           assert(st_off >= header_size, "still ignoring header");
3613           assert(get_store_offset(st, phase) == st_off, "must be");
3614           assert(in(i-1) == zmem, "must be");
3615           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
3616           assert(con == tcon->is_int()->get_con(), "must be");
3617           // Undo the effects of the previous loop trip, which swallowed st:
3618           intcon[0] = 0;        // undo store_constant()
3619           set_req(i-1, st);     // undo set_req(i, zmem)
3620           nodes[j] = NULL;      // undo nodes[j] = st
3621           --old_subword;        // undo ++old_subword
3622         }
3623         continue;               // This StoreI is already optimal.
3624       }
3625     }
3626 
3627     // This store is not needed.
3628     set_req(i, zmem);
3629     nodes[j] = st;              // record for the moment
3630     if (st_size < BytesPerLong) // something has changed
3631           ++old_subword;        // includes int/float, but who's counting...
3632     else  ++old_long;
3633   }
3634 
3635   if ((old_subword + old_long) == 0)
3636     return;                     // nothing more to do
3637 
3638   //// Pass B: Convert any non-zero tiles into optimal constant stores.
3639   // Be sure to insert them before overlapping non-constant stores.
3640   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
3641   for (int j = 0; j < num_tiles; j++) {
3642     jlong con  = tiles[j];
3643     jlong init = inits[j];
3644     if (con == 0)  continue;
3645     jint con0,  con1;           // split the constant, address-wise
3646     jint init0, init1;          // split the init map, address-wise
3647     { union { jlong con; jint intcon[2]; } u;
3648       u.con = con;
3649       con0  = u.intcon[0];
3650       con1  = u.intcon[1];
3651       u.con = init;
3652       init0 = u.intcon[0];
3653       init1 = u.intcon[1];
3654     }
3655 
3656     Node* old = nodes[j];
3657     assert(old != NULL, "need the prior store");
3658     intptr_t offset = (j * BytesPerLong);
3659 
3660     bool split = !Matcher::isSimpleConstant64(con);
3661 
3662     if (offset < header_size) {
3663       assert(offset + BytesPerInt >= header_size, "second int counts");
3664       assert(*(jint*)&tiles[j] == 0, "junk in header");
3665       split = true;             // only the second word counts
3666       // Example:  int a[] = { 42 ... }
3667     } else if (con0 == 0 && init0 == -1) {
3668       split = true;             // first word is covered by full inits
3669       // Example:  int a[] = { ... foo(), 42 ... }
3670     } else if (con1 == 0 && init1 == -1) {
3671       split = true;             // second word is covered by full inits
3672       // Example:  int a[] = { ... 42, foo() ... }
3673     }
3674 
3675     // Here's a case where init0 is neither 0 nor -1:
3676     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
3677     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
3678     // In this case the tile is not split; it is (jlong)42.
3679     // The big tile is stored down, and then the foo() value is inserted.
3680     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
3681 
3682     Node* ctl = old->in(MemNode::Control);
3683     Node* adr = make_raw_address(offset, phase);
3684     const TypePtr* atp = TypeRawPtr::BOTTOM;
3685 
3686     // One or two coalesced stores to plop down.
3687     Node*    st[2];
3688     intptr_t off[2];
3689     int  nst = 0;
3690     if (!split) {
3691       ++new_long;
3692       off[nst] = offset;
3693       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3694                                   phase->longcon(con), T_LONG, MemNode::unordered);
3695     } else {
3696       // Omit either if it is a zero.
3697       if (con0 != 0) {
3698         ++new_int;
3699         off[nst]  = offset;
3700         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3701                                     phase->intcon(con0), T_INT, MemNode::unordered);
3702       }
3703       if (con1 != 0) {
3704         ++new_int;
3705         offset += BytesPerInt;
3706         adr = make_raw_address(offset, phase);
3707         off[nst]  = offset;
3708         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3709                                     phase->intcon(con1), T_INT, MemNode::unordered);
3710       }
3711     }
3712 
3713     // Insert second store first, then the first before the second.
3714     // Insert each one just before any overlapping non-constant stores.
3715     while (nst > 0) {
3716       Node* st1 = st[--nst];
3717       C->copy_node_notes_to(st1, old);
3718       st1 = phase->transform(st1);
3719       offset = off[nst];
3720       assert(offset >= header_size, "do not smash header");
3721       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
3722       guarantee(ins_idx != 0, "must re-insert constant store");
3723       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
3724       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
3725         set_req(--ins_idx, st1);
3726       else
3727         ins_req(ins_idx, st1);
3728     }
3729   }
3730 
3731   if (PrintCompilation && WizardMode)
3732     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
3733                   old_subword, old_long, new_int, new_long);
3734   if (C->log() != NULL)
3735     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
3736                    old_subword, old_long, new_int, new_long);
3737 
3738   // Clean up any remaining occurrences of zmem:
3739   remove_extra_zeroes();
3740 }
3741 
3742 // Explore forward from in(start) to find the first fully initialized
3743 // word, and return its offset.  Skip groups of subword stores which
3744 // together initialize full words.  If in(start) is itself part of a
3745 // fully initialized word, return the offset of in(start).  If there
3746 // are no following full-word stores, or if something is fishy, return
3747 // a negative value.
3748 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
3749   int       int_map = 0;
3750   intptr_t  int_map_off = 0;
3751   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
3752 
3753   for (uint i = start, limit = req(); i < limit; i++) {
3754     Node* st = in(i);
3755 
3756     intptr_t st_off = get_store_offset(st, phase);
3757     if (st_off < 0)  break;  // return conservative answer
3758 
3759     int st_size = st->as_Store()->memory_size();
3760     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
3761       return st_off;            // we found a complete word init
3762     }
3763 
3764     // update the map:
3765 
3766     intptr_t this_int_off = align_size_down(st_off, BytesPerInt);
3767     if (this_int_off != int_map_off) {
3768       // reset the map:
3769       int_map = 0;
3770       int_map_off = this_int_off;
3771     }
3772 
3773     int subword_off = st_off - this_int_off;
3774     int_map |= right_n_bits(st_size) << subword_off;
3775     if ((int_map & FULL_MAP) == FULL_MAP) {
3776       return this_int_off;      // we found a complete word init
3777     }
3778 
3779     // Did this store hit or cross the word boundary?
3780     intptr_t next_int_off = align_size_down(st_off + st_size, BytesPerInt);
3781     if (next_int_off == this_int_off + BytesPerInt) {
3782       // We passed the current int, without fully initializing it.
3783       int_map_off = next_int_off;
3784       int_map >>= BytesPerInt;
3785     } else if (next_int_off > this_int_off + BytesPerInt) {
3786       // We passed the current and next int.
3787       return this_int_off + BytesPerInt;
3788     }
3789   }
3790 
3791   return -1;
3792 }
3793 
3794 
3795 // Called when the associated AllocateNode is expanded into CFG.
3796 // At this point, we may perform additional optimizations.
3797 // Linearize the stores by ascending offset, to make memory
3798 // activity as coherent as possible.
3799 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
3800                                       intptr_t header_size,
3801                                       Node* size_in_bytes,
3802                                       PhaseGVN* phase) {
3803   assert(!is_complete(), "not already complete");
3804   assert(stores_are_sane(phase), "");
3805   assert(allocation() != NULL, "must be present");
3806 
3807   remove_extra_zeroes();
3808 
3809   if (ReduceFieldZeroing || ReduceBulkZeroing)
3810     // reduce instruction count for common initialization patterns
3811     coalesce_subword_stores(header_size, size_in_bytes, phase);
3812 
3813   Node* zmem = zero_memory();   // initially zero memory state
3814   Node* inits = zmem;           // accumulating a linearized chain of inits
3815   #ifdef ASSERT
3816   intptr_t first_offset = allocation()->minimum_header_size();
3817   intptr_t last_init_off = first_offset;  // previous init offset
3818   intptr_t last_init_end = first_offset;  // previous init offset+size
3819   intptr_t last_tile_end = first_offset;  // previous tile offset+size
3820   #endif
3821   intptr_t zeroes_done = header_size;
3822 
3823   bool do_zeroing = true;       // we might give up if inits are very sparse
3824   int  big_init_gaps = 0;       // how many large gaps have we seen?
3825 
3826   if (UseTLAB && ZeroTLAB)  do_zeroing = false;
3827   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
3828 
3829   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3830     Node* st = in(i);
3831     intptr_t st_off = get_store_offset(st, phase);
3832     if (st_off < 0)
3833       break;                    // unknown junk in the inits
3834     if (st->in(MemNode::Memory) != zmem)
3835       break;                    // complicated store chains somehow in list
3836 
3837     int st_size = st->as_Store()->memory_size();
3838     intptr_t next_init_off = st_off + st_size;
3839 
3840     if (do_zeroing && zeroes_done < next_init_off) {
3841       // See if this store needs a zero before it or under it.
3842       intptr_t zeroes_needed = st_off;
3843 
3844       if (st_size < BytesPerInt) {
3845         // Look for subword stores which only partially initialize words.
3846         // If we find some, we must lay down some word-level zeroes first,
3847         // underneath the subword stores.
3848         //
3849         // Examples:
3850         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
3851         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
3852         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
3853         //
3854         // Note:  coalesce_subword_stores may have already done this,
3855         // if it was prompted by constant non-zero subword initializers.
3856         // But this case can still arise with non-constant stores.
3857 
3858         intptr_t next_full_store = find_next_fullword_store(i, phase);
3859 
3860         // In the examples above:
3861         //   in(i)          p   q   r   s     x   y     z
3862         //   st_off        12  13  14  15    12  13    14
3863         //   st_size        1   1   1   1     1   1     1
3864         //   next_full_s.  12  16  16  16    16  16    16
3865         //   z's_done      12  16  16  16    12  16    12
3866         //   z's_needed    12  16  16  16    16  16    16
3867         //   zsize          0   0   0   0     4   0     4
3868         if (next_full_store < 0) {
3869           // Conservative tack:  Zero to end of current word.
3870           zeroes_needed = align_size_up(zeroes_needed, BytesPerInt);
3871         } else {
3872           // Zero to beginning of next fully initialized word.
3873           // Or, don't zero at all, if we are already in that word.
3874           assert(next_full_store >= zeroes_needed, "must go forward");
3875           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
3876           zeroes_needed = next_full_store;
3877         }
3878       }
3879 
3880       if (zeroes_needed > zeroes_done) {
3881         intptr_t zsize = zeroes_needed - zeroes_done;
3882         // Do some incremental zeroing on rawmem, in parallel with inits.
3883         zeroes_done = align_size_down(zeroes_done, BytesPerInt);
3884         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3885                                               zeroes_done, zeroes_needed,
3886                                               phase);
3887         zeroes_done = zeroes_needed;
3888         if (zsize > InitArrayShortSize && ++big_init_gaps > 2)
3889           do_zeroing = false;   // leave the hole, next time
3890       }
3891     }
3892 
3893     // Collect the store and move on:
3894     st->set_req(MemNode::Memory, inits);
3895     inits = st;                 // put it on the linearized chain
3896     set_req(i, zmem);           // unhook from previous position
3897 
3898     if (zeroes_done == st_off)
3899       zeroes_done = next_init_off;
3900 
3901     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
3902 
3903     #ifdef ASSERT
3904     // Various order invariants.  Weaker than stores_are_sane because
3905     // a large constant tile can be filled in by smaller non-constant stores.
3906     assert(st_off >= last_init_off, "inits do not reverse");
3907     last_init_off = st_off;
3908     const Type* val = NULL;
3909     if (st_size >= BytesPerInt &&
3910         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
3911         (int)val->basic_type() < (int)T_OBJECT) {
3912       assert(st_off >= last_tile_end, "tiles do not overlap");
3913       assert(st_off >= last_init_end, "tiles do not overwrite inits");
3914       last_tile_end = MAX2(last_tile_end, next_init_off);
3915     } else {
3916       intptr_t st_tile_end = align_size_up(next_init_off, BytesPerLong);
3917       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
3918       assert(st_off      >= last_init_end, "inits do not overlap");
3919       last_init_end = next_init_off;  // it's a non-tile
3920     }
3921     #endif //ASSERT
3922   }
3923 
3924   remove_extra_zeroes();        // clear out all the zmems left over
3925   add_req(inits);
3926 
3927   if (!(UseTLAB && ZeroTLAB)) {
3928     // If anything remains to be zeroed, zero it all now.
3929     zeroes_done = align_size_down(zeroes_done, BytesPerInt);
3930     // if it is the last unused 4 bytes of an instance, forget about it
3931     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
3932     if (zeroes_done + BytesPerLong >= size_limit) {
3933       assert(allocation() != NULL, "");
3934       if (allocation()->Opcode() == Op_Allocate) {
3935         Node* klass_node = allocation()->in(AllocateNode::KlassNode);
3936         ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
3937         if (zeroes_done == k->layout_helper())
3938           zeroes_done = size_limit;
3939       }
3940     }
3941     if (zeroes_done < size_limit) {
3942       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3943                                             zeroes_done, size_in_bytes, phase);
3944     }
3945   }
3946 
3947   set_complete(phase);
3948   return rawmem;
3949 }
3950 
3951 
3952 #ifdef ASSERT
3953 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
3954   if (is_complete())
3955     return true;                // stores could be anything at this point
3956   assert(allocation() != NULL, "must be present");
3957   intptr_t last_off = allocation()->minimum_header_size();
3958   for (uint i = InitializeNode::RawStores; i < req(); i++) {
3959     Node* st = in(i);
3960     intptr_t st_off = get_store_offset(st, phase);
3961     if (st_off < 0)  continue;  // ignore dead garbage
3962     if (last_off > st_off) {
3963       tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
3964       this->dump(2);
3965       assert(false, "ascending store offsets");
3966       return false;
3967     }
3968     last_off = st_off + st->as_Store()->memory_size();
3969   }
3970   return true;
3971 }
3972 #endif //ASSERT
3973 
3974 
3975 
3976 
3977 //============================MergeMemNode=====================================
3978 //
3979 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
3980 // contributing store or call operations.  Each contributor provides the memory
3981 // state for a particular "alias type" (see Compile::alias_type).  For example,
3982 // if a MergeMem has an input X for alias category #6, then any memory reference
3983 // to alias category #6 may use X as its memory state input, as an exact equivalent
3984 // to using the MergeMem as a whole.
3985 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
3986 //
3987 // (Here, the <N> notation gives the index of the relevant adr_type.)
3988 //
3989 // In one special case (and more cases in the future), alias categories overlap.
3990 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
3991 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
3992 // it is exactly equivalent to that state W:
3993 //   MergeMem(<Bot>: W) <==> W
3994 //
3995 // Usually, the merge has more than one input.  In that case, where inputs
3996 // overlap (i.e., one is Bot), the narrower alias type determines the memory
3997 // state for that type, and the wider alias type (Bot) fills in everywhere else:
3998 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
3999 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
4000 //
4001 // A merge can take a "wide" memory state as one of its narrow inputs.
4002 // This simply means that the merge observes out only the relevant parts of
4003 // the wide input.  That is, wide memory states arriving at narrow merge inputs
4004 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
4005 //
4006 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
4007 // and that memory slices "leak through":
4008 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
4009 //
4010 // But, in such a cascade, repeated memory slices can "block the leak":
4011 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
4012 //
4013 // In the last example, Y is not part of the combined memory state of the
4014 // outermost MergeMem.  The system must, of course, prevent unschedulable
4015 // memory states from arising, so you can be sure that the state Y is somehow
4016 // a precursor to state Y'.
4017 //
4018 //
4019 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
4020 // of each MergeMemNode array are exactly the numerical alias indexes, including
4021 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
4022 // Compile::alias_type (and kin) produce and manage these indexes.
4023 //
4024 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
4025 // (Note that this provides quick access to the top node inside MergeMem methods,
4026 // without the need to reach out via TLS to Compile::current.)
4027 //
4028 // As a consequence of what was just described, a MergeMem that represents a full
4029 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
4030 // containing all alias categories.
4031 //
4032 // MergeMem nodes never (?) have control inputs, so in(0) is NULL.
4033 //
4034 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
4035 // a memory state for the alias type <N>, or else the top node, meaning that
4036 // there is no particular input for that alias type.  Note that the length of
4037 // a MergeMem is variable, and may be extended at any time to accommodate new
4038 // memory states at larger alias indexes.  When merges grow, they are of course
4039 // filled with "top" in the unused in() positions.
4040 //
4041 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
4042 // (Top was chosen because it works smoothly with passes like GCM.)
4043 //
4044 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
4045 // the type of random VM bits like TLS references.)  Since it is always the
4046 // first non-Bot memory slice, some low-level loops use it to initialize an
4047 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
4048 //
4049 //
4050 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
4051 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
4052 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
4053 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
4054 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
4055 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
4056 //
4057 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
4058 // really that different from the other memory inputs.  An abbreviation called
4059 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
4060 //
4061 //
4062 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
4063 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
4064 // that "emerges though" the base memory will be marked as excluding the alias types
4065 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
4066 //
4067 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
4068 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
4069 //
4070 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
4071 // (It is currently unimplemented.)  As you can see, the resulting merge is
4072 // actually a disjoint union of memory states, rather than an overlay.
4073 //
4074 
4075 //------------------------------MergeMemNode-----------------------------------
4076 Node* MergeMemNode::make_empty_memory() {
4077   Node* empty_memory = (Node*) Compile::current()->top();
4078   assert(empty_memory->is_top(), "correct sentinel identity");
4079   return empty_memory;
4080 }
4081 
4082 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
4083   init_class_id(Class_MergeMem);
4084   // all inputs are nullified in Node::Node(int)
4085   // set_input(0, NULL);  // no control input
4086 
4087   // Initialize the edges uniformly to top, for starters.
4088   Node* empty_mem = make_empty_memory();
4089   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
4090     init_req(i,empty_mem);
4091   }
4092   assert(empty_memory() == empty_mem, "");
4093 
4094   if( new_base != NULL && new_base->is_MergeMem() ) {
4095     MergeMemNode* mdef = new_base->as_MergeMem();
4096     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
4097     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
4098       mms.set_memory(mms.memory2());
4099     }
4100     assert(base_memory() == mdef->base_memory(), "");
4101   } else {
4102     set_base_memory(new_base);
4103   }
4104 }
4105 
4106 // Make a new, untransformed MergeMem with the same base as 'mem'.
4107 // If mem is itself a MergeMem, populate the result with the same edges.
4108 MergeMemNode* MergeMemNode::make(Node* mem) {
4109   return new MergeMemNode(mem);
4110 }
4111 
4112 //------------------------------cmp--------------------------------------------
4113 uint MergeMemNode::hash() const { return NO_HASH; }
4114 uint MergeMemNode::cmp( const Node &n ) const {
4115   return (&n == this);          // Always fail except on self
4116 }
4117 
4118 //------------------------------Identity---------------------------------------
4119 Node* MergeMemNode::Identity(PhaseGVN* phase) {
4120   // Identity if this merge point does not record any interesting memory
4121   // disambiguations.
4122   Node* base_mem = base_memory();
4123   Node* empty_mem = empty_memory();
4124   if (base_mem != empty_mem) {  // Memory path is not dead?
4125     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4126       Node* mem = in(i);
4127       if (mem != empty_mem && mem != base_mem) {
4128         return this;            // Many memory splits; no change
4129       }
4130     }
4131   }
4132   return base_mem;              // No memory splits; ID on the one true input
4133 }
4134 
4135 //------------------------------Ideal------------------------------------------
4136 // This method is invoked recursively on chains of MergeMem nodes
4137 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4138   // Remove chain'd MergeMems
4139   //
4140   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
4141   // relative to the "in(Bot)".  Since we are patching both at the same time,
4142   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
4143   // but rewrite each "in(i)" relative to the new "in(Bot)".
4144   Node *progress = NULL;
4145 
4146 
4147   Node* old_base = base_memory();
4148   Node* empty_mem = empty_memory();
4149   if (old_base == empty_mem)
4150     return NULL; // Dead memory path.
4151 
4152   MergeMemNode* old_mbase;
4153   if (old_base != NULL && old_base->is_MergeMem())
4154     old_mbase = old_base->as_MergeMem();
4155   else
4156     old_mbase = NULL;
4157   Node* new_base = old_base;
4158 
4159   // simplify stacked MergeMems in base memory
4160   if (old_mbase)  new_base = old_mbase->base_memory();
4161 
4162   // the base memory might contribute new slices beyond my req()
4163   if (old_mbase)  grow_to_match(old_mbase);
4164 
4165   // Look carefully at the base node if it is a phi.
4166   PhiNode* phi_base;
4167   if (new_base != NULL && new_base->is_Phi())
4168     phi_base = new_base->as_Phi();
4169   else
4170     phi_base = NULL;
4171 
4172   Node*    phi_reg = NULL;
4173   uint     phi_len = (uint)-1;
4174   if (phi_base != NULL && !phi_base->is_copy()) {
4175     // do not examine phi if degraded to a copy
4176     phi_reg = phi_base->region();
4177     phi_len = phi_base->req();
4178     // see if the phi is unfinished
4179     for (uint i = 1; i < phi_len; i++) {
4180       if (phi_base->in(i) == NULL) {
4181         // incomplete phi; do not look at it yet!
4182         phi_reg = NULL;
4183         phi_len = (uint)-1;
4184         break;
4185       }
4186     }
4187   }
4188 
4189   // Note:  We do not call verify_sparse on entry, because inputs
4190   // can normalize to the base_memory via subsume_node or similar
4191   // mechanisms.  This method repairs that damage.
4192 
4193   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
4194 
4195   // Look at each slice.
4196   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4197     Node* old_in = in(i);
4198     // calculate the old memory value
4199     Node* old_mem = old_in;
4200     if (old_mem == empty_mem)  old_mem = old_base;
4201     assert(old_mem == memory_at(i), "");
4202 
4203     // maybe update (reslice) the old memory value
4204 
4205     // simplify stacked MergeMems
4206     Node* new_mem = old_mem;
4207     MergeMemNode* old_mmem;
4208     if (old_mem != NULL && old_mem->is_MergeMem())
4209       old_mmem = old_mem->as_MergeMem();
4210     else
4211       old_mmem = NULL;
4212     if (old_mmem == this) {
4213       // This can happen if loops break up and safepoints disappear.
4214       // A merge of BotPtr (default) with a RawPtr memory derived from a
4215       // safepoint can be rewritten to a merge of the same BotPtr with
4216       // the BotPtr phi coming into the loop.  If that phi disappears
4217       // also, we can end up with a self-loop of the mergemem.
4218       // In general, if loops degenerate and memory effects disappear,
4219       // a mergemem can be left looking at itself.  This simply means
4220       // that the mergemem's default should be used, since there is
4221       // no longer any apparent effect on this slice.
4222       // Note: If a memory slice is a MergeMem cycle, it is unreachable
4223       //       from start.  Update the input to TOP.
4224       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
4225     }
4226     else if (old_mmem != NULL) {
4227       new_mem = old_mmem->memory_at(i);
4228     }
4229     // else preceding memory was not a MergeMem
4230 
4231     // replace equivalent phis (unfortunately, they do not GVN together)
4232     if (new_mem != NULL && new_mem != new_base &&
4233         new_mem->req() == phi_len && new_mem->in(0) == phi_reg) {
4234       if (new_mem->is_Phi()) {
4235         PhiNode* phi_mem = new_mem->as_Phi();
4236         for (uint i = 1; i < phi_len; i++) {
4237           if (phi_base->in(i) != phi_mem->in(i)) {
4238             phi_mem = NULL;
4239             break;
4240           }
4241         }
4242         if (phi_mem != NULL) {
4243           // equivalent phi nodes; revert to the def
4244           new_mem = new_base;
4245         }
4246       }
4247     }
4248 
4249     // maybe store down a new value
4250     Node* new_in = new_mem;
4251     if (new_in == new_base)  new_in = empty_mem;
4252 
4253     if (new_in != old_in) {
4254       // Warning:  Do not combine this "if" with the previous "if"
4255       // A memory slice might have be be rewritten even if it is semantically
4256       // unchanged, if the base_memory value has changed.
4257       set_req(i, new_in);
4258       progress = this;          // Report progress
4259     }
4260   }
4261 
4262   if (new_base != old_base) {
4263     set_req(Compile::AliasIdxBot, new_base);
4264     // Don't use set_base_memory(new_base), because we need to update du.
4265     assert(base_memory() == new_base, "");
4266     progress = this;
4267   }
4268 
4269   if( base_memory() == this ) {
4270     // a self cycle indicates this memory path is dead
4271     set_req(Compile::AliasIdxBot, empty_mem);
4272   }
4273 
4274   // Resolve external cycles by calling Ideal on a MergeMem base_memory
4275   // Recursion must occur after the self cycle check above
4276   if( base_memory()->is_MergeMem() ) {
4277     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
4278     Node *m = phase->transform(new_mbase);  // Rollup any cycles
4279     if( m != NULL && (m->is_top() ||
4280         m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem) ) {
4281       // propagate rollup of dead cycle to self
4282       set_req(Compile::AliasIdxBot, empty_mem);
4283     }
4284   }
4285 
4286   if( base_memory() == empty_mem ) {
4287     progress = this;
4288     // Cut inputs during Parse phase only.
4289     // During Optimize phase a dead MergeMem node will be subsumed by Top.
4290     if( !can_reshape ) {
4291       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4292         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
4293       }
4294     }
4295   }
4296 
4297   if( !progress && base_memory()->is_Phi() && can_reshape ) {
4298     // Check if PhiNode::Ideal's "Split phis through memory merges"
4299     // transform should be attempted. Look for this->phi->this cycle.
4300     uint merge_width = req();
4301     if (merge_width > Compile::AliasIdxRaw) {
4302       PhiNode* phi = base_memory()->as_Phi();
4303       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
4304         if (phi->in(i) == this) {
4305           phase->is_IterGVN()->_worklist.push(phi);
4306           break;
4307         }
4308       }
4309     }
4310   }
4311 
4312   assert(progress || verify_sparse(), "please, no dups of base");
4313   return progress;
4314 }
4315 
4316 //-------------------------set_base_memory-------------------------------------
4317 void MergeMemNode::set_base_memory(Node *new_base) {
4318   Node* empty_mem = empty_memory();
4319   set_req(Compile::AliasIdxBot, new_base);
4320   assert(memory_at(req()) == new_base, "must set default memory");
4321   // Clear out other occurrences of new_base:
4322   if (new_base != empty_mem) {
4323     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4324       if (in(i) == new_base)  set_req(i, empty_mem);
4325     }
4326   }
4327 }
4328 
4329 //------------------------------out_RegMask------------------------------------
4330 const RegMask &MergeMemNode::out_RegMask() const {
4331   return RegMask::Empty;
4332 }
4333 
4334 //------------------------------dump_spec--------------------------------------
4335 #ifndef PRODUCT
4336 void MergeMemNode::dump_spec(outputStream *st) const {
4337   st->print(" {");
4338   Node* base_mem = base_memory();
4339   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
4340     Node* mem = (in(i) != NULL) ? memory_at(i) : base_mem;
4341     if (mem == base_mem) { st->print(" -"); continue; }
4342     st->print( " N%d:", mem->_idx );
4343     Compile::current()->get_adr_type(i)->dump_on(st);
4344   }
4345   st->print(" }");
4346 }
4347 #endif // !PRODUCT
4348 
4349 
4350 #ifdef ASSERT
4351 static bool might_be_same(Node* a, Node* b) {
4352   if (a == b)  return true;
4353   if (!(a->is_Phi() || b->is_Phi()))  return false;
4354   // phis shift around during optimization
4355   return true;  // pretty stupid...
4356 }
4357 
4358 // verify a narrow slice (either incoming or outgoing)
4359 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
4360   if (!VerifyAliases)       return;  // don't bother to verify unless requested
4361   if (is_error_reported())  return;  // muzzle asserts when debugging an error
4362   if (Node::in_dump())      return;  // muzzle asserts when printing
4363   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
4364   assert(n != NULL, "");
4365   // Elide intervening MergeMem's
4366   while (n->is_MergeMem()) {
4367     n = n->as_MergeMem()->memory_at(alias_idx);
4368   }
4369   Compile* C = Compile::current();
4370   const TypePtr* n_adr_type = n->adr_type();
4371   if (n == m->empty_memory()) {
4372     // Implicit copy of base_memory()
4373   } else if (n_adr_type != TypePtr::BOTTOM) {
4374     assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
4375     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
4376   } else {
4377     // A few places like make_runtime_call "know" that VM calls are narrow,
4378     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
4379     bool expected_wide_mem = false;
4380     if (n == m->base_memory()) {
4381       expected_wide_mem = true;
4382     } else if (alias_idx == Compile::AliasIdxRaw ||
4383                n == m->memory_at(Compile::AliasIdxRaw)) {
4384       expected_wide_mem = true;
4385     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
4386       // memory can "leak through" calls on channels that
4387       // are write-once.  Allow this also.
4388       expected_wide_mem = true;
4389     }
4390     assert(expected_wide_mem, "expected narrow slice replacement");
4391   }
4392 }
4393 #else // !ASSERT
4394 #define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
4395 #endif
4396 
4397 
4398 //-----------------------------memory_at---------------------------------------
4399 Node* MergeMemNode::memory_at(uint alias_idx) const {
4400   assert(alias_idx >= Compile::AliasIdxRaw ||
4401          alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
4402          "must avoid base_memory and AliasIdxTop");
4403 
4404   // Otherwise, it is a narrow slice.
4405   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
4406   Compile *C = Compile::current();
4407   if (is_empty_memory(n)) {
4408     // the array is sparse; empty slots are the "top" node
4409     n = base_memory();
4410     assert(Node::in_dump()
4411            || n == NULL || n->bottom_type() == Type::TOP
4412            || n->adr_type() == NULL // address is TOP
4413            || n->adr_type() == TypePtr::BOTTOM
4414            || n->adr_type() == TypeRawPtr::BOTTOM
4415            || Compile::current()->AliasLevel() == 0,
4416            "must be a wide memory");
4417     // AliasLevel == 0 if we are organizing the memory states manually.
4418     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
4419   } else {
4420     // make sure the stored slice is sane
4421     #ifdef ASSERT
4422     if (is_error_reported() || Node::in_dump()) {
4423     } else if (might_be_same(n, base_memory())) {
4424       // Give it a pass:  It is a mostly harmless repetition of the base.
4425       // This can arise normally from node subsumption during optimization.
4426     } else {
4427       verify_memory_slice(this, alias_idx, n);
4428     }
4429     #endif
4430   }
4431   return n;
4432 }
4433 
4434 //---------------------------set_memory_at-------------------------------------
4435 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
4436   verify_memory_slice(this, alias_idx, n);
4437   Node* empty_mem = empty_memory();
4438   if (n == base_memory())  n = empty_mem;  // collapse default
4439   uint need_req = alias_idx+1;
4440   if (req() < need_req) {
4441     if (n == empty_mem)  return;  // already the default, so do not grow me
4442     // grow the sparse array
4443     do {
4444       add_req(empty_mem);
4445     } while (req() < need_req);
4446   }
4447   set_req( alias_idx, n );
4448 }
4449 
4450 
4451 
4452 //--------------------------iteration_setup------------------------------------
4453 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
4454   if (other != NULL) {
4455     grow_to_match(other);
4456     // invariant:  the finite support of mm2 is within mm->req()
4457     #ifdef ASSERT
4458     for (uint i = req(); i < other->req(); i++) {
4459       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
4460     }
4461     #endif
4462   }
4463   // Replace spurious copies of base_memory by top.
4464   Node* base_mem = base_memory();
4465   if (base_mem != NULL && !base_mem->is_top()) {
4466     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
4467       if (in(i) == base_mem)
4468         set_req(i, empty_memory());
4469     }
4470   }
4471 }
4472 
4473 //---------------------------grow_to_match-------------------------------------
4474 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
4475   Node* empty_mem = empty_memory();
4476   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
4477   // look for the finite support of the other memory
4478   for (uint i = other->req(); --i >= req(); ) {
4479     if (other->in(i) != empty_mem) {
4480       uint new_len = i+1;
4481       while (req() < new_len)  add_req(empty_mem);
4482       break;
4483     }
4484   }
4485 }
4486 
4487 //---------------------------verify_sparse-------------------------------------
4488 #ifndef PRODUCT
4489 bool MergeMemNode::verify_sparse() const {
4490   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
4491   Node* base_mem = base_memory();
4492   // The following can happen in degenerate cases, since empty==top.
4493   if (is_empty_memory(base_mem))  return true;
4494   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4495     assert(in(i) != NULL, "sane slice");
4496     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
4497   }
4498   return true;
4499 }
4500 
4501 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
4502   Node* n;
4503   n = mm->in(idx);
4504   if (mem == n)  return true;  // might be empty_memory()
4505   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
4506   if (mem == n)  return true;
4507   while (n->is_Phi() && (n = n->as_Phi()->is_copy()) != NULL) {
4508     if (mem == n)  return true;
4509     if (n == NULL)  break;
4510   }
4511   return false;
4512 }
4513 #endif // !PRODUCT
--- EOF ---