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