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