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