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       ciArrayKlass* ak = tary_klass->as_array_klass();
2244       // Do not fold klass loads from [V? because the runtime type might be [V due to [V <: [V?
2245       bool can_be_flattened = ak->is_obj_array_klass() && !ak->storage_properties().is_null_free() && ak->element_klass()->is_valuetype();
2246 
2247       if (tary->klass_is_exact() && !can_be_flattened) {
2248         return TypeKlassPtr::make(tary_klass);
2249       }
2250 
2251       // If the klass is an object array, we defer the question to the
2252       // array component klass.
2253       if (ak->is_obj_array_klass() && !can_be_flattened) {
2254         assert(ak->is_loaded(), "");
2255         ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
2256         if (base_k->is_loaded() && base_k->is_instance_klass()) {
2257           ciInstanceKlass *ik = base_k->as_instance_klass();
2258           // See if we can become precise: no subklasses and no interface
2259           if (!ik->is_interface() && !ik->has_subklass()) {
2260             //assert(!UseExactTypes, "this code should be useless with exact types");
2261             // Add a dependence; if any subclass added we need to recompile
2262             if (!ik->is_final()) {
2263               phase->C->dependencies()->assert_leaf_type(ik);
2264             }
2265             // Return precise array klass
2266             return TypeKlassPtr::make(ak);
2267           }
2268         }
2269         return TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
2270       } else if (ak->is_type_array_klass()) {
2271         //assert(!UseExactTypes, "this code should be useless with exact types");
2272         return TypeKlassPtr::make(ak); // These are always precise
2273       }
2274     }
2275   }
2276 
2277   // Check for loading klass from an array klass
2278   const TypeKlassPtr *tkls = tp->isa_klassptr();
2279   if (tkls != NULL && !StressReflectiveCode) {
2280     if (!tkls->is_loaded()) {
2281       return _type;             // Bail out if not loaded
2282     }
2283     ciKlass* klass = tkls->klass();
2284     if( klass->is_obj_array_klass() &&
2285         tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
2286       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
2287       // // Always returning precise element type is incorrect,
2288       // // e.g., element type could be object and array may contain strings
2289       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
2290 
2291       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
2292       // according to the element type's subclassing.
2293       return TypeKlassPtr::make(tkls->ptr(), elem, Type::Offset(0));
2294     } else if (klass->is_value_array_klass() &&
2295                tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
2296       ciKlass* elem = klass->as_value_array_klass()->element_klass();
2297       return TypeKlassPtr::make(tkls->ptr(), elem, Type::Offset(0));
2298     }
2299     if( klass->is_instance_klass() && tkls->klass_is_exact() &&
2300         tkls->offset() == in_bytes(Klass::super_offset())) {
2301       ciKlass* sup = klass->as_instance_klass()->super();
2302       // The field is Klass::_super.  Return its (constant) value.
2303       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
2304       return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
2305     }
2306   }
2307 
2308   // Bailout case
2309   return LoadNode::Value(phase);
2310 }
2311 
2312 //------------------------------Identity---------------------------------------
2313 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
2314 // Also feed through the klass in Allocate(...klass...)._klass.
2315 Node* LoadKlassNode::Identity(PhaseGVN* phase) {
2316   return klass_identity_common(phase);
2317 }
2318 
2319 Node* LoadNode::klass_identity_common(PhaseGVN* phase) {
2320   Node* x = LoadNode::Identity(phase);
2321   if (x != this)  return x;
2322 
2323   // Take apart the address into an oop and and offset.
2324   // Return 'this' if we cannot.
2325   Node*    adr    = in(MemNode::Address);
2326   intptr_t offset = 0;
2327   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2328   if (base == NULL)     return this;
2329   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
2330   if (toop == NULL)     return this;
2331 
2332   // Step over potential GC barrier for OopHandle resolve
2333   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2334   if (bs->is_gc_barrier_node(base)) {
2335     base = bs->step_over_gc_barrier(base);
2336   }
2337 
2338   // We can fetch the klass directly through an AllocateNode.
2339   // This works even if the klass is not constant (clone or newArray).
2340   if (offset == oopDesc::klass_offset_in_bytes()) {
2341     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
2342     if (allocated_klass != NULL) {
2343       return allocated_klass;
2344     }
2345   }
2346 
2347   // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
2348   // See inline_native_Class_query for occurrences of these patterns.
2349   // Java Example:  x.getClass().isAssignableFrom(y)
2350   //
2351   // This improves reflective code, often making the Class
2352   // mirror go completely dead.  (Current exception:  Class
2353   // mirrors may appear in debug info, but we could clean them out by
2354   // introducing a new debug info operator for Klass.java_mirror).
2355 
2356   if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
2357       && offset == java_lang_Class::klass_offset_in_bytes()) {
2358     if (base->is_Load()) {
2359       Node* base2 = base->in(MemNode::Address);
2360       if (base2->is_Load()) { /* direct load of a load which is the OopHandle */
2361         Node* adr2 = base2->in(MemNode::Address);
2362         const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2363         if (tkls != NULL && !tkls->empty()
2364             && (tkls->klass()->is_instance_klass() ||
2365               tkls->klass()->is_array_klass())
2366             && adr2->is_AddP()
2367            ) {
2368           int mirror_field = in_bytes(Klass::java_mirror_offset());
2369           if (tkls->offset() == mirror_field) {
2370             return adr2->in(AddPNode::Base);
2371           }
2372         }
2373       }
2374     }
2375   }
2376 
2377   return this;
2378 }
2379 
2380 
2381 //------------------------------Value------------------------------------------
2382 const Type* LoadNKlassNode::Value(PhaseGVN* phase) const {
2383   const Type *t = klass_value_common(phase);
2384   if (t == Type::TOP)
2385     return t;
2386 
2387   return t->make_narrowklass();
2388 }
2389 
2390 //------------------------------Identity---------------------------------------
2391 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
2392 // Also feed through the klass in Allocate(...klass...)._klass.
2393 Node* LoadNKlassNode::Identity(PhaseGVN* phase) {
2394   Node *x = klass_identity_common(phase);
2395 
2396   const Type *t = phase->type( x );
2397   if( t == Type::TOP ) return x;
2398   if( t->isa_narrowklass()) return x;
2399   assert (!t->isa_narrowoop(), "no narrow oop here");
2400 
2401   return phase->transform(new EncodePKlassNode(x, t->make_narrowklass()));
2402 }
2403 
2404 //------------------------------Value-----------------------------------------
2405 const Type* LoadRangeNode::Value(PhaseGVN* phase) const {
2406   // Either input is TOP ==> the result is TOP
2407   const Type *t1 = phase->type( in(MemNode::Memory) );
2408   if( t1 == Type::TOP ) return Type::TOP;
2409   Node *adr = in(MemNode::Address);
2410   const Type *t2 = phase->type( adr );
2411   if( t2 == Type::TOP ) return Type::TOP;
2412   const TypePtr *tp = t2->is_ptr();
2413   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
2414   const TypeAryPtr *tap = tp->isa_aryptr();
2415   if( !tap ) return _type;
2416   return tap->size();
2417 }
2418 
2419 //-------------------------------Ideal---------------------------------------
2420 // Feed through the length in AllocateArray(...length...)._length.
2421 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2422   Node* p = MemNode::Ideal_common(phase, can_reshape);
2423   if (p)  return (p == NodeSentinel) ? NULL : p;
2424 
2425   // Take apart the address into an oop and and offset.
2426   // Return 'this' if we cannot.
2427   Node*    adr    = in(MemNode::Address);
2428   intptr_t offset = 0;
2429   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase,  offset);
2430   if (base == NULL)     return NULL;
2431   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2432   if (tary == NULL)     return NULL;
2433 
2434   // We can fetch the length directly through an AllocateArrayNode.
2435   // This works even if the length is not constant (clone or newArray).
2436   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2437     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2438     if (alloc != NULL) {
2439       Node* allocated_length = alloc->Ideal_length();
2440       Node* len = alloc->make_ideal_length(tary, phase);
2441       if (allocated_length != len) {
2442         // New CastII improves on this.
2443         return len;
2444       }
2445     }
2446   }
2447 
2448   return NULL;
2449 }
2450 
2451 //------------------------------Identity---------------------------------------
2452 // Feed through the length in AllocateArray(...length...)._length.
2453 Node* LoadRangeNode::Identity(PhaseGVN* phase) {
2454   Node* x = LoadINode::Identity(phase);
2455   if (x != this)  return x;
2456 
2457   // Take apart the address into an oop and and offset.
2458   // Return 'this' if we cannot.
2459   Node*    adr    = in(MemNode::Address);
2460   intptr_t offset = 0;
2461   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2462   if (base == NULL)     return this;
2463   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2464   if (tary == NULL)     return this;
2465 
2466   // We can fetch the length directly through an AllocateArrayNode.
2467   // This works even if the length is not constant (clone or newArray).
2468   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2469     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2470     if (alloc != NULL) {
2471       Node* allocated_length = alloc->Ideal_length();
2472       // Do not allow make_ideal_length to allocate a CastII node.
2473       Node* len = alloc->make_ideal_length(tary, phase, false);
2474       if (allocated_length == len) {
2475         // Return allocated_length only if it would not be improved by a CastII.
2476         return allocated_length;
2477       }
2478     }
2479   }
2480 
2481   return this;
2482 
2483 }
2484 
2485 //=============================================================================
2486 //---------------------------StoreNode::make-----------------------------------
2487 // Polymorphic factory method:
2488 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo) {
2489   assert((mo == unordered || mo == release), "unexpected");
2490   Compile* C = gvn.C;
2491   assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
2492          ctl != NULL, "raw memory operations should have control edge");
2493 
2494   switch (bt) {
2495   case T_BOOLEAN: val = gvn.transform(new AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case
2496   case T_BYTE:    return new StoreBNode(ctl, mem, adr, adr_type, val, mo);
2497   case T_INT:     return new StoreINode(ctl, mem, adr, adr_type, val, mo);
2498   case T_CHAR:
2499   case T_SHORT:   return new StoreCNode(ctl, mem, adr, adr_type, val, mo);
2500   case T_LONG:    return new StoreLNode(ctl, mem, adr, adr_type, val, mo);
2501   case T_FLOAT:   return new StoreFNode(ctl, mem, adr, adr_type, val, mo);
2502   case T_DOUBLE:  return new StoreDNode(ctl, mem, adr, adr_type, val, mo);
2503   case T_METADATA:
2504   case T_ADDRESS:
2505   case T_VALUETYPE:
2506   case T_OBJECT:
2507 #ifdef _LP64
2508     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2509       val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop()));
2510       return new StoreNNode(ctl, mem, adr, adr_type, val, mo);
2511     } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
2512                (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
2513                 adr->bottom_type()->isa_rawptr())) {
2514       val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
2515       return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
2516     }
2517 #endif
2518     {
2519       return new StorePNode(ctl, mem, adr, adr_type, val, mo);
2520     }
2521   default:
2522     ShouldNotReachHere();
2523     return (StoreNode*)NULL;
2524   }
2525 }
2526 
2527 StoreLNode* StoreLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2528   bool require_atomic = true;
2529   return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2530 }
2531 
2532 StoreDNode* StoreDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2533   bool require_atomic = true;
2534   return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2535 }
2536 
2537 
2538 //--------------------------bottom_type----------------------------------------
2539 const Type *StoreNode::bottom_type() const {
2540   return Type::MEMORY;
2541 }
2542 
2543 //------------------------------hash-------------------------------------------
2544 uint StoreNode::hash() const {
2545   // unroll addition of interesting fields
2546   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
2547 
2548   // Since they are not commoned, do not hash them:
2549   return NO_HASH;
2550 }
2551 
2552 //------------------------------Ideal------------------------------------------
2553 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
2554 // When a store immediately follows a relevant allocation/initialization,
2555 // try to capture it into the initialization, or hoist it above.
2556 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2557   Node* p = MemNode::Ideal_common(phase, can_reshape);
2558   if (p)  return (p == NodeSentinel) ? NULL : p;
2559 
2560   Node* mem     = in(MemNode::Memory);
2561   Node* address = in(MemNode::Address);
2562   // Back-to-back stores to same address?  Fold em up.  Generally
2563   // unsafe if I have intervening uses...  Also disallowed for StoreCM
2564   // since they must follow each StoreP operation.  Redundant StoreCMs
2565   // are eliminated just before matching in final_graph_reshape.
2566   {
2567     Node* st = mem;
2568     // If Store 'st' has more than one use, we cannot fold 'st' away.
2569     // For example, 'st' might be the final state at a conditional
2570     // return.  Or, 'st' might be used by some node which is live at
2571     // the same time 'st' is live, which might be unschedulable.  So,
2572     // require exactly ONE user until such time as we clone 'mem' for
2573     // each of 'mem's uses (thus making the exactly-1-user-rule hold
2574     // true).
2575     while (st->is_Store() && st->outcnt() == 1 && st->Opcode() != Op_StoreCM) {
2576       // Looking at a dead closed cycle of memory?
2577       assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
2578       assert(Opcode() == st->Opcode() ||
2579              st->Opcode() == Op_StoreVector ||
2580              Opcode() == Op_StoreVector ||
2581              phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw ||
2582              (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode
2583              (Opcode() == Op_StoreI && st->Opcode() == Op_StoreL) || // initialization by arraycopy
2584              (Opcode() == Op_StoreL && st->Opcode() == Op_StoreN) ||
2585              (is_mismatched_access() || st->as_Store()->is_mismatched_access()),
2586              "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]);
2587 
2588       if (st->in(MemNode::Address)->eqv_uncast(address) &&
2589           st->as_Store()->memory_size() <= this->memory_size()) {
2590         Node* use = st->raw_out(0);
2591         phase->igvn_rehash_node_delayed(use);
2592         if (can_reshape) {
2593           use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase->is_IterGVN());
2594         } else {
2595           // It's OK to do this in the parser, since DU info is always accurate,
2596           // and the parser always refers to nodes via SafePointNode maps.
2597           use->set_req(MemNode::Memory, st->in(MemNode::Memory));
2598         }
2599         return this;
2600       }
2601       st = st->in(MemNode::Memory);
2602     }
2603   }
2604 
2605 
2606   // Capture an unaliased, unconditional, simple store into an initializer.
2607   // Or, if it is independent of the allocation, hoist it above the allocation.
2608   if (ReduceFieldZeroing && /*can_reshape &&*/
2609       mem->is_Proj() && mem->in(0)->is_Initialize()) {
2610     InitializeNode* init = mem->in(0)->as_Initialize();
2611     intptr_t offset = init->can_capture_store(this, phase, can_reshape);
2612     if (offset > 0) {
2613       Node* moved = init->capture_store(this, offset, phase, can_reshape);
2614       // If the InitializeNode captured me, it made a raw copy of me,
2615       // and I need to disappear.
2616       if (moved != NULL) {
2617         // %%% hack to ensure that Ideal returns a new node:
2618         mem = MergeMemNode::make(mem);
2619         return mem;             // fold me away
2620       }
2621     }
2622   }
2623 
2624   return NULL;                  // No further progress
2625 }
2626 
2627 //------------------------------Value-----------------------------------------
2628 const Type* StoreNode::Value(PhaseGVN* phase) const {
2629   // Either input is TOP ==> the result is TOP
2630   const Type *t1 = phase->type( in(MemNode::Memory) );
2631   if( t1 == Type::TOP ) return Type::TOP;
2632   const Type *t2 = phase->type( in(MemNode::Address) );
2633   if( t2 == Type::TOP ) return Type::TOP;
2634   const Type *t3 = phase->type( in(MemNode::ValueIn) );
2635   if( t3 == Type::TOP ) return Type::TOP;
2636   return Type::MEMORY;
2637 }
2638 
2639 //------------------------------Identity---------------------------------------
2640 // Remove redundant stores:
2641 //   Store(m, p, Load(m, p)) changes to m.
2642 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
2643 Node* StoreNode::Identity(PhaseGVN* phase) {
2644   Node* mem = in(MemNode::Memory);
2645   Node* adr = in(MemNode::Address);
2646   Node* val = in(MemNode::ValueIn);
2647 
2648   Node* result = this;
2649 
2650   // Load then Store?  Then the Store is useless
2651   if (val->is_Load() &&
2652       val->in(MemNode::Address)->eqv_uncast(adr) &&
2653       val->in(MemNode::Memory )->eqv_uncast(mem) &&
2654       val->as_Load()->store_Opcode() == Opcode()) {
2655     result = mem;
2656   }
2657 
2658   // Two stores in a row of the same value?
2659   if (result == this &&
2660       mem->is_Store() &&
2661       mem->in(MemNode::Address)->eqv_uncast(adr) &&
2662       mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
2663       mem->Opcode() == Opcode()) {
2664     result = mem;
2665   }
2666 
2667   // Store of zero anywhere into a freshly-allocated object?
2668   // Then the store is useless.
2669   // (It must already have been captured by the InitializeNode.)
2670   if (result == this && ReduceFieldZeroing) {
2671     // a newly allocated object is already all-zeroes everywhere
2672     if (mem->is_Proj() && mem->in(0)->is_Allocate() &&
2673         (phase->type(val)->is_zero_type() || mem->in(0)->in(AllocateNode::DefaultValue) == val)) {
2674       assert(!phase->type(val)->is_zero_type() || mem->in(0)->in(AllocateNode::DefaultValue) == NULL, "storing null to value array is forbidden");
2675       result = mem;
2676     }
2677 
2678     if (result == this) {
2679       // the store may also apply to zero-bits in an earlier object
2680       Node* prev_mem = find_previous_store(phase);
2681       // Steps (a), (b):  Walk past independent stores to find an exact match.
2682       if (prev_mem != NULL) {
2683         Node* prev_val = can_see_stored_value(prev_mem, phase);
2684         if (prev_val != NULL && phase->eqv(prev_val, val)) {
2685           // prev_val and val might differ by a cast; it would be good
2686           // to keep the more informative of the two.
2687           if (phase->type(val)->is_zero_type()) {
2688             result = mem;
2689           } else if (prev_mem->is_Proj() && prev_mem->in(0)->is_Initialize()) {
2690             InitializeNode* init = prev_mem->in(0)->as_Initialize();
2691             AllocateNode* alloc = init->allocation();
2692             if (alloc != NULL && alloc->in(AllocateNode::DefaultValue) == val) {
2693               result = mem;
2694             }
2695           }
2696         }
2697       }
2698     }
2699   }
2700 
2701   if (result != this && phase->is_IterGVN() != NULL) {
2702     MemBarNode* trailing = trailing_membar();
2703     if (trailing != NULL) {
2704 #ifdef ASSERT
2705       const TypeOopPtr* t_oop = phase->type(in(Address))->isa_oopptr();
2706       assert(t_oop == NULL || t_oop->is_known_instance_field(), "only for non escaping objects");
2707 #endif
2708       PhaseIterGVN* igvn = phase->is_IterGVN();
2709       trailing->remove(igvn);
2710     }
2711   }
2712 
2713   return result;
2714 }
2715 
2716 //------------------------------match_edge-------------------------------------
2717 // Do we Match on this edge index or not?  Match only memory & value
2718 uint StoreNode::match_edge(uint idx) const {
2719   return idx == MemNode::Address || idx == MemNode::ValueIn;
2720 }
2721 
2722 //------------------------------cmp--------------------------------------------
2723 // Do not common stores up together.  They generally have to be split
2724 // back up anyways, so do not bother.
2725 bool StoreNode::cmp( const Node &n ) const {
2726   return (&n == this);          // Always fail except on self
2727 }
2728 
2729 //------------------------------Ideal_masked_input-----------------------------
2730 // Check for a useless mask before a partial-word store
2731 // (StoreB ... (AndI valIn conIa) )
2732 // If (conIa & mask == mask) this simplifies to
2733 // (StoreB ... (valIn) )
2734 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
2735   Node *val = in(MemNode::ValueIn);
2736   if( val->Opcode() == Op_AndI ) {
2737     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2738     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
2739       set_req(MemNode::ValueIn, val->in(1));
2740       return this;
2741     }
2742   }
2743   return NULL;
2744 }
2745 
2746 
2747 //------------------------------Ideal_sign_extended_input----------------------
2748 // Check for useless sign-extension before a partial-word store
2749 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
2750 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
2751 // (StoreB ... (valIn) )
2752 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
2753   Node *val = in(MemNode::ValueIn);
2754   if( val->Opcode() == Op_RShiftI ) {
2755     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2756     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
2757       Node *shl = val->in(1);
2758       if( shl->Opcode() == Op_LShiftI ) {
2759         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
2760         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
2761           set_req(MemNode::ValueIn, shl->in(1));
2762           return this;
2763         }
2764       }
2765     }
2766   }
2767   return NULL;
2768 }
2769 
2770 //------------------------------value_never_loaded-----------------------------------
2771 // Determine whether there are any possible loads of the value stored.
2772 // For simplicity, we actually check if there are any loads from the
2773 // address stored to, not just for loads of the value stored by this node.
2774 //
2775 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
2776   Node *adr = in(Address);
2777   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
2778   if (adr_oop == NULL)
2779     return false;
2780   if (!adr_oop->is_known_instance_field())
2781     return false; // if not a distinct instance, there may be aliases of the address
2782   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
2783     Node *use = adr->fast_out(i);
2784     if (use->is_Load() || use->is_LoadStore()) {
2785       return false;
2786     }
2787   }
2788   return true;
2789 }
2790 
2791 MemBarNode* StoreNode::trailing_membar() const {
2792   if (is_release()) {
2793     MemBarNode* trailing_mb = NULL;
2794     for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
2795       Node* u = fast_out(i);
2796       if (u->is_MemBar()) {
2797         if (u->as_MemBar()->trailing_store()) {
2798           assert(u->Opcode() == Op_MemBarVolatile, "");
2799           assert(trailing_mb == NULL, "only one");
2800           trailing_mb = u->as_MemBar();
2801 #ifdef ASSERT
2802           Node* leading = u->as_MemBar()->leading_membar();
2803           assert(leading->Opcode() == Op_MemBarRelease, "incorrect membar");
2804           assert(leading->as_MemBar()->leading_store(), "incorrect membar pair");
2805           assert(leading->as_MemBar()->trailing_membar() == u, "incorrect membar pair");
2806 #endif
2807         } else {
2808           assert(u->as_MemBar()->standalone(), "");
2809         }
2810       }
2811     }
2812     return trailing_mb;
2813   }
2814   return NULL;
2815 }
2816 
2817 
2818 //=============================================================================
2819 //------------------------------Ideal------------------------------------------
2820 // If the store is from an AND mask that leaves the low bits untouched, then
2821 // we can skip the AND operation.  If the store is from a sign-extension
2822 // (a left shift, then right shift) we can skip both.
2823 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
2824   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
2825   if( progress != NULL ) return progress;
2826 
2827   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
2828   if( progress != NULL ) return progress;
2829 
2830   // Finally check the default case
2831   return StoreNode::Ideal(phase, can_reshape);
2832 }
2833 
2834 //=============================================================================
2835 //------------------------------Ideal------------------------------------------
2836 // If the store is from an AND mask that leaves the low bits untouched, then
2837 // we can skip the AND operation
2838 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
2839   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
2840   if( progress != NULL ) return progress;
2841 
2842   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
2843   if( progress != NULL ) return progress;
2844 
2845   // Finally check the default case
2846   return StoreNode::Ideal(phase, can_reshape);
2847 }
2848 
2849 //=============================================================================
2850 //------------------------------Identity---------------------------------------
2851 Node* StoreCMNode::Identity(PhaseGVN* phase) {
2852   // No need to card mark when storing a null ptr
2853   Node* my_store = in(MemNode::OopStore);
2854   if (my_store->is_Store()) {
2855     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
2856     if( t1 == TypePtr::NULL_PTR ) {
2857       return in(MemNode::Memory);
2858     }
2859   }
2860   return this;
2861 }
2862 
2863 //=============================================================================
2864 //------------------------------Ideal---------------------------------------
2865 Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
2866   Node* progress = StoreNode::Ideal(phase, can_reshape);
2867   if (progress != NULL) return progress;
2868 
2869   Node* my_store = in(MemNode::OopStore);
2870   if (my_store->is_MergeMem()) {
2871     Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
2872     set_req(MemNode::OopStore, mem);
2873     return this;
2874   }
2875 
2876   return NULL;
2877 }
2878 
2879 //------------------------------Value-----------------------------------------
2880 const Type* StoreCMNode::Value(PhaseGVN* phase) const {
2881   // Either input is TOP ==> the result is TOP
2882   const Type *t = phase->type( in(MemNode::Memory) );
2883   if( t == Type::TOP ) return Type::TOP;
2884   t = phase->type( in(MemNode::Address) );
2885   if( t == Type::TOP ) return Type::TOP;
2886   t = phase->type( in(MemNode::ValueIn) );
2887   if( t == Type::TOP ) return Type::TOP;
2888   // If extra input is TOP ==> the result is TOP
2889   t = phase->type( in(MemNode::OopStore) );
2890   if( t == Type::TOP ) return Type::TOP;
2891 
2892   return StoreNode::Value( phase );
2893 }
2894 
2895 
2896 //=============================================================================
2897 //----------------------------------SCMemProjNode------------------------------
2898 const Type* SCMemProjNode::Value(PhaseGVN* phase) const
2899 {
2900   return bottom_type();
2901 }
2902 
2903 //=============================================================================
2904 //----------------------------------LoadStoreNode------------------------------
2905 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
2906   : Node(required),
2907     _type(rt),
2908     _adr_type(at)
2909 {
2910   init_req(MemNode::Control, c  );
2911   init_req(MemNode::Memory , mem);
2912   init_req(MemNode::Address, adr);
2913   init_req(MemNode::ValueIn, val);
2914   init_class_id(Class_LoadStore);
2915 }
2916 
2917 uint LoadStoreNode::ideal_reg() const {
2918   return _type->ideal_reg();
2919 }
2920 
2921 bool LoadStoreNode::result_not_used() const {
2922   for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
2923     Node *x = fast_out(i);
2924     if (x->Opcode() == Op_SCMemProj) continue;
2925     return false;
2926   }
2927   return true;
2928 }
2929 
2930 MemBarNode* LoadStoreNode::trailing_membar() const {
2931   MemBarNode* trailing = NULL;
2932   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
2933     Node* u = fast_out(i);
2934     if (u->is_MemBar()) {
2935       if (u->as_MemBar()->trailing_load_store()) {
2936         assert(u->Opcode() == Op_MemBarAcquire, "");
2937         assert(trailing == NULL, "only one");
2938         trailing = u->as_MemBar();
2939 #ifdef ASSERT
2940         Node* leading = trailing->leading_membar();
2941         assert(support_IRIW_for_not_multiple_copy_atomic_cpu || leading->Opcode() == Op_MemBarRelease, "incorrect membar");
2942         assert(leading->as_MemBar()->leading_load_store(), "incorrect membar pair");
2943         assert(leading->as_MemBar()->trailing_membar() == trailing, "incorrect membar pair");
2944 #endif
2945       } else {
2946         assert(u->as_MemBar()->standalone(), "wrong barrier kind");
2947       }
2948     }
2949   }
2950 
2951   return trailing;
2952 }
2953 
2954 uint LoadStoreNode::size_of() const { return sizeof(*this); }
2955 
2956 //=============================================================================
2957 //----------------------------------LoadStoreConditionalNode--------------------
2958 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, NULL, TypeInt::BOOL, 5) {
2959   init_req(ExpectedIn, ex );
2960 }
2961 
2962 //=============================================================================
2963 //-------------------------------adr_type--------------------------------------
2964 const TypePtr* ClearArrayNode::adr_type() const {
2965   Node *adr = in(3);
2966   if (adr == NULL)  return NULL; // node is dead
2967   return MemNode::calculate_adr_type(adr->bottom_type());
2968 }
2969 
2970 //------------------------------match_edge-------------------------------------
2971 // Do we Match on this edge index or not?  Do not match memory
2972 uint ClearArrayNode::match_edge(uint idx) const {
2973   return idx > 1;
2974 }
2975 
2976 //------------------------------Identity---------------------------------------
2977 // Clearing a zero length array does nothing
2978 Node* ClearArrayNode::Identity(PhaseGVN* phase) {
2979   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
2980 }
2981 
2982 //------------------------------Idealize---------------------------------------
2983 // Clearing a short array is faster with stores
2984 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2985   // Already know this is a large node, do not try to ideal it
2986   if (!IdealizeClearArrayNode || _is_large) return NULL;
2987 
2988   const int unit = BytesPerLong;
2989   const TypeX* t = phase->type(in(2))->isa_intptr_t();
2990   if (!t)  return NULL;
2991   if (!t->is_con())  return NULL;
2992   intptr_t raw_count = t->get_con();
2993   intptr_t size = raw_count;
2994   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
2995   // Clearing nothing uses the Identity call.
2996   // Negative clears are possible on dead ClearArrays
2997   // (see jck test stmt114.stmt11402.val).
2998   if (size <= 0 || size % unit != 0)  return NULL;
2999   intptr_t count = size / unit;
3000   // Length too long; communicate this to matchers and assemblers.
3001   // Assemblers are responsible to produce fast hardware clears for it.
3002   if (size > InitArrayShortSize) {
3003     return new ClearArrayNode(in(0), in(1), in(2), in(3), in(4), true);
3004   }
3005   Node *mem = in(1);
3006   if( phase->type(mem)==Type::TOP ) return NULL;
3007   Node *adr = in(3);
3008   const Type* at = phase->type(adr);
3009   if( at==Type::TOP ) return NULL;
3010   const TypePtr* atp = at->isa_ptr();
3011   // adjust atp to be the correct array element address type
3012   if (atp == NULL)  atp = TypePtr::BOTTOM;
3013   else              atp = atp->add_offset(Type::OffsetBot);
3014   // Get base for derived pointer purposes
3015   if( adr->Opcode() != Op_AddP ) Unimplemented();
3016   Node *base = adr->in(1);
3017 
3018   Node *val = in(4);
3019   Node *off  = phase->MakeConX(BytesPerLong);
3020   mem = new StoreLNode(in(0), mem, adr, atp, val, MemNode::unordered, false);
3021   count--;
3022   while( count-- ) {
3023     mem = phase->transform(mem);
3024     adr = phase->transform(new AddPNode(base,adr,off));
3025     mem = new StoreLNode(in(0), mem, adr, atp, val, MemNode::unordered, false);
3026   }
3027   return mem;
3028 }
3029 
3030 //----------------------------step_through----------------------------------
3031 // Return allocation input memory edge if it is different instance
3032 // or itself if it is the one we are looking for.
3033 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseTransform* phase) {
3034   Node* n = *np;
3035   assert(n->is_ClearArray(), "sanity");
3036   intptr_t offset;
3037   AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
3038   // This method is called only before Allocate nodes are expanded
3039   // during macro nodes expansion. Before that ClearArray nodes are
3040   // only generated in PhaseMacroExpand::generate_arraycopy() (before
3041   // Allocate nodes are expanded) which follows allocations.
3042   assert(alloc != NULL, "should have allocation");
3043   if (alloc->_idx == instance_id) {
3044     // Can not bypass initialization of the instance we are looking for.
3045     return false;
3046   }
3047   // Otherwise skip it.
3048   InitializeNode* init = alloc->initialization();
3049   if (init != NULL)
3050     *np = init->in(TypeFunc::Memory);
3051   else
3052     *np = alloc->in(TypeFunc::Memory);
3053   return true;
3054 }
3055 
3056 //----------------------------clear_memory-------------------------------------
3057 // Generate code to initialize object storage to zero.
3058 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3059                                    Node* val,
3060                                    Node* raw_val,
3061                                    intptr_t start_offset,
3062                                    Node* end_offset,
3063                                    PhaseGVN* phase) {
3064   intptr_t offset = start_offset;
3065 
3066   int unit = BytesPerLong;
3067   if ((offset % unit) != 0) {
3068     Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset));
3069     adr = phase->transform(adr);
3070     const TypePtr* atp = TypeRawPtr::BOTTOM;
3071     if (val != NULL) {
3072       assert(phase->type(val)->isa_narrowoop(), "should be narrow oop");
3073       mem = new StoreNNode(ctl, mem, adr, atp, val, MemNode::unordered);
3074     } else {
3075       assert(raw_val == NULL, "val may not be null");
3076       mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
3077     }
3078     mem = phase->transform(mem);
3079     offset += BytesPerInt;
3080   }
3081   assert((offset % unit) == 0, "");
3082 
3083   // Initialize the remaining stuff, if any, with a ClearArray.
3084   return clear_memory(ctl, mem, dest, raw_val, phase->MakeConX(offset), end_offset, phase);
3085 }
3086 
3087 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3088                                    Node* raw_val,
3089                                    Node* start_offset,
3090                                    Node* end_offset,
3091                                    PhaseGVN* phase) {
3092   if (start_offset == end_offset) {
3093     // nothing to do
3094     return mem;
3095   }
3096 
3097   int unit = BytesPerLong;
3098   Node* zbase = start_offset;
3099   Node* zend  = end_offset;
3100 
3101   // Scale to the unit required by the CPU:
3102   if (!Matcher::init_array_count_is_in_bytes) {
3103     Node* shift = phase->intcon(exact_log2(unit));
3104     zbase = phase->transform(new URShiftXNode(zbase, shift) );
3105     zend  = phase->transform(new URShiftXNode(zend,  shift) );
3106   }
3107 
3108   // Bulk clear double-words
3109   Node* zsize = phase->transform(new SubXNode(zend, zbase) );
3110   Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) );
3111   if (raw_val == NULL) {
3112     raw_val = phase->MakeConX(0);
3113   }
3114   mem = new ClearArrayNode(ctl, mem, zsize, adr, raw_val, false);
3115   return phase->transform(mem);
3116 }
3117 
3118 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3119                                    Node* val,
3120                                    Node* raw_val,
3121                                    intptr_t start_offset,
3122                                    intptr_t end_offset,
3123                                    PhaseGVN* phase) {
3124   if (start_offset == end_offset) {
3125     // nothing to do
3126     return mem;
3127   }
3128 
3129   assert((end_offset % BytesPerInt) == 0, "odd end offset");
3130   intptr_t done_offset = end_offset;
3131   if ((done_offset % BytesPerLong) != 0) {
3132     done_offset -= BytesPerInt;
3133   }
3134   if (done_offset > start_offset) {
3135     mem = clear_memory(ctl, mem, dest, val, raw_val,
3136                        start_offset, phase->MakeConX(done_offset), phase);
3137   }
3138   if (done_offset < end_offset) { // emit the final 32-bit store
3139     Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset));
3140     adr = phase->transform(adr);
3141     const TypePtr* atp = TypeRawPtr::BOTTOM;
3142     if (val != NULL) {
3143       assert(phase->type(val)->isa_narrowoop(), "should be narrow oop");
3144       mem = new StoreNNode(ctl, mem, adr, atp, val, MemNode::unordered);
3145     } else {
3146       assert(raw_val == NULL, "val may not be null");
3147       mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
3148     }
3149     mem = phase->transform(mem);
3150     done_offset += BytesPerInt;
3151   }
3152   assert(done_offset == end_offset, "");
3153   return mem;
3154 }
3155 
3156 //=============================================================================
3157 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
3158   : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
3159     _adr_type(C->get_adr_type(alias_idx)), _kind(Standalone)
3160 #ifdef ASSERT
3161   , _pair_idx(0)
3162 #endif
3163 {
3164   init_class_id(Class_MemBar);
3165   Node* top = C->top();
3166   init_req(TypeFunc::I_O,top);
3167   init_req(TypeFunc::FramePtr,top);
3168   init_req(TypeFunc::ReturnAdr,top);
3169   if (precedent != NULL)
3170     init_req(TypeFunc::Parms, precedent);
3171 }
3172 
3173 //------------------------------cmp--------------------------------------------
3174 uint MemBarNode::hash() const { return NO_HASH; }
3175 bool MemBarNode::cmp( const Node &n ) const {
3176   return (&n == this);          // Always fail except on self
3177 }
3178 
3179 //------------------------------make-------------------------------------------
3180 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
3181   switch (opcode) {
3182   case Op_MemBarAcquire:     return new MemBarAcquireNode(C, atp, pn);
3183   case Op_LoadFence:         return new LoadFenceNode(C, atp, pn);
3184   case Op_MemBarRelease:     return new MemBarReleaseNode(C, atp, pn);
3185   case Op_StoreFence:        return new StoreFenceNode(C, atp, pn);
3186   case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn);
3187   case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn);
3188   case Op_MemBarVolatile:    return new MemBarVolatileNode(C, atp, pn);
3189   case Op_MemBarCPUOrder:    return new MemBarCPUOrderNode(C, atp, pn);
3190   case Op_OnSpinWait:        return new OnSpinWaitNode(C, atp, pn);
3191   case Op_Initialize:        return new InitializeNode(C, atp, pn);
3192   case Op_MemBarStoreStore:  return new MemBarStoreStoreNode(C, atp, pn);
3193   default: ShouldNotReachHere(); return NULL;
3194   }
3195 }
3196 
3197 void MemBarNode::remove(PhaseIterGVN *igvn) {
3198   if (outcnt() != 2) {
3199     return;
3200   }
3201   if (trailing_store() || trailing_load_store()) {
3202     MemBarNode* leading = leading_membar();
3203     if (leading != NULL) {
3204       assert(leading->trailing_membar() == this, "inconsistent leading/trailing membars");
3205       leading->remove(igvn);
3206     }
3207   }
3208   igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
3209   igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
3210 }
3211 
3212 //------------------------------Ideal------------------------------------------
3213 // Return a node which is more "ideal" than the current node.  Strip out
3214 // control copies
3215 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3216   if (remove_dead_region(phase, can_reshape)) return this;
3217   // Don't bother trying to transform a dead node
3218   if (in(0) && in(0)->is_top()) {
3219     return NULL;
3220   }
3221 
3222 #if INCLUDE_ZGC
3223   if (UseZGC) {
3224     if (req() == (Precedent+1) && in(MemBarNode::Precedent)->in(0) != NULL && in(MemBarNode::Precedent)->in(0)->is_LoadBarrier()) {
3225       Node* load_node = in(MemBarNode::Precedent)->in(0)->in(LoadBarrierNode::Oop);
3226       set_req(MemBarNode::Precedent, load_node);
3227       return this;
3228     }
3229   }
3230 #endif
3231 
3232   bool progress = false;
3233   // Eliminate volatile MemBars for scalar replaced objects.
3234   if (can_reshape && req() == (Precedent+1)) {
3235     bool eliminate = false;
3236     int opc = Opcode();
3237     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
3238       // Volatile field loads and stores.
3239       Node* my_mem = in(MemBarNode::Precedent);
3240       // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
3241       if ((my_mem != NULL) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
3242         // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
3243         // replace this Precedent (decodeN) with the Load instead.
3244         if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1))  {
3245           Node* load_node = my_mem->in(1);
3246           set_req(MemBarNode::Precedent, load_node);
3247           phase->is_IterGVN()->_worklist.push(my_mem);
3248           my_mem = load_node;
3249         } else {
3250           assert(my_mem->unique_out() == this, "sanity");
3251           del_req(Precedent);
3252           phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
3253           my_mem = NULL;
3254         }
3255         progress = true;
3256       }
3257       if (my_mem != NULL && my_mem->is_Mem()) {
3258         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
3259         // Check for scalar replaced object reference.
3260         if( t_oop != NULL && t_oop->is_known_instance_field() &&
3261             t_oop->offset() != Type::OffsetBot &&
3262             t_oop->offset() != Type::OffsetTop) {
3263           eliminate = true;
3264         }
3265       }
3266     } else if (opc == Op_MemBarRelease) {
3267       // Final field stores.
3268       Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent), phase);
3269       if ((alloc != NULL) && alloc->is_Allocate() &&
3270           alloc->as_Allocate()->does_not_escape_thread()) {
3271         // The allocated object does not escape.
3272         eliminate = true;
3273       }
3274     }
3275     if (eliminate) {
3276       // Replace MemBar projections by its inputs.
3277       PhaseIterGVN* igvn = phase->is_IterGVN();
3278       remove(igvn);
3279       // Must return either the original node (now dead) or a new node
3280       // (Do not return a top here, since that would break the uniqueness of top.)
3281       return new ConINode(TypeInt::ZERO);
3282     }
3283   }
3284   return progress ? this : NULL;
3285 }
3286 
3287 //------------------------------Value------------------------------------------
3288 const Type* MemBarNode::Value(PhaseGVN* phase) const {
3289   if( !in(0) ) return Type::TOP;
3290   if( phase->type(in(0)) == Type::TOP )
3291     return Type::TOP;
3292   return TypeTuple::MEMBAR;
3293 }
3294 
3295 //------------------------------match------------------------------------------
3296 // Construct projections for memory.
3297 Node *MemBarNode::match(const ProjNode *proj, const Matcher *m, const RegMask* mask) {
3298   switch (proj->_con) {
3299   case TypeFunc::Control:
3300   case TypeFunc::Memory:
3301     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
3302   }
3303   ShouldNotReachHere();
3304   return NULL;
3305 }
3306 
3307 void MemBarNode::set_store_pair(MemBarNode* leading, MemBarNode* trailing) {
3308   trailing->_kind = TrailingStore;
3309   leading->_kind = LeadingStore;
3310 #ifdef ASSERT
3311   trailing->_pair_idx = leading->_idx;
3312   leading->_pair_idx = leading->_idx;
3313 #endif
3314 }
3315 
3316 void MemBarNode::set_load_store_pair(MemBarNode* leading, MemBarNode* trailing) {
3317   trailing->_kind = TrailingLoadStore;
3318   leading->_kind = LeadingLoadStore;
3319 #ifdef ASSERT
3320   trailing->_pair_idx = leading->_idx;
3321   leading->_pair_idx = leading->_idx;
3322 #endif
3323 }
3324 
3325 MemBarNode* MemBarNode::trailing_membar() const {
3326   ResourceMark rm;
3327   Node* trailing = (Node*)this;
3328   VectorSet seen(Thread::current()->resource_area());
3329   Node_Stack multis(0);
3330   do {
3331     Node* c = trailing;
3332     uint i = 0;
3333     do {
3334       trailing = NULL;
3335       for (; i < c->outcnt(); i++) {
3336         Node* next = c->raw_out(i);
3337         if (next != c && next->is_CFG()) {
3338           if (c->is_MultiBranch()) {
3339             if (multis.node() == c) {
3340               multis.set_index(i+1);
3341             } else {
3342               multis.push(c, i+1);
3343             }
3344           }
3345           trailing = next;
3346           break;
3347         }
3348       }
3349       if (trailing != NULL && !seen.test_set(trailing->_idx)) {
3350         break;
3351       }
3352       while (multis.size() > 0) {
3353         c = multis.node();
3354         i = multis.index();
3355         if (i < c->req()) {
3356           break;
3357         }
3358         multis.pop();
3359       }
3360     } while (multis.size() > 0);
3361   } while (!trailing->is_MemBar() || !trailing->as_MemBar()->trailing());
3362 
3363   MemBarNode* mb = trailing->as_MemBar();
3364   assert((mb->_kind == TrailingStore && _kind == LeadingStore) ||
3365          (mb->_kind == TrailingLoadStore && _kind == LeadingLoadStore), "bad trailing membar");
3366   assert(mb->_pair_idx == _pair_idx, "bad trailing membar");
3367   return mb;
3368 }
3369 
3370 MemBarNode* MemBarNode::leading_membar() const {
3371   ResourceMark rm;
3372   VectorSet seen(Thread::current()->resource_area());
3373   Node_Stack regions(0);
3374   Node* leading = in(0);
3375   while (leading != NULL && (!leading->is_MemBar() || !leading->as_MemBar()->leading())) {
3376     while (leading == NULL || leading->is_top() || seen.test_set(leading->_idx)) {
3377       leading = NULL;
3378       while (regions.size() > 0 && leading == NULL) {
3379         Node* r = regions.node();
3380         uint i = regions.index();
3381         if (i < r->req()) {
3382           leading = r->in(i);
3383           regions.set_index(i+1);
3384         } else {
3385           regions.pop();
3386         }
3387       }
3388       if (leading == NULL) {
3389         assert(regions.size() == 0, "all paths should have been tried");
3390         return NULL;
3391       }
3392     }
3393     if (leading->is_Region()) {
3394       regions.push(leading, 2);
3395       leading = leading->in(1);
3396     } else {
3397       leading = leading->in(0);
3398     }
3399   }
3400 #ifdef ASSERT
3401   Unique_Node_List wq;
3402   wq.push((Node*)this);
3403   uint found = 0;
3404   for (uint i = 0; i < wq.size(); i++) {
3405     Node* n = wq.at(i);
3406     if (n->is_Region()) {
3407       for (uint j = 1; j < n->req(); j++) {
3408         Node* in = n->in(j);
3409         if (in != NULL && !in->is_top()) {
3410           wq.push(in);
3411         }
3412       }
3413     } else {
3414       if (n->is_MemBar() && n->as_MemBar()->leading()) {
3415         assert(n == leading, "consistency check failed");
3416         found++;
3417       } else {
3418         Node* in = n->in(0);
3419         if (in != NULL && !in->is_top()) {
3420           wq.push(in);
3421         }
3422       }
3423     }
3424   }
3425   assert(found == 1 || (found == 0 && leading == NULL), "consistency check failed");
3426 #endif
3427   if (leading == NULL) {
3428     return NULL;
3429   }
3430   MemBarNode* mb = leading->as_MemBar();
3431   assert((mb->_kind == LeadingStore && _kind == TrailingStore) ||
3432          (mb->_kind == LeadingLoadStore && _kind == TrailingLoadStore), "bad leading membar");
3433   assert(mb->_pair_idx == _pair_idx, "bad leading membar");
3434   return mb;
3435 }
3436 
3437 //===========================InitializeNode====================================
3438 // SUMMARY:
3439 // This node acts as a memory barrier on raw memory, after some raw stores.
3440 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
3441 // The Initialize can 'capture' suitably constrained stores as raw inits.
3442 // It can coalesce related raw stores into larger units (called 'tiles').
3443 // It can avoid zeroing new storage for memory units which have raw inits.
3444 // At macro-expansion, it is marked 'complete', and does not optimize further.
3445 //
3446 // EXAMPLE:
3447 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
3448 //   ctl = incoming control; mem* = incoming memory
3449 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
3450 // First allocate uninitialized memory and fill in the header:
3451 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
3452 //   ctl := alloc.Control; mem* := alloc.Memory*
3453 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
3454 // Then initialize to zero the non-header parts of the raw memory block:
3455 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
3456 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
3457 // After the initialize node executes, the object is ready for service:
3458 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
3459 // Suppose its body is immediately initialized as {1,2}:
3460 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3461 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3462 //   mem.SLICE(#short[*]) := store2
3463 //
3464 // DETAILS:
3465 // An InitializeNode collects and isolates object initialization after
3466 // an AllocateNode and before the next possible safepoint.  As a
3467 // memory barrier (MemBarNode), it keeps critical stores from drifting
3468 // down past any safepoint or any publication of the allocation.
3469 // Before this barrier, a newly-allocated object may have uninitialized bits.
3470 // After this barrier, it may be treated as a real oop, and GC is allowed.
3471 //
3472 // The semantics of the InitializeNode include an implicit zeroing of
3473 // the new object from object header to the end of the object.
3474 // (The object header and end are determined by the AllocateNode.)
3475 //
3476 // Certain stores may be added as direct inputs to the InitializeNode.
3477 // These stores must update raw memory, and they must be to addresses
3478 // derived from the raw address produced by AllocateNode, and with
3479 // a constant offset.  They must be ordered by increasing offset.
3480 // The first one is at in(RawStores), the last at in(req()-1).
3481 // Unlike most memory operations, they are not linked in a chain,
3482 // but are displayed in parallel as users of the rawmem output of
3483 // the allocation.
3484 //
3485 // (See comments in InitializeNode::capture_store, which continue
3486 // the example given above.)
3487 //
3488 // When the associated Allocate is macro-expanded, the InitializeNode
3489 // may be rewritten to optimize collected stores.  A ClearArrayNode
3490 // may also be created at that point to represent any required zeroing.
3491 // The InitializeNode is then marked 'complete', prohibiting further
3492 // capturing of nearby memory operations.
3493 //
3494 // During macro-expansion, all captured initializations which store
3495 // constant values of 32 bits or smaller are coalesced (if advantageous)
3496 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
3497 // initialized in fewer memory operations.  Memory words which are
3498 // covered by neither tiles nor non-constant stores are pre-zeroed
3499 // by explicit stores of zero.  (The code shape happens to do all
3500 // zeroing first, then all other stores, with both sequences occurring
3501 // in order of ascending offsets.)
3502 //
3503 // Alternatively, code may be inserted between an AllocateNode and its
3504 // InitializeNode, to perform arbitrary initialization of the new object.
3505 // E.g., the object copying intrinsics insert complex data transfers here.
3506 // The initialization must then be marked as 'complete' disable the
3507 // built-in zeroing semantics and the collection of initializing stores.
3508 //
3509 // While an InitializeNode is incomplete, reads from the memory state
3510 // produced by it are optimizable if they match the control edge and
3511 // new oop address associated with the allocation/initialization.
3512 // They return a stored value (if the offset matches) or else zero.
3513 // A write to the memory state, if it matches control and address,
3514 // and if it is to a constant offset, may be 'captured' by the
3515 // InitializeNode.  It is cloned as a raw memory operation and rewired
3516 // inside the initialization, to the raw oop produced by the allocation.
3517 // Operations on addresses which are provably distinct (e.g., to
3518 // other AllocateNodes) are allowed to bypass the initialization.
3519 //
3520 // The effect of all this is to consolidate object initialization
3521 // (both arrays and non-arrays, both piecewise and bulk) into a
3522 // single location, where it can be optimized as a unit.
3523 //
3524 // Only stores with an offset less than TrackedInitializationLimit words
3525 // will be considered for capture by an InitializeNode.  This puts a
3526 // reasonable limit on the complexity of optimized initializations.
3527 
3528 //---------------------------InitializeNode------------------------------------
3529 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
3530   : MemBarNode(C, adr_type, rawoop),
3531     _is_complete(Incomplete), _does_not_escape(false)
3532 {
3533   init_class_id(Class_Initialize);
3534 
3535   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
3536   assert(in(RawAddress) == rawoop, "proper init");
3537   // Note:  allocation() can be NULL, for secondary initialization barriers
3538 }
3539 
3540 // Since this node is not matched, it will be processed by the
3541 // register allocator.  Declare that there are no constraints
3542 // on the allocation of the RawAddress edge.
3543 const RegMask &InitializeNode::in_RegMask(uint idx) const {
3544   // This edge should be set to top, by the set_complete.  But be conservative.
3545   if (idx == InitializeNode::RawAddress)
3546     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
3547   return RegMask::Empty;
3548 }
3549 
3550 Node* InitializeNode::memory(uint alias_idx) {
3551   Node* mem = in(Memory);
3552   if (mem->is_MergeMem()) {
3553     return mem->as_MergeMem()->memory_at(alias_idx);
3554   } else {
3555     // incoming raw memory is not split
3556     return mem;
3557   }
3558 }
3559 
3560 bool InitializeNode::is_non_zero() {
3561   if (is_complete())  return false;
3562   remove_extra_zeroes();
3563   return (req() > RawStores);
3564 }
3565 
3566 void InitializeNode::set_complete(PhaseGVN* phase) {
3567   assert(!is_complete(), "caller responsibility");
3568   _is_complete = Complete;
3569 
3570   // After this node is complete, it contains a bunch of
3571   // raw-memory initializations.  There is no need for
3572   // it to have anything to do with non-raw memory effects.
3573   // Therefore, tell all non-raw users to re-optimize themselves,
3574   // after skipping the memory effects of this initialization.
3575   PhaseIterGVN* igvn = phase->is_IterGVN();
3576   if (igvn)  igvn->add_users_to_worklist(this);
3577 }
3578 
3579 // convenience function
3580 // return false if the init contains any stores already
3581 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
3582   InitializeNode* init = initialization();
3583   if (init == NULL || init->is_complete()) {
3584     return false;
3585   }
3586   init->remove_extra_zeroes();
3587   // for now, if this allocation has already collected any inits, bail:
3588   if (init->is_non_zero())  return false;
3589   init->set_complete(phase);
3590   return true;
3591 }
3592 
3593 void InitializeNode::remove_extra_zeroes() {
3594   if (req() == RawStores)  return;
3595   Node* zmem = zero_memory();
3596   uint fill = RawStores;
3597   for (uint i = fill; i < req(); i++) {
3598     Node* n = in(i);
3599     if (n->is_top() || n == zmem)  continue;  // skip
3600     if (fill < i)  set_req(fill, n);          // compact
3601     ++fill;
3602   }
3603   // delete any empty spaces created:
3604   while (fill < req()) {
3605     del_req(fill);
3606   }
3607 }
3608 
3609 // Helper for remembering which stores go with which offsets.
3610 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
3611   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
3612   intptr_t offset = -1;
3613   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
3614                                                phase, offset);
3615   if (base == NULL)     return -1;  // something is dead,
3616   if (offset < 0)       return -1;  //        dead, dead
3617   return offset;
3618 }
3619 
3620 // Helper for proving that an initialization expression is
3621 // "simple enough" to be folded into an object initialization.
3622 // Attempts to prove that a store's initial value 'n' can be captured
3623 // within the initialization without creating a vicious cycle, such as:
3624 //     { Foo p = new Foo(); p.next = p; }
3625 // True for constants and parameters and small combinations thereof.
3626 bool InitializeNode::detect_init_independence(Node* n, int& count) {
3627   if (n == NULL)      return true;   // (can this really happen?)
3628   if (n->is_Proj())   n = n->in(0);
3629   if (n == this)      return false;  // found a cycle
3630   if (n->is_Con())    return true;
3631   if (n->is_Start())  return true;   // params, etc., are OK
3632   if (n->is_Root())   return true;   // even better
3633 
3634   Node* ctl = n->in(0);
3635   if (ctl != NULL && !ctl->is_top()) {
3636     if (ctl->is_Proj())  ctl = ctl->in(0);
3637     if (ctl == this)  return false;
3638 
3639     // If we already know that the enclosing memory op is pinned right after
3640     // the init, then any control flow that the store has picked up
3641     // must have preceded the init, or else be equal to the init.
3642     // Even after loop optimizations (which might change control edges)
3643     // a store is never pinned *before* the availability of its inputs.
3644     if (!MemNode::all_controls_dominate(n, this))
3645       return false;                  // failed to prove a good control
3646   }
3647 
3648   // Check data edges for possible dependencies on 'this'.
3649   if ((count += 1) > 20)  return false;  // complexity limit
3650   for (uint i = 1; i < n->req(); i++) {
3651     Node* m = n->in(i);
3652     if (m == NULL || m == n || m->is_top())  continue;
3653     uint first_i = n->find_edge(m);
3654     if (i != first_i)  continue;  // process duplicate edge just once
3655     if (!detect_init_independence(m, count)) {
3656       return false;
3657     }
3658   }
3659 
3660   return true;
3661 }
3662 
3663 // Here are all the checks a Store must pass before it can be moved into
3664 // an initialization.  Returns zero if a check fails.
3665 // On success, returns the (constant) offset to which the store applies,
3666 // within the initialized memory.
3667 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase, bool can_reshape) {
3668   const int FAIL = 0;
3669   if (st->is_unaligned_access()) {
3670     return FAIL;
3671   }
3672   if (st->req() != MemNode::ValueIn + 1)
3673     return FAIL;                // an inscrutable StoreNode (card mark?)
3674   Node* ctl = st->in(MemNode::Control);
3675   if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
3676     return FAIL;                // must be unconditional after the initialization
3677   Node* mem = st->in(MemNode::Memory);
3678   if (!(mem->is_Proj() && mem->in(0) == this))
3679     return FAIL;                // must not be preceded by other stores
3680   Node* adr = st->in(MemNode::Address);
3681   intptr_t offset;
3682   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
3683   if (alloc == NULL)
3684     return FAIL;                // inscrutable address
3685   if (alloc != allocation())
3686     return FAIL;                // wrong allocation!  (store needs to float up)
3687   Node* val = st->in(MemNode::ValueIn);
3688   int complexity_count = 0;
3689   if (!detect_init_independence(val, complexity_count))
3690     return FAIL;                // stored value must be 'simple enough'
3691 
3692   // The Store can be captured only if nothing after the allocation
3693   // and before the Store is using the memory location that the store
3694   // overwrites.
3695   bool failed = false;
3696   // If is_complete_with_arraycopy() is true the shape of the graph is
3697   // well defined and is safe so no need for extra checks.
3698   if (!is_complete_with_arraycopy()) {
3699     // We are going to look at each use of the memory state following
3700     // the allocation to make sure nothing reads the memory that the
3701     // Store writes.
3702     const TypePtr* t_adr = phase->type(adr)->isa_ptr();
3703     int alias_idx = phase->C->get_alias_index(t_adr);
3704     ResourceMark rm;
3705     Unique_Node_List mems;
3706     mems.push(mem);
3707     Node* unique_merge = NULL;
3708     for (uint next = 0; next < mems.size(); ++next) {
3709       Node *m  = mems.at(next);
3710       for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
3711         Node *n = m->fast_out(j);
3712         if (n->outcnt() == 0) {
3713           continue;
3714         }
3715         if (n == st) {
3716           continue;
3717         } else if (n->in(0) != NULL && n->in(0) != ctl) {
3718           // If the control of this use is different from the control
3719           // of the Store which is right after the InitializeNode then
3720           // this node cannot be between the InitializeNode and the
3721           // Store.
3722           continue;
3723         } else if (n->is_MergeMem()) {
3724           if (n->as_MergeMem()->memory_at(alias_idx) == m) {
3725             // We can hit a MergeMemNode (that will likely go away
3726             // later) that is a direct use of the memory state
3727             // following the InitializeNode on the same slice as the
3728             // store node that we'd like to capture. We need to check
3729             // the uses of the MergeMemNode.
3730             mems.push(n);
3731           }
3732         } else if (n->is_Mem()) {
3733           Node* other_adr = n->in(MemNode::Address);
3734           if (other_adr == adr) {
3735             failed = true;
3736             break;
3737           } else {
3738             const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
3739             if (other_t_adr != NULL) {
3740               int other_alias_idx = phase->C->get_alias_index(other_t_adr);
3741               if (other_alias_idx == alias_idx) {
3742                 // A load from the same memory slice as the store right
3743                 // after the InitializeNode. We check the control of the
3744                 // object/array that is loaded from. If it's the same as
3745                 // the store control then we cannot capture the store.
3746                 assert(!n->is_Store(), "2 stores to same slice on same control?");
3747                 Node* base = other_adr;
3748                 assert(base->is_AddP(), "should be addp but is %s", base->Name());
3749                 base = base->in(AddPNode::Base);
3750                 if (base != NULL) {
3751                   base = base->uncast();
3752                   if (base->is_Proj() && base->in(0) == alloc) {
3753                     failed = true;
3754                     break;
3755                   }
3756                 }
3757               }
3758             }
3759           }
3760         } else {
3761           failed = true;
3762           break;
3763         }
3764       }
3765     }
3766   }
3767   if (failed) {
3768     if (!can_reshape) {
3769       // We decided we couldn't capture the store during parsing. We
3770       // should try again during the next IGVN once the graph is
3771       // cleaner.
3772       phase->C->record_for_igvn(st);
3773     }
3774     return FAIL;
3775   }
3776 
3777   return offset;                // success
3778 }
3779 
3780 // Find the captured store in(i) which corresponds to the range
3781 // [start..start+size) in the initialized object.
3782 // If there is one, return its index i.  If there isn't, return the
3783 // negative of the index where it should be inserted.
3784 // Return 0 if the queried range overlaps an initialization boundary
3785 // or if dead code is encountered.
3786 // If size_in_bytes is zero, do not bother with overlap checks.
3787 int InitializeNode::captured_store_insertion_point(intptr_t start,
3788                                                    int size_in_bytes,
3789                                                    PhaseTransform* phase) {
3790   const int FAIL = 0, MAX_STORE = BytesPerLong;
3791 
3792   if (is_complete())
3793     return FAIL;                // arraycopy got here first; punt
3794 
3795   assert(allocation() != NULL, "must be present");
3796 
3797   // no negatives, no header fields:
3798   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
3799 
3800   // after a certain size, we bail out on tracking all the stores:
3801   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3802   if (start >= ti_limit)  return FAIL;
3803 
3804   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
3805     if (i >= limit)  return -(int)i; // not found; here is where to put it
3806 
3807     Node*    st     = in(i);
3808     intptr_t st_off = get_store_offset(st, phase);
3809     if (st_off < 0) {
3810       if (st != zero_memory()) {
3811         return FAIL;            // bail out if there is dead garbage
3812       }
3813     } else if (st_off > start) {
3814       // ...we are done, since stores are ordered
3815       if (st_off < start + size_in_bytes) {
3816         return FAIL;            // the next store overlaps
3817       }
3818       return -(int)i;           // not found; here is where to put it
3819     } else if (st_off < start) {
3820       if (size_in_bytes != 0 &&
3821           start < st_off + MAX_STORE &&
3822           start < st_off + st->as_Store()->memory_size()) {
3823         return FAIL;            // the previous store overlaps
3824       }
3825     } else {
3826       if (size_in_bytes != 0 &&
3827           st->as_Store()->memory_size() != size_in_bytes) {
3828         return FAIL;            // mismatched store size
3829       }
3830       return i;
3831     }
3832 
3833     ++i;
3834   }
3835 }
3836 
3837 // Look for a captured store which initializes at the offset 'start'
3838 // with the given size.  If there is no such store, and no other
3839 // initialization interferes, then return zero_memory (the memory
3840 // projection of the AllocateNode).
3841 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
3842                                           PhaseTransform* phase) {
3843   assert(stores_are_sane(phase), "");
3844   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3845   if (i == 0) {
3846     return NULL;                // something is dead
3847   } else if (i < 0) {
3848     return zero_memory();       // just primordial zero bits here
3849   } else {
3850     Node* st = in(i);           // here is the store at this position
3851     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
3852     return st;
3853   }
3854 }
3855 
3856 // Create, as a raw pointer, an address within my new object at 'offset'.
3857 Node* InitializeNode::make_raw_address(intptr_t offset,
3858                                        PhaseTransform* phase) {
3859   Node* addr = in(RawAddress);
3860   if (offset != 0) {
3861     Compile* C = phase->C;
3862     addr = phase->transform( new AddPNode(C->top(), addr,
3863                                                  phase->MakeConX(offset)) );
3864   }
3865   return addr;
3866 }
3867 
3868 // Clone the given store, converting it into a raw store
3869 // initializing a field or element of my new object.
3870 // Caller is responsible for retiring the original store,
3871 // with subsume_node or the like.
3872 //
3873 // From the example above InitializeNode::InitializeNode,
3874 // here are the old stores to be captured:
3875 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3876 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3877 //
3878 // Here is the changed code; note the extra edges on init:
3879 //   alloc = (Allocate ...)
3880 //   rawoop = alloc.RawAddress
3881 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
3882 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
3883 //   init = (Initialize alloc.Control alloc.Memory rawoop
3884 //                      rawstore1 rawstore2)
3885 //
3886 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
3887                                     PhaseTransform* phase, bool can_reshape) {
3888   assert(stores_are_sane(phase), "");
3889 
3890   if (start < 0)  return NULL;
3891   assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
3892 
3893   Compile* C = phase->C;
3894   int size_in_bytes = st->memory_size();
3895   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3896   if (i == 0)  return NULL;     // bail out
3897   Node* prev_mem = NULL;        // raw memory for the captured store
3898   if (i > 0) {
3899     prev_mem = in(i);           // there is a pre-existing store under this one
3900     set_req(i, C->top());       // temporarily disconnect it
3901     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
3902   } else {
3903     i = -i;                     // no pre-existing store
3904     prev_mem = zero_memory();   // a slice of the newly allocated object
3905     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
3906       set_req(--i, C->top());   // reuse this edge; it has been folded away
3907     else
3908       ins_req(i, C->top());     // build a new edge
3909   }
3910   Node* new_st = st->clone();
3911   new_st->set_req(MemNode::Control, in(Control));
3912   new_st->set_req(MemNode::Memory,  prev_mem);
3913   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
3914   new_st = phase->transform(new_st);
3915 
3916   // At this point, new_st might have swallowed a pre-existing store
3917   // at the same offset, or perhaps new_st might have disappeared,
3918   // if it redundantly stored the same value (or zero to fresh memory).
3919 
3920   // In any case, wire it in:
3921   phase->igvn_rehash_node_delayed(this);
3922   set_req(i, new_st);
3923 
3924   // The caller may now kill the old guy.
3925   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
3926   assert(check_st == new_st || check_st == NULL, "must be findable");
3927   assert(!is_complete(), "");
3928   return new_st;
3929 }
3930 
3931 static bool store_constant(jlong* tiles, int num_tiles,
3932                            intptr_t st_off, int st_size,
3933                            jlong con) {
3934   if ((st_off & (st_size-1)) != 0)
3935     return false;               // strange store offset (assume size==2**N)
3936   address addr = (address)tiles + st_off;
3937   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
3938   switch (st_size) {
3939   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
3940   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
3941   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
3942   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
3943   default: return false;        // strange store size (detect size!=2**N here)
3944   }
3945   return true;                  // return success to caller
3946 }
3947 
3948 // Coalesce subword constants into int constants and possibly
3949 // into long constants.  The goal, if the CPU permits,
3950 // is to initialize the object with a small number of 64-bit tiles.
3951 // Also, convert floating-point constants to bit patterns.
3952 // Non-constants are not relevant to this pass.
3953 //
3954 // In terms of the running example on InitializeNode::InitializeNode
3955 // and InitializeNode::capture_store, here is the transformation
3956 // of rawstore1 and rawstore2 into rawstore12:
3957 //   alloc = (Allocate ...)
3958 //   rawoop = alloc.RawAddress
3959 //   tile12 = 0x00010002
3960 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
3961 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
3962 //
3963 void
3964 InitializeNode::coalesce_subword_stores(intptr_t header_size,
3965                                         Node* size_in_bytes,
3966                                         PhaseGVN* phase) {
3967   Compile* C = phase->C;
3968 
3969   assert(stores_are_sane(phase), "");
3970   // Note:  After this pass, they are not completely sane,
3971   // since there may be some overlaps.
3972 
3973   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
3974 
3975   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3976   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
3977   size_limit = MIN2(size_limit, ti_limit);
3978   size_limit = align_up(size_limit, BytesPerLong);
3979   int num_tiles = size_limit / BytesPerLong;
3980 
3981   // allocate space for the tile map:
3982   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
3983   jlong  tiles_buf[small_len];
3984   Node*  nodes_buf[small_len];
3985   jlong  inits_buf[small_len];
3986   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
3987                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3988   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
3989                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
3990   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
3991                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3992   // tiles: exact bitwise model of all primitive constants
3993   // nodes: last constant-storing node subsumed into the tiles model
3994   // inits: which bytes (in each tile) are touched by any initializations
3995 
3996   //// Pass A: Fill in the tile model with any relevant stores.
3997 
3998   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
3999   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
4000   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
4001   Node* zmem = zero_memory(); // initially zero memory state
4002   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
4003     Node* st = in(i);
4004     intptr_t st_off = get_store_offset(st, phase);
4005 
4006     // Figure out the store's offset and constant value:
4007     if (st_off < header_size)             continue; //skip (ignore header)
4008     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
4009     int st_size = st->as_Store()->memory_size();
4010     if (st_off + st_size > size_limit)    break;
4011 
4012     // Record which bytes are touched, whether by constant or not.
4013     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
4014       continue;                 // skip (strange store size)
4015 
4016     const Type* val = phase->type(st->in(MemNode::ValueIn));
4017     if (!val->singleton())                continue; //skip (non-con store)
4018     BasicType type = val->basic_type();
4019 
4020     jlong con = 0;
4021     switch (type) {
4022     case T_INT:    con = val->is_int()->get_con();  break;
4023     case T_LONG:   con = val->is_long()->get_con(); break;
4024     case T_FLOAT:  con = jint_cast(val->getf());    break;
4025     case T_DOUBLE: con = jlong_cast(val->getd());   break;
4026     default:                              continue; //skip (odd store type)
4027     }
4028 
4029     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
4030         st->Opcode() == Op_StoreL) {
4031       continue;                 // This StoreL is already optimal.
4032     }
4033 
4034     // Store down the constant.
4035     store_constant(tiles, num_tiles, st_off, st_size, con);
4036 
4037     intptr_t j = st_off >> LogBytesPerLong;
4038 
4039     if (type == T_INT && st_size == BytesPerInt
4040         && (st_off & BytesPerInt) == BytesPerInt) {
4041       jlong lcon = tiles[j];
4042       if (!Matcher::isSimpleConstant64(lcon) &&
4043           st->Opcode() == Op_StoreI) {
4044         // This StoreI is already optimal by itself.
4045         jint* intcon = (jint*) &tiles[j];
4046         intcon[1] = 0;  // undo the store_constant()
4047 
4048         // If the previous store is also optimal by itself, back up and
4049         // undo the action of the previous loop iteration... if we can.
4050         // But if we can't, just let the previous half take care of itself.
4051         st = nodes[j];
4052         st_off -= BytesPerInt;
4053         con = intcon[0];
4054         if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
4055           assert(st_off >= header_size, "still ignoring header");
4056           assert(get_store_offset(st, phase) == st_off, "must be");
4057           assert(in(i-1) == zmem, "must be");
4058           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
4059           assert(con == tcon->is_int()->get_con(), "must be");
4060           // Undo the effects of the previous loop trip, which swallowed st:
4061           intcon[0] = 0;        // undo store_constant()
4062           set_req(i-1, st);     // undo set_req(i, zmem)
4063           nodes[j] = NULL;      // undo nodes[j] = st
4064           --old_subword;        // undo ++old_subword
4065         }
4066         continue;               // This StoreI is already optimal.
4067       }
4068     }
4069 
4070     // This store is not needed.
4071     set_req(i, zmem);
4072     nodes[j] = st;              // record for the moment
4073     if (st_size < BytesPerLong) // something has changed
4074           ++old_subword;        // includes int/float, but who's counting...
4075     else  ++old_long;
4076   }
4077 
4078   if ((old_subword + old_long) == 0)
4079     return;                     // nothing more to do
4080 
4081   //// Pass B: Convert any non-zero tiles into optimal constant stores.
4082   // Be sure to insert them before overlapping non-constant stores.
4083   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
4084   for (int j = 0; j < num_tiles; j++) {
4085     jlong con  = tiles[j];
4086     jlong init = inits[j];
4087     if (con == 0)  continue;
4088     jint con0,  con1;           // split the constant, address-wise
4089     jint init0, init1;          // split the init map, address-wise
4090     { union { jlong con; jint intcon[2]; } u;
4091       u.con = con;
4092       con0  = u.intcon[0];
4093       con1  = u.intcon[1];
4094       u.con = init;
4095       init0 = u.intcon[0];
4096       init1 = u.intcon[1];
4097     }
4098 
4099     Node* old = nodes[j];
4100     assert(old != NULL, "need the prior store");
4101     intptr_t offset = (j * BytesPerLong);
4102 
4103     bool split = !Matcher::isSimpleConstant64(con);
4104 
4105     if (offset < header_size) {
4106       assert(offset + BytesPerInt >= header_size, "second int counts");
4107       assert(*(jint*)&tiles[j] == 0, "junk in header");
4108       split = true;             // only the second word counts
4109       // Example:  int a[] = { 42 ... }
4110     } else if (con0 == 0 && init0 == -1) {
4111       split = true;             // first word is covered by full inits
4112       // Example:  int a[] = { ... foo(), 42 ... }
4113     } else if (con1 == 0 && init1 == -1) {
4114       split = true;             // second word is covered by full inits
4115       // Example:  int a[] = { ... 42, foo() ... }
4116     }
4117 
4118     // Here's a case where init0 is neither 0 nor -1:
4119     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
4120     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
4121     // In this case the tile is not split; it is (jlong)42.
4122     // The big tile is stored down, and then the foo() value is inserted.
4123     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
4124 
4125     Node* ctl = old->in(MemNode::Control);
4126     Node* adr = make_raw_address(offset, phase);
4127     const TypePtr* atp = TypeRawPtr::BOTTOM;
4128 
4129     // One or two coalesced stores to plop down.
4130     Node*    st[2];
4131     intptr_t off[2];
4132     int  nst = 0;
4133     if (!split) {
4134       ++new_long;
4135       off[nst] = offset;
4136       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4137                                   phase->longcon(con), T_LONG, MemNode::unordered);
4138     } else {
4139       // Omit either if it is a zero.
4140       if (con0 != 0) {
4141         ++new_int;
4142         off[nst]  = offset;
4143         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4144                                     phase->intcon(con0), T_INT, MemNode::unordered);
4145       }
4146       if (con1 != 0) {
4147         ++new_int;
4148         offset += BytesPerInt;
4149         adr = make_raw_address(offset, phase);
4150         off[nst]  = offset;
4151         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4152                                     phase->intcon(con1), T_INT, MemNode::unordered);
4153       }
4154     }
4155 
4156     // Insert second store first, then the first before the second.
4157     // Insert each one just before any overlapping non-constant stores.
4158     while (nst > 0) {
4159       Node* st1 = st[--nst];
4160       C->copy_node_notes_to(st1, old);
4161       st1 = phase->transform(st1);
4162       offset = off[nst];
4163       assert(offset >= header_size, "do not smash header");
4164       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
4165       guarantee(ins_idx != 0, "must re-insert constant store");
4166       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
4167       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
4168         set_req(--ins_idx, st1);
4169       else
4170         ins_req(ins_idx, st1);
4171     }
4172   }
4173 
4174   if (PrintCompilation && WizardMode)
4175     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
4176                   old_subword, old_long, new_int, new_long);
4177   if (C->log() != NULL)
4178     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
4179                    old_subword, old_long, new_int, new_long);
4180 
4181   // Clean up any remaining occurrences of zmem:
4182   remove_extra_zeroes();
4183 }
4184 
4185 // Explore forward from in(start) to find the first fully initialized
4186 // word, and return its offset.  Skip groups of subword stores which
4187 // together initialize full words.  If in(start) is itself part of a
4188 // fully initialized word, return the offset of in(start).  If there
4189 // are no following full-word stores, or if something is fishy, return
4190 // a negative value.
4191 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
4192   int       int_map = 0;
4193   intptr_t  int_map_off = 0;
4194   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
4195 
4196   for (uint i = start, limit = req(); i < limit; i++) {
4197     Node* st = in(i);
4198 
4199     intptr_t st_off = get_store_offset(st, phase);
4200     if (st_off < 0)  break;  // return conservative answer
4201 
4202     int st_size = st->as_Store()->memory_size();
4203     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
4204       return st_off;            // we found a complete word init
4205     }
4206 
4207     // update the map:
4208 
4209     intptr_t this_int_off = align_down(st_off, BytesPerInt);
4210     if (this_int_off != int_map_off) {
4211       // reset the map:
4212       int_map = 0;
4213       int_map_off = this_int_off;
4214     }
4215 
4216     int subword_off = st_off - this_int_off;
4217     int_map |= right_n_bits(st_size) << subword_off;
4218     if ((int_map & FULL_MAP) == FULL_MAP) {
4219       return this_int_off;      // we found a complete word init
4220     }
4221 
4222     // Did this store hit or cross the word boundary?
4223     intptr_t next_int_off = align_down(st_off + st_size, BytesPerInt);
4224     if (next_int_off == this_int_off + BytesPerInt) {
4225       // We passed the current int, without fully initializing it.
4226       int_map_off = next_int_off;
4227       int_map >>= BytesPerInt;
4228     } else if (next_int_off > this_int_off + BytesPerInt) {
4229       // We passed the current and next int.
4230       return this_int_off + BytesPerInt;
4231     }
4232   }
4233 
4234   return -1;
4235 }
4236 
4237 
4238 // Called when the associated AllocateNode is expanded into CFG.
4239 // At this point, we may perform additional optimizations.
4240 // Linearize the stores by ascending offset, to make memory
4241 // activity as coherent as possible.
4242 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
4243                                       intptr_t header_size,
4244                                       Node* size_in_bytes,
4245                                       PhaseGVN* phase) {
4246   assert(!is_complete(), "not already complete");
4247   assert(stores_are_sane(phase), "");
4248   assert(allocation() != NULL, "must be present");
4249 
4250   remove_extra_zeroes();
4251 
4252   if (ReduceFieldZeroing || ReduceBulkZeroing)
4253     // reduce instruction count for common initialization patterns
4254     coalesce_subword_stores(header_size, size_in_bytes, phase);
4255 
4256   Node* zmem = zero_memory();   // initially zero memory state
4257   Node* inits = zmem;           // accumulating a linearized chain of inits
4258   #ifdef ASSERT
4259   intptr_t first_offset = allocation()->minimum_header_size();
4260   intptr_t last_init_off = first_offset;  // previous init offset
4261   intptr_t last_init_end = first_offset;  // previous init offset+size
4262   intptr_t last_tile_end = first_offset;  // previous tile offset+size
4263   #endif
4264   intptr_t zeroes_done = header_size;
4265 
4266   bool do_zeroing = true;       // we might give up if inits are very sparse
4267   int  big_init_gaps = 0;       // how many large gaps have we seen?
4268 
4269   if (UseTLAB && ZeroTLAB)  do_zeroing = false;
4270   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
4271 
4272   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
4273     Node* st = in(i);
4274     intptr_t st_off = get_store_offset(st, phase);
4275     if (st_off < 0)
4276       break;                    // unknown junk in the inits
4277     if (st->in(MemNode::Memory) != zmem)
4278       break;                    // complicated store chains somehow in list
4279 
4280     int st_size = st->as_Store()->memory_size();
4281     intptr_t next_init_off = st_off + st_size;
4282 
4283     if (do_zeroing && zeroes_done < next_init_off) {
4284       // See if this store needs a zero before it or under it.
4285       intptr_t zeroes_needed = st_off;
4286 
4287       if (st_size < BytesPerInt) {
4288         // Look for subword stores which only partially initialize words.
4289         // If we find some, we must lay down some word-level zeroes first,
4290         // underneath the subword stores.
4291         //
4292         // Examples:
4293         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
4294         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
4295         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
4296         //
4297         // Note:  coalesce_subword_stores may have already done this,
4298         // if it was prompted by constant non-zero subword initializers.
4299         // But this case can still arise with non-constant stores.
4300 
4301         intptr_t next_full_store = find_next_fullword_store(i, phase);
4302 
4303         // In the examples above:
4304         //   in(i)          p   q   r   s     x   y     z
4305         //   st_off        12  13  14  15    12  13    14
4306         //   st_size        1   1   1   1     1   1     1
4307         //   next_full_s.  12  16  16  16    16  16    16
4308         //   z's_done      12  16  16  16    12  16    12
4309         //   z's_needed    12  16  16  16    16  16    16
4310         //   zsize          0   0   0   0     4   0     4
4311         if (next_full_store < 0) {
4312           // Conservative tack:  Zero to end of current word.
4313           zeroes_needed = align_up(zeroes_needed, BytesPerInt);
4314         } else {
4315           // Zero to beginning of next fully initialized word.
4316           // Or, don't zero at all, if we are already in that word.
4317           assert(next_full_store >= zeroes_needed, "must go forward");
4318           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
4319           zeroes_needed = next_full_store;
4320         }
4321       }
4322 
4323       if (zeroes_needed > zeroes_done) {
4324         intptr_t zsize = zeroes_needed - zeroes_done;
4325         // Do some incremental zeroing on rawmem, in parallel with inits.
4326         zeroes_done = align_down(zeroes_done, BytesPerInt);
4327         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
4328                                               allocation()->in(AllocateNode::DefaultValue),
4329                                               allocation()->in(AllocateNode::RawDefaultValue),
4330                                               zeroes_done, zeroes_needed,
4331                                               phase);
4332         zeroes_done = zeroes_needed;
4333         if (zsize > InitArrayShortSize && ++big_init_gaps > 2)
4334           do_zeroing = false;   // leave the hole, next time
4335       }
4336     }
4337 
4338     // Collect the store and move on:
4339     st->set_req(MemNode::Memory, inits);
4340     inits = st;                 // put it on the linearized chain
4341     set_req(i, zmem);           // unhook from previous position
4342 
4343     if (zeroes_done == st_off)
4344       zeroes_done = next_init_off;
4345 
4346     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
4347 
4348     #ifdef ASSERT
4349     // Various order invariants.  Weaker than stores_are_sane because
4350     // a large constant tile can be filled in by smaller non-constant stores.
4351     assert(st_off >= last_init_off, "inits do not reverse");
4352     last_init_off = st_off;
4353     const Type* val = NULL;
4354     if (st_size >= BytesPerInt &&
4355         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
4356         (int)val->basic_type() < (int)T_OBJECT) {
4357       assert(st_off >= last_tile_end, "tiles do not overlap");
4358       assert(st_off >= last_init_end, "tiles do not overwrite inits");
4359       last_tile_end = MAX2(last_tile_end, next_init_off);
4360     } else {
4361       intptr_t st_tile_end = align_up(next_init_off, BytesPerLong);
4362       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
4363       assert(st_off      >= last_init_end, "inits do not overlap");
4364       last_init_end = next_init_off;  // it's a non-tile
4365     }
4366     #endif //ASSERT
4367   }
4368 
4369   remove_extra_zeroes();        // clear out all the zmems left over
4370   add_req(inits);
4371 
4372   if (!(UseTLAB && ZeroTLAB)) {
4373     // If anything remains to be zeroed, zero it all now.
4374     zeroes_done = align_down(zeroes_done, BytesPerInt);
4375     // if it is the last unused 4 bytes of an instance, forget about it
4376     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
4377     if (zeroes_done + BytesPerLong >= size_limit) {
4378       AllocateNode* alloc = allocation();
4379       assert(alloc != NULL, "must be present");
4380       if (alloc != NULL && alloc->Opcode() == Op_Allocate) {
4381         Node* klass_node = alloc->in(AllocateNode::KlassNode);
4382         ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
4383         if (zeroes_done == k->layout_helper())
4384           zeroes_done = size_limit;
4385       }
4386     }
4387     if (zeroes_done < size_limit) {
4388       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
4389                                             allocation()->in(AllocateNode::DefaultValue),
4390                                             allocation()->in(AllocateNode::RawDefaultValue),
4391                                             zeroes_done, size_in_bytes, phase);
4392     }
4393   }
4394 
4395   set_complete(phase);
4396   return rawmem;
4397 }
4398 
4399 
4400 #ifdef ASSERT
4401 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
4402   if (is_complete())
4403     return true;                // stores could be anything at this point
4404   assert(allocation() != NULL, "must be present");
4405   intptr_t last_off = allocation()->minimum_header_size();
4406   for (uint i = InitializeNode::RawStores; i < req(); i++) {
4407     Node* st = in(i);
4408     intptr_t st_off = get_store_offset(st, phase);
4409     if (st_off < 0)  continue;  // ignore dead garbage
4410     if (last_off > st_off) {
4411       tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
4412       this->dump(2);
4413       assert(false, "ascending store offsets");
4414       return false;
4415     }
4416     last_off = st_off + st->as_Store()->memory_size();
4417   }
4418   return true;
4419 }
4420 #endif //ASSERT
4421 
4422 
4423 
4424 
4425 //============================MergeMemNode=====================================
4426 //
4427 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
4428 // contributing store or call operations.  Each contributor provides the memory
4429 // state for a particular "alias type" (see Compile::alias_type).  For example,
4430 // if a MergeMem has an input X for alias category #6, then any memory reference
4431 // to alias category #6 may use X as its memory state input, as an exact equivalent
4432 // to using the MergeMem as a whole.
4433 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
4434 //
4435 // (Here, the <N> notation gives the index of the relevant adr_type.)
4436 //
4437 // In one special case (and more cases in the future), alias categories overlap.
4438 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
4439 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
4440 // it is exactly equivalent to that state W:
4441 //   MergeMem(<Bot>: W) <==> W
4442 //
4443 // Usually, the merge has more than one input.  In that case, where inputs
4444 // overlap (i.e., one is Bot), the narrower alias type determines the memory
4445 // state for that type, and the wider alias type (Bot) fills in everywhere else:
4446 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
4447 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
4448 //
4449 // A merge can take a "wide" memory state as one of its narrow inputs.
4450 // This simply means that the merge observes out only the relevant parts of
4451 // the wide input.  That is, wide memory states arriving at narrow merge inputs
4452 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
4453 //
4454 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
4455 // and that memory slices "leak through":
4456 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
4457 //
4458 // But, in such a cascade, repeated memory slices can "block the leak":
4459 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
4460 //
4461 // In the last example, Y is not part of the combined memory state of the
4462 // outermost MergeMem.  The system must, of course, prevent unschedulable
4463 // memory states from arising, so you can be sure that the state Y is somehow
4464 // a precursor to state Y'.
4465 //
4466 //
4467 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
4468 // of each MergeMemNode array are exactly the numerical alias indexes, including
4469 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
4470 // Compile::alias_type (and kin) produce and manage these indexes.
4471 //
4472 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
4473 // (Note that this provides quick access to the top node inside MergeMem methods,
4474 // without the need to reach out via TLS to Compile::current.)
4475 //
4476 // As a consequence of what was just described, a MergeMem that represents a full
4477 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
4478 // containing all alias categories.
4479 //
4480 // MergeMem nodes never (?) have control inputs, so in(0) is NULL.
4481 //
4482 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
4483 // a memory state for the alias type <N>, or else the top node, meaning that
4484 // there is no particular input for that alias type.  Note that the length of
4485 // a MergeMem is variable, and may be extended at any time to accommodate new
4486 // memory states at larger alias indexes.  When merges grow, they are of course
4487 // filled with "top" in the unused in() positions.
4488 //
4489 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
4490 // (Top was chosen because it works smoothly with passes like GCM.)
4491 //
4492 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
4493 // the type of random VM bits like TLS references.)  Since it is always the
4494 // first non-Bot memory slice, some low-level loops use it to initialize an
4495 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
4496 //
4497 //
4498 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
4499 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
4500 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
4501 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
4502 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
4503 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
4504 //
4505 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
4506 // really that different from the other memory inputs.  An abbreviation called
4507 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
4508 //
4509 //
4510 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
4511 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
4512 // that "emerges though" the base memory will be marked as excluding the alias types
4513 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
4514 //
4515 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
4516 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
4517 //
4518 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
4519 // (It is currently unimplemented.)  As you can see, the resulting merge is
4520 // actually a disjoint union of memory states, rather than an overlay.
4521 //
4522 
4523 //------------------------------MergeMemNode-----------------------------------
4524 Node* MergeMemNode::make_empty_memory() {
4525   Node* empty_memory = (Node*) Compile::current()->top();
4526   assert(empty_memory->is_top(), "correct sentinel identity");
4527   return empty_memory;
4528 }
4529 
4530 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
4531   init_class_id(Class_MergeMem);
4532   // all inputs are nullified in Node::Node(int)
4533   // set_input(0, NULL);  // no control input
4534 
4535   // Initialize the edges uniformly to top, for starters.
4536   Node* empty_mem = make_empty_memory();
4537   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
4538     init_req(i,empty_mem);
4539   }
4540   assert(empty_memory() == empty_mem, "");
4541 
4542   if( new_base != NULL && new_base->is_MergeMem() ) {
4543     MergeMemNode* mdef = new_base->as_MergeMem();
4544     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
4545     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
4546       mms.set_memory(mms.memory2());
4547     }
4548     assert(base_memory() == mdef->base_memory(), "");
4549   } else {
4550     set_base_memory(new_base);
4551   }
4552 }
4553 
4554 // Make a new, untransformed MergeMem with the same base as 'mem'.
4555 // If mem is itself a MergeMem, populate the result with the same edges.
4556 MergeMemNode* MergeMemNode::make(Node* mem) {
4557   return new MergeMemNode(mem);
4558 }
4559 
4560 //------------------------------cmp--------------------------------------------
4561 uint MergeMemNode::hash() const { return NO_HASH; }
4562 bool MergeMemNode::cmp( const Node &n ) const {
4563   return (&n == this);          // Always fail except on self
4564 }
4565 
4566 //------------------------------Identity---------------------------------------
4567 Node* MergeMemNode::Identity(PhaseGVN* phase) {
4568   // Identity if this merge point does not record any interesting memory
4569   // disambiguations.
4570   Node* base_mem = base_memory();
4571   Node* empty_mem = empty_memory();
4572   if (base_mem != empty_mem) {  // Memory path is not dead?
4573     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4574       Node* mem = in(i);
4575       if (mem != empty_mem && mem != base_mem) {
4576         return this;            // Many memory splits; no change
4577       }
4578     }
4579   }
4580   return base_mem;              // No memory splits; ID on the one true input
4581 }
4582 
4583 //------------------------------Ideal------------------------------------------
4584 // This method is invoked recursively on chains of MergeMem nodes
4585 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4586   // Remove chain'd MergeMems
4587   //
4588   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
4589   // relative to the "in(Bot)".  Since we are patching both at the same time,
4590   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
4591   // but rewrite each "in(i)" relative to the new "in(Bot)".
4592   Node *progress = NULL;
4593 
4594 
4595   Node* old_base = base_memory();
4596   Node* empty_mem = empty_memory();
4597   if (old_base == empty_mem)
4598     return NULL; // Dead memory path.
4599 
4600   MergeMemNode* old_mbase;
4601   if (old_base != NULL && old_base->is_MergeMem())
4602     old_mbase = old_base->as_MergeMem();
4603   else
4604     old_mbase = NULL;
4605   Node* new_base = old_base;
4606 
4607   // simplify stacked MergeMems in base memory
4608   if (old_mbase)  new_base = old_mbase->base_memory();
4609 
4610   // the base memory might contribute new slices beyond my req()
4611   if (old_mbase)  grow_to_match(old_mbase);
4612 
4613   // Look carefully at the base node if it is a phi.
4614   PhiNode* phi_base;
4615   if (new_base != NULL && new_base->is_Phi())
4616     phi_base = new_base->as_Phi();
4617   else
4618     phi_base = NULL;
4619 
4620   Node*    phi_reg = NULL;
4621   uint     phi_len = (uint)-1;
4622   if (phi_base != NULL && !phi_base->is_copy()) {
4623     // do not examine phi if degraded to a copy
4624     phi_reg = phi_base->region();
4625     phi_len = phi_base->req();
4626     // see if the phi is unfinished
4627     for (uint i = 1; i < phi_len; i++) {
4628       if (phi_base->in(i) == NULL) {
4629         // incomplete phi; do not look at it yet!
4630         phi_reg = NULL;
4631         phi_len = (uint)-1;
4632         break;
4633       }
4634     }
4635   }
4636 
4637   // Note:  We do not call verify_sparse on entry, because inputs
4638   // can normalize to the base_memory via subsume_node or similar
4639   // mechanisms.  This method repairs that damage.
4640 
4641   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
4642 
4643   // Look at each slice.
4644   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4645     Node* old_in = in(i);
4646     // calculate the old memory value
4647     Node* old_mem = old_in;
4648     if (old_mem == empty_mem)  old_mem = old_base;
4649     assert(old_mem == memory_at(i), "");
4650 
4651     // maybe update (reslice) the old memory value
4652 
4653     // simplify stacked MergeMems
4654     Node* new_mem = old_mem;
4655     MergeMemNode* old_mmem;
4656     if (old_mem != NULL && old_mem->is_MergeMem())
4657       old_mmem = old_mem->as_MergeMem();
4658     else
4659       old_mmem = NULL;
4660     if (old_mmem == this) {
4661       // This can happen if loops break up and safepoints disappear.
4662       // A merge of BotPtr (default) with a RawPtr memory derived from a
4663       // safepoint can be rewritten to a merge of the same BotPtr with
4664       // the BotPtr phi coming into the loop.  If that phi disappears
4665       // also, we can end up with a self-loop of the mergemem.
4666       // In general, if loops degenerate and memory effects disappear,
4667       // a mergemem can be left looking at itself.  This simply means
4668       // that the mergemem's default should be used, since there is
4669       // no longer any apparent effect on this slice.
4670       // Note: If a memory slice is a MergeMem cycle, it is unreachable
4671       //       from start.  Update the input to TOP.
4672       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
4673     }
4674     else if (old_mmem != NULL) {
4675       new_mem = old_mmem->memory_at(i);
4676     }
4677     // else preceding memory was not a MergeMem
4678 
4679     // replace equivalent phis (unfortunately, they do not GVN together)
4680     if (new_mem != NULL && new_mem != new_base &&
4681         new_mem->req() == phi_len && new_mem->in(0) == phi_reg) {
4682       if (new_mem->is_Phi()) {
4683         PhiNode* phi_mem = new_mem->as_Phi();
4684         for (uint i = 1; i < phi_len; i++) {
4685           if (phi_base->in(i) != phi_mem->in(i)) {
4686             phi_mem = NULL;
4687             break;
4688           }
4689         }
4690         if (phi_mem != NULL) {
4691           // equivalent phi nodes; revert to the def
4692           new_mem = new_base;
4693         }
4694       }
4695     }
4696 
4697     // maybe store down a new value
4698     Node* new_in = new_mem;
4699     if (new_in == new_base)  new_in = empty_mem;
4700 
4701     if (new_in != old_in) {
4702       // Warning:  Do not combine this "if" with the previous "if"
4703       // A memory slice might have be be rewritten even if it is semantically
4704       // unchanged, if the base_memory value has changed.
4705       set_req(i, new_in);
4706       progress = this;          // Report progress
4707     }
4708   }
4709 
4710   if (new_base != old_base) {
4711     set_req(Compile::AliasIdxBot, new_base);
4712     // Don't use set_base_memory(new_base), because we need to update du.
4713     assert(base_memory() == new_base, "");
4714     progress = this;
4715   }
4716 
4717   if( base_memory() == this ) {
4718     // a self cycle indicates this memory path is dead
4719     set_req(Compile::AliasIdxBot, empty_mem);
4720   }
4721 
4722   // Resolve external cycles by calling Ideal on a MergeMem base_memory
4723   // Recursion must occur after the self cycle check above
4724   if( base_memory()->is_MergeMem() ) {
4725     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
4726     Node *m = phase->transform(new_mbase);  // Rollup any cycles
4727     if( m != NULL &&
4728         (m->is_top() ||
4729          (m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem)) ) {
4730       // propagate rollup of dead cycle to self
4731       set_req(Compile::AliasIdxBot, empty_mem);
4732     }
4733   }
4734 
4735   if( base_memory() == empty_mem ) {
4736     progress = this;
4737     // Cut inputs during Parse phase only.
4738     // During Optimize phase a dead MergeMem node will be subsumed by Top.
4739     if( !can_reshape ) {
4740       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4741         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
4742       }
4743     }
4744   }
4745 
4746   if( !progress && base_memory()->is_Phi() && can_reshape ) {
4747     // Check if PhiNode::Ideal's "Split phis through memory merges"
4748     // transform should be attempted. Look for this->phi->this cycle.
4749     uint merge_width = req();
4750     if (merge_width > Compile::AliasIdxRaw) {
4751       PhiNode* phi = base_memory()->as_Phi();
4752       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
4753         if (phi->in(i) == this) {
4754           phase->is_IterGVN()->_worklist.push(phi);
4755           break;
4756         }
4757       }
4758     }
4759   }
4760 
4761   assert(progress || verify_sparse(), "please, no dups of base");
4762   return progress;
4763 }
4764 
4765 //-------------------------set_base_memory-------------------------------------
4766 void MergeMemNode::set_base_memory(Node *new_base) {
4767   Node* empty_mem = empty_memory();
4768   set_req(Compile::AliasIdxBot, new_base);
4769   assert(memory_at(req()) == new_base, "must set default memory");
4770   // Clear out other occurrences of new_base:
4771   if (new_base != empty_mem) {
4772     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4773       if (in(i) == new_base)  set_req(i, empty_mem);
4774     }
4775   }
4776 }
4777 
4778 //------------------------------out_RegMask------------------------------------
4779 const RegMask &MergeMemNode::out_RegMask() const {
4780   return RegMask::Empty;
4781 }
4782 
4783 //------------------------------dump_spec--------------------------------------
4784 #ifndef PRODUCT
4785 void MergeMemNode::dump_spec(outputStream *st) const {
4786   st->print(" {");
4787   Node* base_mem = base_memory();
4788   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
4789     Node* mem = (in(i) != NULL) ? memory_at(i) : base_mem;
4790     if (mem == base_mem) { st->print(" -"); continue; }
4791     st->print( " N%d:", mem->_idx );
4792     Compile::current()->get_adr_type(i)->dump_on(st);
4793   }
4794   st->print(" }");
4795 }
4796 #endif // !PRODUCT
4797 
4798 
4799 #ifdef ASSERT
4800 static bool might_be_same(Node* a, Node* b) {
4801   if (a == b)  return true;
4802   if (!(a->is_Phi() || b->is_Phi()))  return false;
4803   // phis shift around during optimization
4804   return true;  // pretty stupid...
4805 }
4806 
4807 // verify a narrow slice (either incoming or outgoing)
4808 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
4809   if (!VerifyAliases)                return;  // don't bother to verify unless requested
4810   if (VMError::is_error_reported())  return;  // muzzle asserts when debugging an error
4811   if (Node::in_dump())               return;  // muzzle asserts when printing
4812   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
4813   assert(n != NULL, "");
4814   // Elide intervening MergeMem's
4815   while (n->is_MergeMem()) {
4816     n = n->as_MergeMem()->memory_at(alias_idx);
4817   }
4818   Compile* C = Compile::current();
4819   const TypePtr* n_adr_type = n->adr_type();
4820   if (n == m->empty_memory()) {
4821     // Implicit copy of base_memory()
4822   } else if (n_adr_type != TypePtr::BOTTOM) {
4823     assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
4824     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
4825   } else {
4826     // A few places like make_runtime_call "know" that VM calls are narrow,
4827     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
4828     bool expected_wide_mem = false;
4829     if (n == m->base_memory()) {
4830       expected_wide_mem = true;
4831     } else if (alias_idx == Compile::AliasIdxRaw ||
4832                n == m->memory_at(Compile::AliasIdxRaw)) {
4833       expected_wide_mem = true;
4834     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
4835       // memory can "leak through" calls on channels that
4836       // are write-once.  Allow this also.
4837       expected_wide_mem = true;
4838     }
4839     assert(expected_wide_mem, "expected narrow slice replacement");
4840   }
4841 }
4842 #else // !ASSERT
4843 #define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
4844 #endif
4845 
4846 
4847 //-----------------------------memory_at---------------------------------------
4848 Node* MergeMemNode::memory_at(uint alias_idx) const {
4849   assert(alias_idx >= Compile::AliasIdxRaw ||
4850          alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
4851          "must avoid base_memory and AliasIdxTop");
4852 
4853   // Otherwise, it is a narrow slice.
4854   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
4855   Compile *C = Compile::current();
4856   if (is_empty_memory(n)) {
4857     // the array is sparse; empty slots are the "top" node
4858     n = base_memory();
4859     assert(Node::in_dump()
4860            || n == NULL || n->bottom_type() == Type::TOP
4861            || n->adr_type() == NULL // address is TOP
4862            || n->adr_type() == TypePtr::BOTTOM
4863            || n->adr_type() == TypeRawPtr::BOTTOM
4864            || Compile::current()->AliasLevel() == 0,
4865            "must be a wide memory");
4866     // AliasLevel == 0 if we are organizing the memory states manually.
4867     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
4868   } else {
4869     // make sure the stored slice is sane
4870     #ifdef ASSERT
4871     if (VMError::is_error_reported() || Node::in_dump()) {
4872     } else if (might_be_same(n, base_memory())) {
4873       // Give it a pass:  It is a mostly harmless repetition of the base.
4874       // This can arise normally from node subsumption during optimization.
4875     } else {
4876       verify_memory_slice(this, alias_idx, n);
4877     }
4878     #endif
4879   }
4880   return n;
4881 }
4882 
4883 //---------------------------set_memory_at-------------------------------------
4884 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
4885   verify_memory_slice(this, alias_idx, n);
4886   Node* empty_mem = empty_memory();
4887   if (n == base_memory())  n = empty_mem;  // collapse default
4888   uint need_req = alias_idx+1;
4889   if (req() < need_req) {
4890     if (n == empty_mem)  return;  // already the default, so do not grow me
4891     // grow the sparse array
4892     do {
4893       add_req(empty_mem);
4894     } while (req() < need_req);
4895   }
4896   set_req( alias_idx, n );
4897 }
4898 
4899 
4900 
4901 //--------------------------iteration_setup------------------------------------
4902 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
4903   if (other != NULL) {
4904     grow_to_match(other);
4905     // invariant:  the finite support of mm2 is within mm->req()
4906     #ifdef ASSERT
4907     for (uint i = req(); i < other->req(); i++) {
4908       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
4909     }
4910     #endif
4911   }
4912   // Replace spurious copies of base_memory by top.
4913   Node* base_mem = base_memory();
4914   if (base_mem != NULL && !base_mem->is_top()) {
4915     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
4916       if (in(i) == base_mem)
4917         set_req(i, empty_memory());
4918     }
4919   }
4920 }
4921 
4922 //---------------------------grow_to_match-------------------------------------
4923 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
4924   Node* empty_mem = empty_memory();
4925   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
4926   // look for the finite support of the other memory
4927   for (uint i = other->req(); --i >= req(); ) {
4928     if (other->in(i) != empty_mem) {
4929       uint new_len = i+1;
4930       while (req() < new_len)  add_req(empty_mem);
4931       break;
4932     }
4933   }
4934 }
4935 
4936 //---------------------------verify_sparse-------------------------------------
4937 #ifndef PRODUCT
4938 bool MergeMemNode::verify_sparse() const {
4939   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
4940   Node* base_mem = base_memory();
4941   // The following can happen in degenerate cases, since empty==top.
4942   if (is_empty_memory(base_mem))  return true;
4943   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4944     assert(in(i) != NULL, "sane slice");
4945     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
4946   }
4947   return true;
4948 }
4949 
4950 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
4951   Node* n;
4952   n = mm->in(idx);
4953   if (mem == n)  return true;  // might be empty_memory()
4954   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
4955   if (mem == n)  return true;
4956   while (n->is_Phi() && (n = n->as_Phi()->is_copy()) != NULL) {
4957     if (mem == n)  return true;
4958     if (n == NULL)  break;
4959   }
4960   return false;
4961 }
4962 #endif // !PRODUCT