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