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