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