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