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