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