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