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