1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/systemDictionary.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "memory/allocation.inline.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "oops/objArrayKlass.hpp"
  31 #include "opto/addnode.hpp"
  32 #include "opto/arraycopynode.hpp"
  33 #include "opto/cfgnode.hpp"
  34 #include "opto/compile.hpp"
  35 #include "opto/connode.hpp"
  36 #include "opto/convertnode.hpp"
  37 #include "opto/loopnode.hpp"
  38 #include "opto/machnode.hpp"
  39 #include "opto/matcher.hpp"
  40 #include "opto/memnode.hpp"
  41 #include "opto/mulnode.hpp"
  42 #include "opto/narrowptrnode.hpp"
  43 #include "opto/phaseX.hpp"
  44 #include "opto/regmask.hpp"
  45 #include "utilities/align.hpp"
  46 #include "utilities/copy.hpp"
  47 #include "utilities/vmError.hpp"
  48 
  49 // Portions of code courtesy of Clifford Click
  50 
  51 // Optimization - Graph Style
  52 
  53 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
  54 
  55 //=============================================================================
  56 uint MemNode::size_of() const { return sizeof(*this); }
  57 
  58 const TypePtr *MemNode::adr_type() const {
  59   Node* adr = in(Address);
  60   if (adr == NULL)  return NULL; // node is dead
  61   const TypePtr* cross_check = NULL;
  62   DEBUG_ONLY(cross_check = _adr_type);
  63   return calculate_adr_type(adr->bottom_type(), cross_check);
  64 }
  65 
  66 bool MemNode::check_if_adr_maybe_raw(Node* adr) {
  67   if (adr != NULL) {
  68     if (adr->bottom_type()->base() == Type::RawPtr || adr->bottom_type()->base() == Type::AnyPtr) {
  69       return true;
  70     }
  71   }
  72   return false;
  73 }
  74 
  75 #ifndef PRODUCT
  76 void MemNode::dump_spec(outputStream *st) const {
  77   if (in(Address) == NULL)  return; // node is dead
  78 #ifndef ASSERT
  79   // fake the missing field
  80   const TypePtr* _adr_type = NULL;
  81   if (in(Address) != NULL)
  82     _adr_type = in(Address)->bottom_type()->isa_ptr();
  83 #endif
  84   dump_adr_type(this, _adr_type, st);
  85 
  86   Compile* C = Compile::current();
  87   if (C->alias_type(_adr_type)->is_volatile()) {
  88     st->print(" Volatile!");
  89   }
  90   if (_unaligned_access) {
  91     st->print(" unaligned");
  92   }
  93   if (_mismatched_access) {
  94     st->print(" mismatched");
  95   }
  96 }
  97 
  98 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
  99   st->print(" @");
 100   if (adr_type == NULL) {
 101     st->print("NULL");
 102   } else {
 103     adr_type->dump_on(st);
 104     Compile* C = Compile::current();
 105     Compile::AliasType* atp = NULL;
 106     if (C->have_alias_type(adr_type))  atp = C->alias_type(adr_type);
 107     if (atp == NULL)
 108       st->print(", idx=?\?;");
 109     else if (atp->index() == Compile::AliasIdxBot)
 110       st->print(", idx=Bot;");
 111     else if (atp->index() == Compile::AliasIdxTop)
 112       st->print(", idx=Top;");
 113     else if (atp->index() == Compile::AliasIdxRaw)
 114       st->print(", idx=Raw;");
 115     else {
 116       ciField* field = atp->field();
 117       if (field) {
 118         st->print(", name=");
 119         field->print_name_on(st);
 120       }
 121       st->print(", idx=%d;", atp->index());
 122     }
 123   }
 124 }
 125 
 126 extern void print_alias_types();
 127 
 128 #endif
 129 
 130 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) {
 131   assert((t_oop != NULL), "sanity");
 132   bool is_instance = t_oop->is_known_instance_field();
 133   bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() &&
 134                              (load != NULL) && load->is_Load() &&
 135                              (phase->is_IterGVN() != NULL);
 136   if (!(is_instance || is_boxed_value_load))
 137     return mchain;  // don't try to optimize non-instance types
 138   uint instance_id = t_oop->instance_id();
 139   Node *start_mem = phase->C->start()->proj_out(TypeFunc::Memory);
 140   Node *prev = NULL;
 141   Node *result = mchain;
 142   while (prev != result) {
 143     prev = result;
 144     if (result == start_mem)
 145       break;  // hit one of our sentinels
 146     // skip over a call which does not affect this memory slice
 147     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
 148       Node *proj_in = result->in(0);
 149       if (proj_in->is_Allocate() && proj_in->_idx == instance_id) {
 150         break;  // hit one of our sentinels
 151       } else if (proj_in->is_Call()) {
 152         // ArrayCopyNodes processed here as well
 153         CallNode *call = proj_in->as_Call();
 154         if (!call->may_modify(t_oop, phase)) { // returns false for instances
 155           result = call->in(TypeFunc::Memory);
 156         }
 157       } else if (proj_in->is_Initialize()) {
 158         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
 159         // Stop if this is the initialization for the object instance which
 160         // contains this memory slice, otherwise skip over it.
 161         if ((alloc == NULL) || (alloc->_idx == instance_id)) {
 162           break;
 163         }
 164         if (is_instance) {
 165           result = proj_in->in(TypeFunc::Memory);
 166         } else if (is_boxed_value_load) {
 167           Node* klass = alloc->in(AllocateNode::KlassNode);
 168           const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr();
 169           if (tklass->klass_is_exact() && !tklass->klass()->equals(t_oop->klass())) {
 170             result = proj_in->in(TypeFunc::Memory); // not related allocation
 171           }
 172         }
 173       } else if (proj_in->is_MemBar()) {
 174         ArrayCopyNode* ac = NULL;
 175         if (ArrayCopyNode::may_modify(t_oop, proj_in->as_MemBar(), phase, ac)) {
 176           break;
 177         }
 178         result = proj_in->in(TypeFunc::Memory);
 179       } else {
 180         assert(false, "unexpected projection");
 181       }
 182     } else if (result->is_ClearArray()) {
 183       if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) {
 184         // Can not bypass initialization of the instance
 185         // we are looking for.
 186         break;
 187       }
 188       // Otherwise skip it (the call updated 'result' value).
 189     } else if (result->is_MergeMem()) {
 190       result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, NULL, tty);
 191     }
 192   }
 193   return result;
 194 }
 195 
 196 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) {
 197   const TypeOopPtr* t_oop = t_adr->isa_oopptr();
 198   if (t_oop == NULL)
 199     return mchain;  // don't try to optimize non-oop types
 200   Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase);
 201   bool is_instance = t_oop->is_known_instance_field();
 202   PhaseIterGVN *igvn = phase->is_IterGVN();
 203   if (is_instance && igvn != NULL  && result->is_Phi()) {
 204     PhiNode *mphi = result->as_Phi();
 205     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
 206     const TypePtr *t = mphi->adr_type();
 207     if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ||
 208         (t->isa_oopptr() && !t->is_oopptr()->is_known_instance() &&
 209          t->is_oopptr()->cast_to_exactness(true)
 210            ->is_oopptr()->cast_to_ptr_type(t_oop->ptr())
 211             ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop)) {
 212       // clone the Phi with our address type
 213       result = mphi->split_out_instance(t_adr, igvn);
 214     } else {
 215       assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
 216     }
 217   }
 218   return result;
 219 }
 220 
 221 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
 222   uint alias_idx = phase->C->get_alias_index(tp);
 223   Node *mem = mmem;
 224 #ifdef ASSERT
 225   {
 226     // Check that current type is consistent with the alias index used during graph construction
 227     assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
 228     bool consistent =  adr_check == NULL || adr_check->empty() ||
 229                        phase->C->must_alias(adr_check, alias_idx );
 230     // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
 231     if( !consistent && adr_check != NULL && !adr_check->empty() &&
 232                tp->isa_aryptr() &&        tp->offset() == Type::OffsetBot &&
 233         adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
 234         ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
 235           adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
 236           adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
 237       // don't assert if it is dead code.
 238       consistent = true;
 239     }
 240     if( !consistent ) {
 241       st->print("alias_idx==%d, adr_check==", alias_idx);
 242       if( adr_check == NULL ) {
 243         st->print("NULL");
 244       } else {
 245         adr_check->dump();
 246       }
 247       st->cr();
 248       print_alias_types();
 249       assert(consistent, "adr_check must match alias idx");
 250     }
 251   }
 252 #endif
 253   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
 254   // means an array I have not precisely typed yet.  Do not do any
 255   // alias stuff with it any time soon.
 256   const TypeOopPtr *toop = tp->isa_oopptr();
 257   if( tp->base() != Type::AnyPtr &&
 258       !(toop &&
 259         toop->klass() != NULL &&
 260         toop->klass()->is_java_lang_Object() &&
 261         toop->offset() == Type::OffsetBot) ) {
 262     // compress paths and change unreachable cycles to TOP
 263     // If not, we can update the input infinitely along a MergeMem cycle
 264     // Equivalent code in PhiNode::Ideal
 265     Node* m  = phase->transform(mmem);
 266     // If transformed to a MergeMem, get the desired slice
 267     // Otherwise the returned node represents memory for every slice
 268     mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
 269     // Update input if it is progress over what we have now
 270   }
 271   return mem;
 272 }
 273 
 274 //--------------------------Ideal_common---------------------------------------
 275 // Look for degenerate control and memory inputs.  Bypass MergeMem inputs.
 276 // Unhook non-raw memories from complete (macro-expanded) initializations.
 277 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
 278   // If our control input is a dead region, kill all below the region
 279   Node *ctl = in(MemNode::Control);
 280   if (ctl && remove_dead_region(phase, can_reshape))
 281     return this;
 282   ctl = in(MemNode::Control);
 283   // Don't bother trying to transform a dead node
 284   if (ctl && ctl->is_top())  return NodeSentinel;
 285 
 286   PhaseIterGVN *igvn = phase->is_IterGVN();
 287   // Wait if control on the worklist.
 288   if (ctl && can_reshape && igvn != NULL) {
 289     Node* bol = NULL;
 290     Node* cmp = NULL;
 291     if (ctl->in(0)->is_If()) {
 292       assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity");
 293       bol = ctl->in(0)->in(1);
 294       if (bol->is_Bool())
 295         cmp = ctl->in(0)->in(1)->in(1);
 296     }
 297     if (igvn->_worklist.member(ctl) ||
 298         (bol != NULL && igvn->_worklist.member(bol)) ||
 299         (cmp != NULL && igvn->_worklist.member(cmp)) ) {
 300       // This control path may be dead.
 301       // Delay this memory node transformation until the control is processed.
 302       phase->is_IterGVN()->_worklist.push(this);
 303       return NodeSentinel; // caller will return NULL
 304     }
 305   }
 306   // Ignore if memory is dead, or self-loop
 307   Node *mem = in(MemNode::Memory);
 308   if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return NULL
 309   assert(mem != this, "dead loop in MemNode::Ideal");
 310 
 311   if (can_reshape && igvn != NULL && igvn->_worklist.member(mem)) {
 312     // This memory slice may be dead.
 313     // Delay this mem node transformation until the memory is processed.
 314     phase->is_IterGVN()->_worklist.push(this);
 315     return NodeSentinel; // caller will return NULL
 316   }
 317 
 318   Node *address = in(MemNode::Address);
 319   const Type *t_adr = phase->type(address);
 320   if (t_adr == Type::TOP)              return NodeSentinel; // caller will return NULL
 321 
 322   if (can_reshape && igvn != NULL &&
 323       (igvn->_worklist.member(address) ||
 324        (igvn->_worklist.size() > 0 && t_adr != adr_type())) ) {
 325     // The address's base and type may change when the address is processed.
 326     // Delay this mem node transformation until the address is processed.
 327     phase->is_IterGVN()->_worklist.push(this);
 328     return NodeSentinel; // caller will return NULL
 329   }
 330 
 331   // Do NOT remove or optimize the next lines: ensure a new alias index
 332   // is allocated for an oop pointer type before Escape Analysis.
 333   // Note: C++ will not remove it since the call has side effect.
 334   if (t_adr->isa_oopptr()) {
 335     int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
 336   }
 337 
 338   Node* base = NULL;
 339   if (address->is_AddP()) {
 340     base = address->in(AddPNode::Base);
 341   }
 342   if (base != NULL && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
 343       !t_adr->isa_rawptr()) {
 344     // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
 345     // Skip this node optimization if its address has TOP base.
 346     return NodeSentinel; // caller will return NULL
 347   }
 348 
 349   // Avoid independent memory operations
 350   Node* old_mem = mem;
 351 
 352   // The code which unhooks non-raw memories from complete (macro-expanded)
 353   // initializations was removed. After macro-expansion all stores catched
 354   // by Initialize node became raw stores and there is no information
 355   // which memory slices they modify. So it is unsafe to move any memory
 356   // operation above these stores. Also in most cases hooked non-raw memories
 357   // were already unhooked by using information from detect_ptr_independence()
 358   // and find_previous_store().
 359 
 360   if (mem->is_MergeMem()) {
 361     MergeMemNode* mmem = mem->as_MergeMem();
 362     const TypePtr *tp = t_adr->is_ptr();
 363 
 364     mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
 365   }
 366 
 367   if (mem != old_mem) {
 368     set_req(MemNode::Memory, mem);
 369     if (can_reshape && old_mem->outcnt() == 0) {
 370         igvn->_worklist.push(old_mem);
 371     }
 372     if (phase->type( mem ) == Type::TOP) return NodeSentinel;
 373     return this;
 374   }
 375 
 376   // let the subclass continue analyzing...
 377   return NULL;
 378 }
 379 
 380 // Helper function for proving some simple control dominations.
 381 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
 382 // Already assumes that 'dom' is available at 'sub', and that 'sub'
 383 // is not a constant (dominated by the method's StartNode).
 384 // Used by MemNode::find_previous_store to prove that the
 385 // control input of a memory operation predates (dominates)
 386 // an allocation it wants to look past.
 387 bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
 388   if (dom == NULL || dom->is_top() || sub == NULL || sub->is_top())
 389     return false; // Conservative answer for dead code
 390 
 391   // Check 'dom'. Skip Proj and CatchProj nodes.
 392   dom = dom->find_exact_control(dom);
 393   if (dom == NULL || dom->is_top())
 394     return false; // Conservative answer for dead code
 395 
 396   if (dom == sub) {
 397     // For the case when, for example, 'sub' is Initialize and the original
 398     // 'dom' is Proj node of the 'sub'.
 399     return false;
 400   }
 401 
 402   if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub)
 403     return true;
 404 
 405   // 'dom' dominates 'sub' if its control edge and control edges
 406   // of all its inputs dominate or equal to sub's control edge.
 407 
 408   // Currently 'sub' is either Allocate, Initialize or Start nodes.
 409   // Or Region for the check in LoadNode::Ideal();
 410   // 'sub' should have sub->in(0) != NULL.
 411   assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() ||
 412          sub->is_Region() || sub->is_Call(), "expecting only these nodes");
 413 
 414   // Get control edge of 'sub'.
 415   Node* orig_sub = sub;
 416   sub = sub->find_exact_control(sub->in(0));
 417   if (sub == NULL || sub->is_top())
 418     return false; // Conservative answer for dead code
 419 
 420   assert(sub->is_CFG(), "expecting control");
 421 
 422   if (sub == dom)
 423     return true;
 424 
 425   if (sub->is_Start() || sub->is_Root())
 426     return false;
 427 
 428   {
 429     // Check all control edges of 'dom'.
 430 
 431     ResourceMark rm;
 432     Arena* arena = Thread::current()->resource_area();
 433     Node_List nlist(arena);
 434     Unique_Node_List dom_list(arena);
 435 
 436     dom_list.push(dom);
 437     bool only_dominating_controls = false;
 438 
 439     for (uint next = 0; next < dom_list.size(); next++) {
 440       Node* n = dom_list.at(next);
 441       if (n == orig_sub)
 442         return false; // One of dom's inputs dominated by sub.
 443       if (!n->is_CFG() && n->pinned()) {
 444         // Check only own control edge for pinned non-control nodes.
 445         n = n->find_exact_control(n->in(0));
 446         if (n == NULL || n->is_top())
 447           return false; // Conservative answer for dead code
 448         assert(n->is_CFG(), "expecting control");
 449         dom_list.push(n);
 450       } else if (n->is_Con() || n->is_Start() || n->is_Root()) {
 451         only_dominating_controls = true;
 452       } else if (n->is_CFG()) {
 453         if (n->dominates(sub, nlist))
 454           only_dominating_controls = true;
 455         else
 456           return false;
 457       } else {
 458         // First, own control edge.
 459         Node* m = n->find_exact_control(n->in(0));
 460         if (m != NULL) {
 461           if (m->is_top())
 462             return false; // Conservative answer for dead code
 463           dom_list.push(m);
 464         }
 465         // Now, the rest of edges.
 466         uint cnt = n->req();
 467         for (uint i = 1; i < cnt; i++) {
 468           m = n->find_exact_control(n->in(i));
 469           if (m == NULL || m->is_top())
 470             continue;
 471           dom_list.push(m);
 472         }
 473       }
 474     }
 475     return only_dominating_controls;
 476   }
 477 }
 478 
 479 //---------------------detect_ptr_independence---------------------------------
 480 // Used by MemNode::find_previous_store to prove that two base
 481 // pointers are never equal.
 482 // The pointers are accompanied by their associated allocations,
 483 // if any, which have been previously discovered by the caller.
 484 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
 485                                       Node* p2, AllocateNode* a2,
 486                                       PhaseTransform* phase) {
 487   // Attempt to prove that these two pointers cannot be aliased.
 488   // They may both manifestly be allocations, and they should differ.
 489   // Or, if they are not both allocations, they can be distinct constants.
 490   // Otherwise, one is an allocation and the other a pre-existing value.
 491   if (a1 == NULL && a2 == NULL) {           // neither an allocation
 492     return (p1 != p2) && p1->is_Con() && p2->is_Con();
 493   } else if (a1 != NULL && a2 != NULL) {    // both allocations
 494     return (a1 != a2);
 495   } else if (a1 != NULL) {                  // one allocation a1
 496     // (Note:  p2->is_Con implies p2->in(0)->is_Root, which dominates.)
 497     return all_controls_dominate(p2, a1);
 498   } else { //(a2 != NULL)                   // one allocation a2
 499     return all_controls_dominate(p1, a2);
 500   }
 501   return false;
 502 }
 503 
 504 
 505 // Find an arraycopy that must have set (can_see_stored_value=true) or
 506 // could have set (can_see_stored_value=false) the value for this load
 507 Node* LoadNode::find_previous_arraycopy(PhaseTransform* phase, Node* ld_alloc, Node*& mem, bool can_see_stored_value) const {
 508   if (mem->is_Proj() && mem->in(0) != NULL && (mem->in(0)->Opcode() == Op_MemBarStoreStore ||
 509                                                mem->in(0)->Opcode() == Op_MemBarCPUOrder)) {
 510     Node* mb = mem->in(0);
 511     if (mb->in(0) != NULL && mb->in(0)->is_Proj() &&
 512         mb->in(0)->in(0) != NULL && mb->in(0)->in(0)->is_ArrayCopy()) {
 513       ArrayCopyNode* ac = mb->in(0)->in(0)->as_ArrayCopy();
 514       if (ac->is_clonebasic()) {
 515         intptr_t offset;
 516         AllocateNode* alloc = AllocateNode::Ideal_allocation(ac->in(ArrayCopyNode::Dest), phase, offset);
 517         assert(alloc != NULL && (!ReduceBulkZeroing || alloc->initialization()->is_complete_with_arraycopy()), "broken allocation");
 518         if (alloc == ld_alloc) {
 519           return ac;
 520         }
 521       }
 522     }
 523   } else if (mem->is_Proj() && mem->in(0) != NULL && mem->in(0)->is_ArrayCopy()) {
 524     ArrayCopyNode* ac = mem->in(0)->as_ArrayCopy();
 525 
 526     if (ac->is_arraycopy_validated() ||
 527         ac->is_copyof_validated() ||
 528         ac->is_copyofrange_validated()) {
 529       Node* ld_addp = in(MemNode::Address);
 530       if (ld_addp->is_AddP()) {
 531         Node* ld_base = ld_addp->in(AddPNode::Address);
 532         Node* ld_offs = ld_addp->in(AddPNode::Offset);
 533 
 534         Node* dest = ac->in(ArrayCopyNode::Dest);
 535 
 536         if (dest == ld_base) {
 537           const TypeX *ld_offs_t = phase->type(ld_offs)->isa_intptr_t();
 538           if (ac->modifies(ld_offs_t->_lo, ld_offs_t->_hi, phase, can_see_stored_value)) {
 539             return ac;
 540           }
 541           if (!can_see_stored_value) {
 542             mem = ac->in(TypeFunc::Memory);
 543           }
 544         }
 545       }
 546     }
 547   }
 548   return NULL;
 549 }
 550 
 551 // The logic for reordering loads and stores uses four steps:
 552 // (a) Walk carefully past stores and initializations which we
 553 //     can prove are independent of this load.
 554 // (b) Observe that the next memory state makes an exact match
 555 //     with self (load or store), and locate the relevant store.
 556 // (c) Ensure that, if we were to wire self directly to the store,
 557 //     the optimizer would fold it up somehow.
 558 // (d) Do the rewiring, and return, depending on some other part of
 559 //     the optimizer to fold up the load.
 560 // This routine handles steps (a) and (b).  Steps (c) and (d) are
 561 // specific to loads and stores, so they are handled by the callers.
 562 // (Currently, only LoadNode::Ideal has steps (c), (d).  More later.)
 563 //
 564 Node* MemNode::find_previous_store(PhaseTransform* phase) {
 565   Node*         ctrl   = in(MemNode::Control);
 566   Node*         adr    = in(MemNode::Address);
 567   intptr_t      offset = 0;
 568   Node*         base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
 569   AllocateNode* alloc  = AllocateNode::Ideal_allocation(base, phase);
 570 
 571   if (offset == Type::OffsetBot)
 572     return NULL;            // cannot unalias unless there are precise offsets
 573 
 574   const bool adr_maybe_raw = check_if_adr_maybe_raw(adr);
 575   const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
 576 
 577   intptr_t size_in_bytes = memory_size();
 578 
 579   Node* mem = in(MemNode::Memory);   // start searching here...
 580 
 581   int cnt = 50;             // Cycle limiter
 582   for (;;) {                // While we can dance past unrelated stores...
 583     if (--cnt < 0)  break;  // Caught in cycle or a complicated dance?
 584 
 585     Node* prev = mem;
 586     if (mem->is_Store()) {
 587       Node* st_adr = mem->in(MemNode::Address);
 588       intptr_t st_offset = 0;
 589       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
 590       if (st_base == NULL)
 591         break;              // inscrutable pointer
 592 
 593       // For raw accesses it's not enough to prove that constant offsets don't intersect.
 594       // We need the bases to be the equal in order for the offset check to make sense.
 595       if ((adr_maybe_raw || check_if_adr_maybe_raw(st_adr)) && st_base != base) {
 596         break;
 597       }
 598 
 599       if (st_offset != offset && st_offset != Type::OffsetBot) {
 600         const int MAX_STORE = BytesPerLong;
 601         if (st_offset >= offset + size_in_bytes ||
 602             st_offset <= offset - MAX_STORE ||
 603             st_offset <= offset - mem->as_Store()->memory_size()) {
 604           // Success:  The offsets are provably independent.
 605           // (You may ask, why not just test st_offset != offset and be done?
 606           // The answer is that stores of different sizes can co-exist
 607           // in the same sequence of RawMem effects.  We sometimes initialize
 608           // a whole 'tile' of array elements with a single jint or jlong.)
 609           mem = mem->in(MemNode::Memory);
 610           continue;           // (a) advance through independent store memory
 611         }
 612       }
 613       if (st_base != base &&
 614           detect_ptr_independence(base, alloc,
 615                                   st_base,
 616                                   AllocateNode::Ideal_allocation(st_base, phase),
 617                                   phase)) {
 618         // Success:  The bases are provably independent.
 619         mem = mem->in(MemNode::Memory);
 620         continue;           // (a) advance through independent store memory
 621       }
 622 
 623       // (b) At this point, if the bases or offsets do not agree, we lose,
 624       // since we have not managed to prove 'this' and 'mem' independent.
 625       if (st_base == base && st_offset == offset) {
 626         return mem;         // let caller handle steps (c), (d)
 627       }
 628 
 629     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
 630       InitializeNode* st_init = mem->in(0)->as_Initialize();
 631       AllocateNode*  st_alloc = st_init->allocation();
 632       if (st_alloc == NULL)
 633         break;              // something degenerated
 634       bool known_identical = false;
 635       bool known_independent = false;
 636       if (alloc == st_alloc)
 637         known_identical = true;
 638       else if (alloc != NULL)
 639         known_independent = true;
 640       else if (all_controls_dominate(this, st_alloc))
 641         known_independent = true;
 642 
 643       if (known_independent) {
 644         // The bases are provably independent: Either they are
 645         // manifestly distinct allocations, or else the control
 646         // of this load dominates the store's allocation.
 647         int alias_idx = phase->C->get_alias_index(adr_type());
 648         if (alias_idx == Compile::AliasIdxRaw) {
 649           mem = st_alloc->in(TypeFunc::Memory);
 650         } else {
 651           mem = st_init->memory(alias_idx);
 652         }
 653         continue;           // (a) advance through independent store memory
 654       }
 655 
 656       // (b) at this point, if we are not looking at a store initializing
 657       // the same allocation we are loading from, we lose.
 658       if (known_identical) {
 659         // From caller, can_see_stored_value will consult find_captured_store.
 660         return mem;         // let caller handle steps (c), (d)
 661       }
 662 
 663     } else if (find_previous_arraycopy(phase, alloc, mem, false) != NULL) {
 664       if (prev != mem) {
 665         // Found an arraycopy but it doesn't affect that load
 666         continue;
 667       }
 668       // Found an arraycopy that may affect that load
 669       return mem;
 670     } else if (addr_t != NULL && addr_t->is_known_instance_field()) {
 671       // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
 672       if (mem->is_Proj() && mem->in(0)->is_Call()) {
 673         // ArrayCopyNodes processed here as well.
 674         CallNode *call = mem->in(0)->as_Call();
 675         if (!call->may_modify(addr_t, phase)) {
 676           mem = call->in(TypeFunc::Memory);
 677           continue;         // (a) advance through independent call memory
 678         }
 679       } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
 680         ArrayCopyNode* ac = NULL;
 681         if (ArrayCopyNode::may_modify(addr_t, mem->in(0)->as_MemBar(), phase, ac)) {
 682           break;
 683         }
 684         mem = mem->in(0)->in(TypeFunc::Memory);
 685         continue;           // (a) advance through independent MemBar memory
 686       } else if (mem->is_ClearArray()) {
 687         if (ClearArrayNode::step_through(&mem, (uint)addr_t->instance_id(), phase)) {
 688           // (the call updated 'mem' value)
 689           continue;         // (a) advance through independent allocation memory
 690         } else {
 691           // Can not bypass initialization of the instance
 692           // we are looking for.
 693           return mem;
 694         }
 695       } else if (mem->is_MergeMem()) {
 696         int alias_idx = phase->C->get_alias_index(adr_type());
 697         mem = mem->as_MergeMem()->memory_at(alias_idx);
 698         continue;           // (a) advance through independent MergeMem memory
 699       }
 700     }
 701 
 702     // Unless there is an explicit 'continue', we must bail out here,
 703     // because 'mem' is an inscrutable memory state (e.g., a call).
 704     break;
 705   }
 706 
 707   return NULL;              // bail out
 708 }
 709 
 710 //----------------------calculate_adr_type-------------------------------------
 711 // Helper function.  Notices when the given type of address hits top or bottom.
 712 // Also, asserts a cross-check of the type against the expected address type.
 713 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
 714   if (t == Type::TOP)  return NULL; // does not touch memory any more?
 715   #ifdef PRODUCT
 716   cross_check = NULL;
 717   #else
 718   if (!VerifyAliases || VMError::is_error_reported() || Node::in_dump())  cross_check = NULL;
 719   #endif
 720   const TypePtr* tp = t->isa_ptr();
 721   if (tp == NULL) {
 722     assert(cross_check == NULL || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
 723     return TypePtr::BOTTOM;           // touches lots of memory
 724   } else {
 725     #ifdef ASSERT
 726     // %%%% [phh] We don't check the alias index if cross_check is
 727     //            TypeRawPtr::BOTTOM.  Needs to be investigated.
 728     if (cross_check != NULL &&
 729         cross_check != TypePtr::BOTTOM &&
 730         cross_check != TypeRawPtr::BOTTOM) {
 731       // Recheck the alias index, to see if it has changed (due to a bug).
 732       Compile* C = Compile::current();
 733       assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
 734              "must stay in the original alias category");
 735       // The type of the address must be contained in the adr_type,
 736       // disregarding "null"-ness.
 737       // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
 738       const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
 739       assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(),
 740              "real address must not escape from expected memory type");
 741     }
 742     #endif
 743     return tp;
 744   }
 745 }
 746 
 747 //=============================================================================
 748 // Should LoadNode::Ideal() attempt to remove control edges?
 749 bool LoadNode::can_remove_control() const {
 750   return true;
 751 }
 752 uint LoadNode::size_of() const { return sizeof(*this); }
 753 uint LoadNode::cmp( const Node &n ) const
 754 { return !Type::cmp( _type, ((LoadNode&)n)._type ); }
 755 const Type *LoadNode::bottom_type() const { return _type; }
 756 uint LoadNode::ideal_reg() const {
 757   return _type->ideal_reg();
 758 }
 759 
 760 #ifndef PRODUCT
 761 void LoadNode::dump_spec(outputStream *st) const {
 762   MemNode::dump_spec(st);
 763   if( !Verbose && !WizardMode ) {
 764     // standard dump does this in Verbose and WizardMode
 765     st->print(" #"); _type->dump_on(st);
 766   }
 767   if (!depends_only_on_test()) {
 768     st->print(" (does not depend only on test)");
 769   }
 770 }
 771 #endif
 772 
 773 #ifdef ASSERT
 774 //----------------------------is_immutable_value-------------------------------
 775 // Helper function to allow a raw load without control edge for some cases
 776 bool LoadNode::is_immutable_value(Node* adr) {
 777   return (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() &&
 778           adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
 779           (adr->in(AddPNode::Offset)->find_intptr_t_con(-1) ==
 780            in_bytes(JavaThread::osthread_offset())));
 781 }
 782 #endif
 783 
 784 //----------------------------LoadNode::make-----------------------------------
 785 // Polymorphic factory method:
 786 Node *LoadNode::make(PhaseGVN& gvn, Node *ctl, Node *mem, Node *adr, const TypePtr* adr_type, const Type *rt, BasicType bt, MemOrd mo,
 787                      ControlDependency control_dependency, bool unaligned, bool mismatched) {
 788   Compile* C = gvn.C;
 789 
 790   // sanity check the alias category against the created node type
 791   assert(!(adr_type->isa_oopptr() &&
 792            adr_type->offset() == oopDesc::klass_offset_in_bytes()),
 793          "use LoadKlassNode instead");
 794   assert(!(adr_type->isa_aryptr() &&
 795            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
 796          "use LoadRangeNode instead");
 797   // Check control edge of raw loads
 798   assert( ctl != NULL || C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
 799           // oop will be recorded in oop map if load crosses safepoint
 800           rt->isa_oopptr() || is_immutable_value(adr),
 801           "raw memory operations should have control edge");
 802   LoadNode* load = NULL;
 803   switch (bt) {
 804   case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 805   case T_BYTE:    load = new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 806   case T_INT:     load = new LoadINode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 807   case T_CHAR:    load = new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 808   case T_SHORT:   load = new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
 809   case T_LONG:    load = new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency); break;
 810   case T_FLOAT:   load = new LoadFNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency); break;
 811   case T_DOUBLE:  load = new LoadDNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency); break;
 812   case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(),  mo, control_dependency); break;
 813   case T_OBJECT:
 814 #ifdef _LP64
 815     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
 816       load = new LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency);
 817     } else
 818 #endif
 819     {
 820       assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop");
 821       load = new LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency);
 822     }
 823     break;
 824   default:
 825     // ShouldNotReachHere(); ???
 826     break;
 827   }
 828   assert(load != NULL, "LoadNode should have been created");
 829   if (unaligned) {
 830     load->set_unaligned_access();
 831   }
 832   if (mismatched) {
 833     load->set_mismatched_access();
 834   }
 835   if (load->Opcode() == Op_LoadN) {
 836     Node* ld = gvn.transform(load);
 837     return new DecodeNNode(ld, ld->bottom_type()->make_ptr());
 838   }
 839 
 840   return load;
 841 }
 842 
 843 LoadLNode* LoadLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo,
 844                                   ControlDependency control_dependency, bool unaligned, bool mismatched) {
 845   bool require_atomic = true;
 846   LoadLNode* load = new LoadLNode(ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic);
 847   if (unaligned) {
 848     load->set_unaligned_access();
 849   }
 850   if (mismatched) {
 851     load->set_mismatched_access();
 852   }
 853   return load;
 854 }
 855 
 856 LoadDNode* LoadDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo,
 857                                   ControlDependency control_dependency, bool unaligned, bool mismatched) {
 858   bool require_atomic = true;
 859   LoadDNode* load = new LoadDNode(ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic);
 860   if (unaligned) {
 861     load->set_unaligned_access();
 862   }
 863   if (mismatched) {
 864     load->set_mismatched_access();
 865   }
 866   return load;
 867 }
 868 
 869 
 870 
 871 //------------------------------hash-------------------------------------------
 872 uint LoadNode::hash() const {
 873   // unroll addition of interesting fields
 874   return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
 875 }
 876 
 877 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) {
 878   if ((atp != NULL) && (atp->index() >= Compile::AliasIdxRaw)) {
 879     bool non_volatile = (atp->field() != NULL) && !atp->field()->is_volatile();
 880     bool is_stable_ary = FoldStableValues &&
 881                          (tp != NULL) && (tp->isa_aryptr() != NULL) &&
 882                          tp->isa_aryptr()->is_stable();
 883 
 884     return (eliminate_boxing && non_volatile) || is_stable_ary;
 885   }
 886 
 887   return false;
 888 }
 889 
 890 // Is the value loaded previously stored by an arraycopy? If so return
 891 // a load node that reads from the source array so we may be able to
 892 // optimize out the ArrayCopy node later.
 893 Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseGVN* phase) const {
 894   Node* ld_adr = in(MemNode::Address);
 895   intptr_t ld_off = 0;
 896   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
 897   Node* ac = find_previous_arraycopy(phase, ld_alloc, st, true);
 898   if (ac != NULL) {
 899     assert(ac->is_ArrayCopy(), "what kind of node can this be?");
 900 
 901     Node* mem = ac->in(TypeFunc::Memory);
 902     Node* ctl = ac->in(0);
 903     Node* src = ac->in(ArrayCopyNode::Src);
 904 
 905     if (!ac->as_ArrayCopy()->is_clonebasic() && !phase->type(src)->isa_aryptr()) {
 906       return NULL;
 907     }
 908 
 909     LoadNode* ld = clone()->as_Load();
 910     Node* addp = in(MemNode::Address)->clone();
 911     if (ac->as_ArrayCopy()->is_clonebasic()) {
 912       assert(ld_alloc != NULL, "need an alloc");
 913       assert(addp->is_AddP(), "address must be addp");
 914       assert(addp->in(AddPNode::Base) == ac->in(ArrayCopyNode::Dest)->in(AddPNode::Base), "strange pattern");
 915       assert(addp->in(AddPNode::Address) == ac->in(ArrayCopyNode::Dest)->in(AddPNode::Address), "strange pattern");
 916       addp->set_req(AddPNode::Base, src->in(AddPNode::Base));
 917       addp->set_req(AddPNode::Address, src->in(AddPNode::Address));
 918     } else {
 919       assert(ac->as_ArrayCopy()->is_arraycopy_validated() ||
 920              ac->as_ArrayCopy()->is_copyof_validated() ||
 921              ac->as_ArrayCopy()->is_copyofrange_validated(), "only supported cases");
 922       assert(addp->in(AddPNode::Base) == addp->in(AddPNode::Address), "should be");
 923       addp->set_req(AddPNode::Base, src);
 924       addp->set_req(AddPNode::Address, src);
 925 
 926       const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr();
 927       BasicType ary_elem  = ary_t->klass()->as_array_klass()->element_type()->basic_type();
 928       uint header = arrayOopDesc::base_offset_in_bytes(ary_elem);
 929       uint shift  = exact_log2(type2aelembytes(ary_elem));
 930 
 931       Node* diff = phase->transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
 932 #ifdef _LP64
 933       diff = phase->transform(new ConvI2LNode(diff));
 934 #endif
 935       diff = phase->transform(new LShiftXNode(diff, phase->intcon(shift)));
 936 
 937       Node* offset = phase->transform(new AddXNode(addp->in(AddPNode::Offset), diff));
 938       addp->set_req(AddPNode::Offset, offset);
 939     }
 940     addp = phase->transform(addp);
 941 #ifdef ASSERT
 942     const TypePtr* adr_type = phase->type(addp)->is_ptr();
 943     ld->_adr_type = adr_type;
 944 #endif
 945     ld->set_req(MemNode::Address, addp);
 946     ld->set_req(0, ctl);
 947     ld->set_req(MemNode::Memory, mem);
 948     // load depends on the tests that validate the arraycopy
 949     ld->_control_dependency = Pinned;
 950     return ld;
 951   }
 952   return NULL;
 953 }
 954 
 955 
 956 //---------------------------can_see_stored_value------------------------------
 957 // This routine exists to make sure this set of tests is done the same
 958 // everywhere.  We need to make a coordinated change: first LoadNode::Ideal
 959 // will change the graph shape in a way which makes memory alive twice at the
 960 // same time (uses the Oracle model of aliasing), then some
 961 // LoadXNode::Identity will fold things back to the equivalence-class model
 962 // of aliasing.
 963 Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
 964   Node* ld_adr = in(MemNode::Address);
 965   intptr_t ld_off = 0;
 966   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
 967   const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
 968   Compile::AliasType* atp = (tp != NULL) ? phase->C->alias_type(tp) : NULL;
 969   // This is more general than load from boxing objects.
 970   if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) {
 971     uint alias_idx = atp->index();
 972     bool final = !atp->is_rewritable();
 973     Node* result = NULL;
 974     Node* current = st;
 975     // Skip through chains of MemBarNodes checking the MergeMems for
 976     // new states for the slice of this load.  Stop once any other
 977     // kind of node is encountered.  Loads from final memory can skip
 978     // through any kind of MemBar but normal loads shouldn't skip
 979     // through MemBarAcquire since the could allow them to move out of
 980     // a synchronized region.
 981     while (current->is_Proj()) {
 982       int opc = current->in(0)->Opcode();
 983       if ((final && (opc == Op_MemBarAcquire ||
 984                      opc == Op_MemBarAcquireLock ||
 985                      opc == Op_LoadFence)) ||
 986           opc == Op_MemBarRelease ||
 987           opc == Op_StoreFence ||
 988           opc == Op_MemBarReleaseLock ||
 989           opc == Op_MemBarStoreStore ||
 990           opc == Op_MemBarCPUOrder) {
 991         Node* mem = current->in(0)->in(TypeFunc::Memory);
 992         if (mem->is_MergeMem()) {
 993           MergeMemNode* merge = mem->as_MergeMem();
 994           Node* new_st = merge->memory_at(alias_idx);
 995           if (new_st == merge->base_memory()) {
 996             // Keep searching
 997             current = new_st;
 998             continue;
 999           }
1000           // Save the new memory state for the slice and fall through
1001           // to exit.
1002           result = new_st;
1003         }
1004       }
1005       break;
1006     }
1007     if (result != NULL) {
1008       st = result;
1009     }
1010   }
1011 
1012   // Loop around twice in the case Load -> Initialize -> Store.
1013   // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
1014   for (int trip = 0; trip <= 1; trip++) {
1015 
1016     if (st->is_Store()) {
1017       Node* st_adr = st->in(MemNode::Address);
1018       if (!phase->eqv(st_adr, ld_adr)) {
1019         // Try harder before giving up...  Match raw and non-raw pointers.
1020         intptr_t st_off = 0;
1021         AllocateNode* alloc = AllocateNode::Ideal_allocation(st_adr, phase, st_off);
1022         if (alloc == NULL)       return NULL;
1023         if (alloc != ld_alloc)   return NULL;
1024         if (ld_off != st_off)    return NULL;
1025         // At this point we have proven something like this setup:
1026         //  A = Allocate(...)
1027         //  L = LoadQ(,  AddP(CastPP(, A.Parm),, #Off))
1028         //  S = StoreQ(, AddP(,        A.Parm  , #Off), V)
1029         // (Actually, we haven't yet proven the Q's are the same.)
1030         // In other words, we are loading from a casted version of
1031         // the same pointer-and-offset that we stored to.
1032         // Thus, we are able to replace L by V.
1033       }
1034       // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
1035       if (store_Opcode() != st->Opcode())
1036         return NULL;
1037       return st->in(MemNode::ValueIn);
1038     }
1039 
1040     // A load from a freshly-created object always returns zero.
1041     // (This can happen after LoadNode::Ideal resets the load's memory input
1042     // to find_captured_store, which returned InitializeNode::zero_memory.)
1043     if (st->is_Proj() && st->in(0)->is_Allocate() &&
1044         (st->in(0) == ld_alloc) &&
1045         (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) {
1046       // return a zero value for the load's basic type
1047       // (This is one of the few places where a generic PhaseTransform
1048       // can create new nodes.  Think of it as lazily manifesting
1049       // virtually pre-existing constants.)
1050       return phase->zerocon(memory_type());
1051     }
1052 
1053     // A load from an initialization barrier can match a captured store.
1054     if (st->is_Proj() && st->in(0)->is_Initialize()) {
1055       InitializeNode* init = st->in(0)->as_Initialize();
1056       AllocateNode* alloc = init->allocation();
1057       if ((alloc != NULL) && (alloc == ld_alloc)) {
1058         // examine a captured store value
1059         st = init->find_captured_store(ld_off, memory_size(), phase);
1060         if (st != NULL) {
1061           continue;             // take one more trip around
1062         }
1063       }
1064     }
1065 
1066     // Load boxed value from result of valueOf() call is input parameter.
1067     if (this->is_Load() && ld_adr->is_AddP() &&
1068         (tp != NULL) && tp->is_ptr_to_boxed_value()) {
1069       intptr_t ignore = 0;
1070       Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore);
1071       if (base != NULL && base->is_Proj() &&
1072           base->as_Proj()->_con == TypeFunc::Parms &&
1073           base->in(0)->is_CallStaticJava() &&
1074           base->in(0)->as_CallStaticJava()->is_boxing_method()) {
1075         return base->in(0)->in(TypeFunc::Parms);
1076       }
1077     }
1078 
1079     break;
1080   }
1081 
1082   return NULL;
1083 }
1084 
1085 //----------------------is_instance_field_load_with_local_phi------------------
1086 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
1087   if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl &&
1088       in(Address)->is_AddP() ) {
1089     const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr();
1090     // Only instances and boxed values.
1091     if( t_oop != NULL &&
1092         (t_oop->is_ptr_to_boxed_value() ||
1093          t_oop->is_known_instance_field()) &&
1094         t_oop->offset() != Type::OffsetBot &&
1095         t_oop->offset() != Type::OffsetTop) {
1096       return true;
1097     }
1098   }
1099   return false;
1100 }
1101 
1102 //------------------------------Identity---------------------------------------
1103 // Loads are identity if previous store is to same address
1104 Node* LoadNode::Identity(PhaseGVN* phase) {
1105   // If the previous store-maker is the right kind of Store, and the store is
1106   // to the same address, then we are equal to the value stored.
1107   Node* mem = in(Memory);
1108   Node* value = can_see_stored_value(mem, phase);
1109   if( value ) {
1110     // byte, short & char stores truncate naturally.
1111     // A load has to load the truncated value which requires
1112     // some sort of masking operation and that requires an
1113     // Ideal call instead of an Identity call.
1114     if (memory_size() < BytesPerInt) {
1115       // If the input to the store does not fit with the load's result type,
1116       // it must be truncated via an Ideal call.
1117       if (!phase->type(value)->higher_equal(phase->type(this)))
1118         return this;
1119     }
1120     // (This works even when value is a Con, but LoadNode::Value
1121     // usually runs first, producing the singleton type of the Con.)
1122     return value;
1123   }
1124 
1125   // Search for an existing data phi which was generated before for the same
1126   // instance's field to avoid infinite generation of phis in a loop.
1127   Node *region = mem->in(0);
1128   if (is_instance_field_load_with_local_phi(region)) {
1129     const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr();
1130     int this_index  = phase->C->get_alias_index(addr_t);
1131     int this_offset = addr_t->offset();
1132     int this_iid    = addr_t->instance_id();
1133     if (!addr_t->is_known_instance() &&
1134          addr_t->is_ptr_to_boxed_value()) {
1135       // Use _idx of address base (could be Phi node) for boxed values.
1136       intptr_t   ignore = 0;
1137       Node*      base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1138       if (base == NULL) {
1139         return this;
1140       }
1141       this_iid = base->_idx;
1142     }
1143     const Type* this_type = bottom_type();
1144     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1145       Node* phi = region->fast_out(i);
1146       if (phi->is_Phi() && phi != mem &&
1147           phi->as_Phi()->is_same_inst_field(this_type, (int)mem->_idx, this_iid, this_index, this_offset)) {
1148         return phi;
1149       }
1150     }
1151   }
1152 
1153   return this;
1154 }
1155 
1156 // Construct an equivalent unsigned load.
1157 Node* LoadNode::convert_to_unsigned_load(PhaseGVN& gvn) {
1158   BasicType bt = T_ILLEGAL;
1159   const Type* rt = NULL;
1160   switch (Opcode()) {
1161     case Op_LoadUB: return this;
1162     case Op_LoadUS: return this;
1163     case Op_LoadB: bt = T_BOOLEAN; rt = TypeInt::UBYTE; break;
1164     case Op_LoadS: bt = T_CHAR;    rt = TypeInt::CHAR;  break;
1165     default:
1166       assert(false, "no unsigned variant: %s", Name());
1167       return NULL;
1168   }
1169   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1170                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1171                         is_unaligned_access(), is_mismatched_access());
1172 }
1173 
1174 // Construct an equivalent signed load.
1175 Node* LoadNode::convert_to_signed_load(PhaseGVN& gvn) {
1176   BasicType bt = T_ILLEGAL;
1177   const Type* rt = NULL;
1178   switch (Opcode()) {
1179     case Op_LoadUB: bt = T_BYTE;  rt = TypeInt::BYTE;  break;
1180     case Op_LoadUS: bt = T_SHORT; rt = TypeInt::SHORT; break;
1181     case Op_LoadB: // fall through
1182     case Op_LoadS: // fall through
1183     case Op_LoadI: // fall through
1184     case Op_LoadL: return this;
1185     default:
1186       assert(false, "no signed variant: %s", Name());
1187       return NULL;
1188   }
1189   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1190                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1191                         is_unaligned_access(), is_mismatched_access());
1192 }
1193 
1194 // We're loading from an object which has autobox behaviour.
1195 // If this object is result of a valueOf call we'll have a phi
1196 // merging a newly allocated object and a load from the cache.
1197 // We want to replace this load with the original incoming
1198 // argument to the valueOf call.
1199 Node* LoadNode::eliminate_autobox(PhaseGVN* phase) {
1200   assert(phase->C->eliminate_boxing(), "sanity");
1201   intptr_t ignore = 0;
1202   Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1203   if ((base == NULL) || base->is_Phi()) {
1204     // Push the loads from the phi that comes from valueOf up
1205     // through it to allow elimination of the loads and the recovery
1206     // of the original value. It is done in split_through_phi().
1207     return NULL;
1208   } else if (base->is_Load() ||
1209              (base->is_DecodeN() && base->in(1)->is_Load())) {
1210     // Eliminate the load of boxed value for integer types from the cache
1211     // array by deriving the value from the index into the array.
1212     // Capture the offset of the load and then reverse the computation.
1213 
1214     // Get LoadN node which loads a boxing object from 'cache' array.
1215     if (base->is_DecodeN()) {
1216       base = base->in(1);
1217     }
1218     if (!base->in(Address)->is_AddP()) {
1219       return NULL; // Complex address
1220     }
1221     AddPNode* address = base->in(Address)->as_AddP();
1222     Node* cache_base = address->in(AddPNode::Base);
1223     if ((cache_base != NULL) && cache_base->is_DecodeN()) {
1224       // Get ConP node which is static 'cache' field.
1225       cache_base = cache_base->in(1);
1226     }
1227     if ((cache_base != NULL) && cache_base->is_Con()) {
1228       const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr();
1229       if ((base_type != NULL) && base_type->is_autobox_cache()) {
1230         Node* elements[4];
1231         int shift = exact_log2(type2aelembytes(T_OBJECT));
1232         int count = address->unpack_offsets(elements, ARRAY_SIZE(elements));
1233         if (count > 0 && elements[0]->is_Con() &&
1234             (count == 1 ||
1235              (count == 2 && elements[1]->Opcode() == Op_LShiftX &&
1236                             elements[1]->in(2) == phase->intcon(shift)))) {
1237           ciObjArray* array = base_type->const_oop()->as_obj_array();
1238           // Fetch the box object cache[0] at the base of the array and get its value
1239           ciInstance* box = array->obj_at(0)->as_instance();
1240           ciInstanceKlass* ik = box->klass()->as_instance_klass();
1241           assert(ik->is_box_klass(), "sanity");
1242           assert(ik->nof_nonstatic_fields() == 1, "change following code");
1243           if (ik->nof_nonstatic_fields() == 1) {
1244             // This should be true nonstatic_field_at requires calling
1245             // nof_nonstatic_fields so check it anyway
1246             ciConstant c = box->field_value(ik->nonstatic_field_at(0));
1247             BasicType bt = c.basic_type();
1248             // Only integer types have boxing cache.
1249             assert(bt == T_BOOLEAN || bt == T_CHAR  ||
1250                    bt == T_BYTE    || bt == T_SHORT ||
1251                    bt == T_INT     || bt == T_LONG, "wrong type = %s", type2name(bt));
1252             jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int();
1253             if (cache_low != (int)cache_low) {
1254               return NULL; // should not happen since cache is array indexed by value
1255             }
1256             jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift);
1257             if (offset != (int)offset) {
1258               return NULL; // should not happen since cache is array indexed by value
1259             }
1260            // Add up all the offsets making of the address of the load
1261             Node* result = elements[0];
1262             for (int i = 1; i < count; i++) {
1263               result = phase->transform(new AddXNode(result, elements[i]));
1264             }
1265             // Remove the constant offset from the address and then
1266             result = phase->transform(new AddXNode(result, phase->MakeConX(-(int)offset)));
1267             // remove the scaling of the offset to recover the original index.
1268             if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) {
1269               // Peel the shift off directly but wrap it in a dummy node
1270               // since Ideal can't return existing nodes
1271               result = new RShiftXNode(result->in(1), phase->intcon(0));
1272             } else if (result->is_Add() && result->in(2)->is_Con() &&
1273                        result->in(1)->Opcode() == Op_LShiftX &&
1274                        result->in(1)->in(2) == phase->intcon(shift)) {
1275               // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z)
1276               // but for boxing cache access we know that X<<Z will not overflow
1277               // (there is range check) so we do this optimizatrion by hand here.
1278               Node* add_con = new RShiftXNode(result->in(2), phase->intcon(shift));
1279               result = new AddXNode(result->in(1)->in(1), phase->transform(add_con));
1280             } else {
1281               result = new RShiftXNode(result, phase->intcon(shift));
1282             }
1283 #ifdef _LP64
1284             if (bt != T_LONG) {
1285               result = new ConvL2INode(phase->transform(result));
1286             }
1287 #else
1288             if (bt == T_LONG) {
1289               result = new ConvI2LNode(phase->transform(result));
1290             }
1291 #endif
1292             // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
1293             // Need to preserve unboxing load type if it is unsigned.
1294             switch(this->Opcode()) {
1295               case Op_LoadUB:
1296                 result = new AndINode(phase->transform(result), phase->intcon(0xFF));
1297                 break;
1298               case Op_LoadUS:
1299                 result = new AndINode(phase->transform(result), phase->intcon(0xFFFF));
1300                 break;
1301             }
1302             return result;
1303           }
1304         }
1305       }
1306     }
1307   }
1308   return NULL;
1309 }
1310 
1311 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) {
1312   Node* region = phi->in(0);
1313   if (region == NULL) {
1314     return false; // Wait stable graph
1315   }
1316   uint cnt = phi->req();
1317   for (uint i = 1; i < cnt; i++) {
1318     Node* rc = region->in(i);
1319     if (rc == NULL || phase->type(rc) == Type::TOP)
1320       return false; // Wait stable graph
1321     Node* in = phi->in(i);
1322     if (in == NULL || phase->type(in) == Type::TOP)
1323       return false; // Wait stable graph
1324   }
1325   return true;
1326 }
1327 //------------------------------split_through_phi------------------------------
1328 // Split instance or boxed field load through Phi.
1329 Node *LoadNode::split_through_phi(PhaseGVN *phase) {
1330   Node* mem     = in(Memory);
1331   Node* address = in(Address);
1332   const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr();
1333 
1334   assert((t_oop != NULL) &&
1335          (t_oop->is_known_instance_field() ||
1336           t_oop->is_ptr_to_boxed_value()), "invalide conditions");
1337 
1338   Compile* C = phase->C;
1339   intptr_t ignore = 0;
1340   Node*    base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1341   bool base_is_phi = (base != NULL) && base->is_Phi();
1342   bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() &&
1343                            (base != NULL) && (base == address->in(AddPNode::Base)) &&
1344                            phase->type(base)->higher_equal(TypePtr::NOTNULL);
1345 
1346   if (!((mem->is_Phi() || base_is_phi) &&
1347         (load_boxed_values || t_oop->is_known_instance_field()))) {
1348     return NULL; // memory is not Phi
1349   }
1350 
1351   if (mem->is_Phi()) {
1352     if (!stable_phi(mem->as_Phi(), phase)) {
1353       return NULL; // Wait stable graph
1354     }
1355     uint cnt = mem->req();
1356     // Check for loop invariant memory.
1357     if (cnt == 3) {
1358       for (uint i = 1; i < cnt; i++) {
1359         Node* in = mem->in(i);
1360         Node*  m = optimize_memory_chain(in, t_oop, this, phase);
1361         if (m == mem) {
1362           set_req(Memory, mem->in(cnt - i));
1363           return this; // made change
1364         }
1365       }
1366     }
1367   }
1368   if (base_is_phi) {
1369     if (!stable_phi(base->as_Phi(), phase)) {
1370       return NULL; // Wait stable graph
1371     }
1372     uint cnt = base->req();
1373     // Check for loop invariant memory.
1374     if (cnt == 3) {
1375       for (uint i = 1; i < cnt; i++) {
1376         if (base->in(i) == base) {
1377           return NULL; // Wait stable graph
1378         }
1379       }
1380     }
1381   }
1382 
1383   bool load_boxed_phi = load_boxed_values && base_is_phi && (base->in(0) == mem->in(0));
1384 
1385   // Split through Phi (see original code in loopopts.cpp).
1386   assert(C->have_alias_type(t_oop), "instance should have alias type");
1387 
1388   // Do nothing here if Identity will find a value
1389   // (to avoid infinite chain of value phis generation).
1390   if (!phase->eqv(this, this->Identity(phase)))
1391     return NULL;
1392 
1393   // Select Region to split through.
1394   Node* region;
1395   if (!base_is_phi) {
1396     assert(mem->is_Phi(), "sanity");
1397     region = mem->in(0);
1398     // Skip if the region dominates some control edge of the address.
1399     if (!MemNode::all_controls_dominate(address, region))
1400       return NULL;
1401   } else if (!mem->is_Phi()) {
1402     assert(base_is_phi, "sanity");
1403     region = base->in(0);
1404     // Skip if the region dominates some control edge of the memory.
1405     if (!MemNode::all_controls_dominate(mem, region))
1406       return NULL;
1407   } else if (base->in(0) != mem->in(0)) {
1408     assert(base_is_phi && mem->is_Phi(), "sanity");
1409     if (MemNode::all_controls_dominate(mem, base->in(0))) {
1410       region = base->in(0);
1411     } else if (MemNode::all_controls_dominate(address, mem->in(0))) {
1412       region = mem->in(0);
1413     } else {
1414       return NULL; // complex graph
1415     }
1416   } else {
1417     assert(base->in(0) == mem->in(0), "sanity");
1418     region = mem->in(0);
1419   }
1420 
1421   const Type* this_type = this->bottom_type();
1422   int this_index  = C->get_alias_index(t_oop);
1423   int this_offset = t_oop->offset();
1424   int this_iid    = t_oop->instance_id();
1425   if (!t_oop->is_known_instance() && load_boxed_values) {
1426     // Use _idx of address base for boxed values.
1427     this_iid = base->_idx;
1428   }
1429   PhaseIterGVN* igvn = phase->is_IterGVN();
1430   Node* phi = new PhiNode(region, this_type, NULL, mem->_idx, this_iid, this_index, this_offset);
1431   for (uint i = 1; i < region->req(); i++) {
1432     Node* x;
1433     Node* the_clone = NULL;
1434     if (region->in(i) == C->top()) {
1435       x = C->top();      // Dead path?  Use a dead data op
1436     } else {
1437       x = this->clone();        // Else clone up the data op
1438       the_clone = x;            // Remember for possible deletion.
1439       // Alter data node to use pre-phi inputs
1440       if (this->in(0) == region) {
1441         x->set_req(0, region->in(i));
1442       } else {
1443         x->set_req(0, NULL);
1444       }
1445       if (mem->is_Phi() && (mem->in(0) == region)) {
1446         x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone.
1447       }
1448       if (address->is_Phi() && address->in(0) == region) {
1449         x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone
1450       }
1451       if (base_is_phi && (base->in(0) == region)) {
1452         Node* base_x = base->in(i); // Clone address for loads from boxed objects.
1453         Node* adr_x = phase->transform(new AddPNode(base_x,base_x,address->in(AddPNode::Offset)));
1454         x->set_req(Address, adr_x);
1455       }
1456     }
1457     // Check for a 'win' on some paths
1458     const Type *t = x->Value(igvn);
1459 
1460     bool singleton = t->singleton();
1461 
1462     // See comments in PhaseIdealLoop::split_thru_phi().
1463     if (singleton && t == Type::TOP) {
1464       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
1465     }
1466 
1467     if (singleton) {
1468       x = igvn->makecon(t);
1469     } else {
1470       // We now call Identity to try to simplify the cloned node.
1471       // Note that some Identity methods call phase->type(this).
1472       // Make sure that the type array is big enough for
1473       // our new node, even though we may throw the node away.
1474       // (This tweaking with igvn only works because x is a new node.)
1475       igvn->set_type(x, t);
1476       // If x is a TypeNode, capture any more-precise type permanently into Node
1477       // otherwise it will be not updated during igvn->transform since
1478       // igvn->type(x) is set to x->Value() already.
1479       x->raise_bottom_type(t);
1480       Node *y = x->Identity(igvn);
1481       if (y != x) {
1482         x = y;
1483       } else {
1484         y = igvn->hash_find_insert(x);
1485         if (y) {
1486           x = y;
1487         } else {
1488           // Else x is a new node we are keeping
1489           // We do not need register_new_node_with_optimizer
1490           // because set_type has already been called.
1491           igvn->_worklist.push(x);
1492         }
1493       }
1494     }
1495     if (x != the_clone && the_clone != NULL) {
1496       igvn->remove_dead_node(the_clone);
1497     }
1498     phi->set_req(i, x);
1499   }
1500   // Record Phi
1501   igvn->register_new_node_with_optimizer(phi);
1502   return phi;
1503 }
1504 
1505 //------------------------------Ideal------------------------------------------
1506 // If the load is from Field memory and the pointer is non-null, it might be possible to
1507 // zero out the control input.
1508 // If the offset is constant and the base is an object allocation,
1509 // try to hook me up to the exact initializing store.
1510 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1511   Node* p = MemNode::Ideal_common(phase, can_reshape);
1512   if (p)  return (p == NodeSentinel) ? NULL : p;
1513 
1514   Node* ctrl    = in(MemNode::Control);
1515   Node* address = in(MemNode::Address);
1516   bool progress = false;
1517 
1518   // Skip up past a SafePoint control.  Cannot do this for Stores because
1519   // pointer stores & cardmarks must stay on the same side of a SafePoint.
1520   if( ctrl != NULL && ctrl->Opcode() == Op_SafePoint &&
1521       phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw ) {
1522     ctrl = ctrl->in(0);
1523     set_req(MemNode::Control,ctrl);
1524     progress = true;
1525   }
1526 
1527   intptr_t ignore = 0;
1528   Node*    base   = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1529   if (base != NULL
1530       && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) {
1531     // Check for useless control edge in some common special cases
1532     if (in(MemNode::Control) != NULL
1533         && can_remove_control()
1534         && phase->type(base)->higher_equal(TypePtr::NOTNULL)
1535         && all_controls_dominate(base, phase->C->start())) {
1536       // A method-invariant, non-null address (constant or 'this' argument).
1537       set_req(MemNode::Control, NULL);
1538       progress = true;
1539     }
1540   }
1541 
1542   Node* mem = in(MemNode::Memory);
1543   const TypePtr *addr_t = phase->type(address)->isa_ptr();
1544 
1545   if (can_reshape && (addr_t != NULL)) {
1546     // try to optimize our memory input
1547     Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase);
1548     if (opt_mem != mem) {
1549       set_req(MemNode::Memory, opt_mem);
1550       if (phase->type( opt_mem ) == Type::TOP) return NULL;
1551       return this;
1552     }
1553     const TypeOopPtr *t_oop = addr_t->isa_oopptr();
1554     if ((t_oop != NULL) &&
1555         (t_oop->is_known_instance_field() ||
1556          t_oop->is_ptr_to_boxed_value())) {
1557       PhaseIterGVN *igvn = phase->is_IterGVN();
1558       if (igvn != NULL && igvn->_worklist.member(opt_mem)) {
1559         // Delay this transformation until memory Phi is processed.
1560         phase->is_IterGVN()->_worklist.push(this);
1561         return NULL;
1562       }
1563       // Split instance field load through Phi.
1564       Node* result = split_through_phi(phase);
1565       if (result != NULL) return result;
1566 
1567       if (t_oop->is_ptr_to_boxed_value()) {
1568         Node* result = eliminate_autobox(phase);
1569         if (result != NULL) return result;
1570       }
1571     }
1572   }
1573 
1574   // Is there a dominating load that loads the same value?  Leave
1575   // anything that is not a load of a field/array element (like
1576   // barriers etc.) alone
1577   if (in(0) != NULL && adr_type() != TypeRawPtr::BOTTOM && can_reshape) {
1578     for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
1579       Node *use = mem->fast_out(i);
1580       if (use != this &&
1581           use->Opcode() == Opcode() &&
1582           use->in(0) != NULL &&
1583           use->in(0) != in(0) &&
1584           use->in(Address) == in(Address)) {
1585         Node* ctl = in(0);
1586         for (int i = 0; i < 10 && ctl != NULL; i++) {
1587           ctl = IfNode::up_one_dom(ctl);
1588           if (ctl == use->in(0)) {
1589             set_req(0, use->in(0));
1590             return this;
1591           }
1592         }
1593       }
1594     }
1595   }
1596 
1597   // Check for prior store with a different base or offset; make Load
1598   // independent.  Skip through any number of them.  Bail out if the stores
1599   // are in an endless dead cycle and report no progress.  This is a key
1600   // transform for Reflection.  However, if after skipping through the Stores
1601   // we can't then fold up against a prior store do NOT do the transform as
1602   // this amounts to using the 'Oracle' model of aliasing.  It leaves the same
1603   // array memory alive twice: once for the hoisted Load and again after the
1604   // bypassed Store.  This situation only works if EVERYBODY who does
1605   // anti-dependence work knows how to bypass.  I.e. we need all
1606   // anti-dependence checks to ask the same Oracle.  Right now, that Oracle is
1607   // the alias index stuff.  So instead, peek through Stores and IFF we can
1608   // fold up, do so.
1609   Node* prev_mem = find_previous_store(phase);
1610   if (prev_mem != NULL) {
1611     Node* value = can_see_arraycopy_value(prev_mem, phase);
1612     if (value != NULL) {
1613       return value;
1614     }
1615   }
1616   // Steps (a), (b):  Walk past independent stores to find an exact match.
1617   if (prev_mem != NULL && prev_mem != in(MemNode::Memory)) {
1618     // (c) See if we can fold up on the spot, but don't fold up here.
1619     // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or
1620     // just return a prior value, which is done by Identity calls.
1621     if (can_see_stored_value(prev_mem, phase)) {
1622       // Make ready for step (d):
1623       set_req(MemNode::Memory, prev_mem);
1624       return this;
1625     }
1626   }
1627 
1628   return progress ? this : NULL;
1629 }
1630 
1631 // Helper to recognize certain Klass fields which are invariant across
1632 // some group of array types (e.g., int[] or all T[] where T < Object).
1633 const Type*
1634 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
1635                                  ciKlass* klass) const {
1636   if (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) {
1637     // The field is Klass::_modifier_flags.  Return its (constant) value.
1638     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
1639     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
1640     return TypeInt::make(klass->modifier_flags());
1641   }
1642   if (tkls->offset() == in_bytes(Klass::access_flags_offset())) {
1643     // The field is Klass::_access_flags.  Return its (constant) value.
1644     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
1645     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
1646     return TypeInt::make(klass->access_flags());
1647   }
1648   if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
1649     // The field is Klass::_layout_helper.  Return its constant value if known.
1650     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
1651     return TypeInt::make(klass->layout_helper());
1652   }
1653 
1654   // No match.
1655   return NULL;
1656 }
1657 
1658 //------------------------------Value-----------------------------------------
1659 const Type* LoadNode::Value(PhaseGVN* phase) const {
1660   // Either input is TOP ==> the result is TOP
1661   Node* mem = in(MemNode::Memory);
1662   const Type *t1 = phase->type(mem);
1663   if (t1 == Type::TOP)  return Type::TOP;
1664   Node* adr = in(MemNode::Address);
1665   const TypePtr* tp = phase->type(adr)->isa_ptr();
1666   if (tp == NULL || tp->empty())  return Type::TOP;
1667   int off = tp->offset();
1668   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
1669   Compile* C = phase->C;
1670 
1671   // Try to guess loaded type from pointer type
1672   if (tp->isa_aryptr()) {
1673     const TypeAryPtr* ary = tp->is_aryptr();
1674     const Type* t = ary->elem();
1675 
1676     // Determine whether the reference is beyond the header or not, by comparing
1677     // the offset against the offset of the start of the array's data.
1678     // Different array types begin at slightly different offsets (12 vs. 16).
1679     // We choose T_BYTE as an example base type that is least restrictive
1680     // as to alignment, which will therefore produce the smallest
1681     // possible base offset.
1682     const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1683     const bool off_beyond_header = ((uint)off >= (uint)min_base_off);
1684 
1685     // Try to constant-fold a stable array element.
1686     if (FoldStableValues && !is_mismatched_access() && ary->is_stable()) {
1687       // Make sure the reference is not into the header and the offset is constant
1688       ciObject* aobj = ary->const_oop();
1689       if (aobj != NULL && off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
1690         int stable_dimension = (ary->stable_dimension() > 0 ? ary->stable_dimension() - 1 : 0);
1691         const Type* con_type = Type::make_constant_from_array_element(aobj->as_array(), off,
1692                                                                       stable_dimension,
1693                                                                       memory_type(), is_unsigned());
1694         if (con_type != NULL) {
1695           return con_type;
1696         }
1697       }
1698     }
1699 
1700     // Don't do this for integer types. There is only potential profit if
1701     // the element type t is lower than _type; that is, for int types, if _type is
1702     // more restrictive than t.  This only happens here if one is short and the other
1703     // char (both 16 bits), and in those cases we've made an intentional decision
1704     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
1705     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
1706     //
1707     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
1708     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
1709     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
1710     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
1711     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
1712     // In fact, that could have been the original type of p1, and p1 could have
1713     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
1714     // expression (LShiftL quux 3) independently optimized to the constant 8.
1715     if ((t->isa_int() == NULL) && (t->isa_long() == NULL)
1716         && (_type->isa_vect() == NULL)
1717         && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
1718       // t might actually be lower than _type, if _type is a unique
1719       // concrete subclass of abstract class t.
1720       if (off_beyond_header) {  // is the offset beyond the header?
1721         const Type* jt = t->join_speculative(_type);
1722         // In any case, do not allow the join, per se, to empty out the type.
1723         if (jt->empty() && !t->empty()) {
1724           // This can happen if a interface-typed array narrows to a class type.
1725           jt = _type;
1726         }
1727 #ifdef ASSERT
1728         if (phase->C->eliminate_boxing() && adr->is_AddP()) {
1729           // The pointers in the autobox arrays are always non-null
1730           Node* base = adr->in(AddPNode::Base);
1731           if ((base != NULL) && base->is_DecodeN()) {
1732             // Get LoadN node which loads IntegerCache.cache field
1733             base = base->in(1);
1734           }
1735           if ((base != NULL) && base->is_Con()) {
1736             const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
1737             if ((base_type != NULL) && base_type->is_autobox_cache()) {
1738               // It could be narrow oop
1739               assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
1740             }
1741           }
1742         }
1743 #endif
1744         return jt;
1745       }
1746     }
1747   } else if (tp->base() == Type::InstPtr) {
1748     assert( off != Type::OffsetBot ||
1749             // arrays can be cast to Objects
1750             tp->is_oopptr()->klass()->is_java_lang_Object() ||
1751             // unsafe field access may not have a constant offset
1752             C->has_unsafe_access(),
1753             "Field accesses must be precise" );
1754     // For oop loads, we expect the _type to be precise.
1755 
1756     // Optimize loads from constant fields.
1757     const TypeInstPtr* tinst = tp->is_instptr();
1758     ciObject* const_oop = tinst->const_oop();
1759     if (!is_mismatched_access() && off != Type::OffsetBot && const_oop != NULL && const_oop->is_instance()) {
1760       const Type* con_type = Type::make_constant_from_field(const_oop->as_instance(), off, is_unsigned(), memory_type());
1761       if (con_type != NULL) {
1762         return con_type;
1763       }
1764     }
1765   } else if (tp->base() == Type::KlassPtr) {
1766     assert( off != Type::OffsetBot ||
1767             // arrays can be cast to Objects
1768             tp->is_klassptr()->klass()->is_java_lang_Object() ||
1769             // also allow array-loading from the primary supertype
1770             // array during subtype checks
1771             Opcode() == Op_LoadKlass,
1772             "Field accesses must be precise" );
1773     // For klass/static loads, we expect the _type to be precise
1774   } else if (tp->base() == Type::RawPtr && adr->is_Load() && off == 0) {
1775     /* With mirrors being an indirect in the Klass*
1776      * the VM is now using two load. LoadKlass(LoadP(LoadP(Klass, mirror_offset), zero_offset))
1777      * The LoadP from the Klass has a RawPtr type (see LibraryCallKit::load_mirror_from_klass).
1778      *
1779      * So check the type and klass of the node before the LoadP
1780      */
1781     Node* adr2 = adr->in(MemNode::Address);
1782     const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
1783     if (tkls != NULL && !StressReflectiveCode) {
1784       ciKlass* klass = tkls->klass();
1785       if (klass->is_loaded() && tkls->klass_is_exact() && tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
1786         assert(adr->Opcode() == Op_LoadP, "must load an oop from _java_mirror");
1787         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
1788         return TypeInstPtr::make(klass->java_mirror());
1789       }
1790     }
1791   }
1792 
1793   const TypeKlassPtr *tkls = tp->isa_klassptr();
1794   if (tkls != NULL && !StressReflectiveCode) {
1795     ciKlass* klass = tkls->klass();
1796     if (klass->is_loaded() && tkls->klass_is_exact()) {
1797       // We are loading a field from a Klass metaobject whose identity
1798       // is known at compile time (the type is "exact" or "precise").
1799       // Check for fields we know are maintained as constants by the VM.
1800       if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
1801         // The field is Klass::_super_check_offset.  Return its (constant) value.
1802         // (Folds up type checking code.)
1803         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
1804         return TypeInt::make(klass->super_check_offset());
1805       }
1806       // Compute index into primary_supers array
1807       juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
1808       // Check for overflowing; use unsigned compare to handle the negative case.
1809       if( depth < ciKlass::primary_super_limit() ) {
1810         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
1811         // (Folds up type checking code.)
1812         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1813         ciKlass *ss = klass->super_of_depth(depth);
1814         return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1815       }
1816       const Type* aift = load_array_final_field(tkls, klass);
1817       if (aift != NULL)  return aift;






1818     }
1819 
1820     // We can still check if we are loading from the primary_supers array at a
1821     // shallow enough depth.  Even though the klass is not exact, entries less
1822     // than or equal to its super depth are correct.
1823     if (klass->is_loaded() ) {
1824       ciType *inner = klass;
1825       while( inner->is_obj_array_klass() )
1826         inner = inner->as_obj_array_klass()->base_element_type();
1827       if( inner->is_instance_klass() &&
1828           !inner->as_instance_klass()->flags().is_interface() ) {
1829         // Compute index into primary_supers array
1830         juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
1831         // Check for overflowing; use unsigned compare to handle the negative case.
1832         if( depth < ciKlass::primary_super_limit() &&
1833             depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
1834           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
1835           // (Folds up type checking code.)
1836           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1837           ciKlass *ss = klass->super_of_depth(depth);
1838           return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1839         }
1840       }
1841     }
1842 
1843     // If the type is enough to determine that the thing is not an array,
1844     // we can give the layout_helper a positive interval type.
1845     // This will help short-circuit some reflective code.
1846     if (tkls->offset() == in_bytes(Klass::layout_helper_offset())
1847         && !klass->is_array_klass() // not directly typed as an array
1848         && !klass->is_interface()  // specifically not Serializable & Cloneable
1849         && !klass->is_java_lang_Object()   // not the supertype of all T[]
1850         ) {
1851       // Note:  When interfaces are reliable, we can narrow the interface
1852       // test to (klass != Serializable && klass != Cloneable).
1853       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
1854       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
1855       // The key property of this type is that it folds up tests
1856       // for array-ness, since it proves that the layout_helper is positive.
1857       // Thus, a generic value like the basic object layout helper works fine.
1858       return TypeInt::make(min_size, max_jint, Type::WidenMin);
1859     }
1860   }
1861 
1862   // If we are loading from a freshly-allocated object, produce a zero,
1863   // if the load is provably beyond the header of the object.
1864   // (Also allow a variable load from a fresh array to produce zero.)
1865   const TypeOopPtr *tinst = tp->isa_oopptr();
1866   bool is_instance = (tinst != NULL) && tinst->is_known_instance_field();
1867   bool is_boxed_value = (tinst != NULL) && tinst->is_ptr_to_boxed_value();
1868   if (ReduceFieldZeroing || is_instance || is_boxed_value) {
1869     Node* value = can_see_stored_value(mem,phase);
1870     if (value != NULL && value->is_Con()) {
1871       assert(value->bottom_type()->higher_equal(_type),"sanity");
1872       return value->bottom_type();
1873     }
1874   }
1875 
1876   if (is_instance) {
1877     // If we have an instance type and our memory input is the
1878     // programs's initial memory state, there is no matching store,
1879     // so just return a zero of the appropriate type
1880     Node *mem = in(MemNode::Memory);
1881     if (mem->is_Parm() && mem->in(0)->is_Start()) {
1882       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
1883       return Type::get_zero_type(_type->basic_type());
1884     }
1885   }
1886   return _type;
1887 }
1888 
1889 //------------------------------match_edge-------------------------------------
1890 // Do we Match on this edge index or not?  Match only the address.
1891 uint LoadNode::match_edge(uint idx) const {
1892   return idx == MemNode::Address;
1893 }
1894 
1895 //--------------------------LoadBNode::Ideal--------------------------------------
1896 //
1897 //  If the previous store is to the same address as this load,
1898 //  and the value stored was larger than a byte, replace this load
1899 //  with the value stored truncated to a byte.  If no truncation is
1900 //  needed, the replacement is done in LoadNode::Identity().
1901 //
1902 Node *LoadBNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1903   Node* mem = in(MemNode::Memory);
1904   Node* value = can_see_stored_value(mem,phase);
1905   if( value && !phase->type(value)->higher_equal( _type ) ) {
1906     Node *result = phase->transform( new LShiftINode(value, phase->intcon(24)) );
1907     return new RShiftINode(result, phase->intcon(24));
1908   }
1909   // Identity call will handle the case where truncation is not needed.
1910   return LoadNode::Ideal(phase, can_reshape);
1911 }
1912 
1913 const Type* LoadBNode::Value(PhaseGVN* phase) const {
1914   Node* mem = in(MemNode::Memory);
1915   Node* value = can_see_stored_value(mem,phase);
1916   if (value != NULL && value->is_Con() &&
1917       !value->bottom_type()->higher_equal(_type)) {
1918     // If the input to the store does not fit with the load's result type,
1919     // it must be truncated. We can't delay until Ideal call since
1920     // a singleton Value is needed for split_thru_phi optimization.
1921     int con = value->get_int();
1922     return TypeInt::make((con << 24) >> 24);
1923   }
1924   return LoadNode::Value(phase);
1925 }
1926 
1927 //--------------------------LoadUBNode::Ideal-------------------------------------
1928 //
1929 //  If the previous store is to the same address as this load,
1930 //  and the value stored was larger than a byte, replace this load
1931 //  with the value stored truncated to a byte.  If no truncation is
1932 //  needed, the replacement is done in LoadNode::Identity().
1933 //
1934 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
1935   Node* mem = in(MemNode::Memory);
1936   Node* value = can_see_stored_value(mem, phase);
1937   if (value && !phase->type(value)->higher_equal(_type))
1938     return new AndINode(value, phase->intcon(0xFF));
1939   // Identity call will handle the case where truncation is not needed.
1940   return LoadNode::Ideal(phase, can_reshape);
1941 }
1942 
1943 const Type* LoadUBNode::Value(PhaseGVN* phase) const {
1944   Node* mem = in(MemNode::Memory);
1945   Node* value = can_see_stored_value(mem,phase);
1946   if (value != NULL && value->is_Con() &&
1947       !value->bottom_type()->higher_equal(_type)) {
1948     // If the input to the store does not fit with the load's result type,
1949     // it must be truncated. We can't delay until Ideal call since
1950     // a singleton Value is needed for split_thru_phi optimization.
1951     int con = value->get_int();
1952     return TypeInt::make(con & 0xFF);
1953   }
1954   return LoadNode::Value(phase);
1955 }
1956 
1957 //--------------------------LoadUSNode::Ideal-------------------------------------
1958 //
1959 //  If the previous store is to the same address as this load,
1960 //  and the value stored was larger than a char, replace this load
1961 //  with the value stored truncated to a char.  If no truncation is
1962 //  needed, the replacement is done in LoadNode::Identity().
1963 //
1964 Node *LoadUSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1965   Node* mem = in(MemNode::Memory);
1966   Node* value = can_see_stored_value(mem,phase);
1967   if( value && !phase->type(value)->higher_equal( _type ) )
1968     return new AndINode(value,phase->intcon(0xFFFF));
1969   // Identity call will handle the case where truncation is not needed.
1970   return LoadNode::Ideal(phase, can_reshape);
1971 }
1972 
1973 const Type* LoadUSNode::Value(PhaseGVN* phase) const {
1974   Node* mem = in(MemNode::Memory);
1975   Node* value = can_see_stored_value(mem,phase);
1976   if (value != NULL && value->is_Con() &&
1977       !value->bottom_type()->higher_equal(_type)) {
1978     // If the input to the store does not fit with the load's result type,
1979     // it must be truncated. We can't delay until Ideal call since
1980     // a singleton Value is needed for split_thru_phi optimization.
1981     int con = value->get_int();
1982     return TypeInt::make(con & 0xFFFF);
1983   }
1984   return LoadNode::Value(phase);
1985 }
1986 
1987 //--------------------------LoadSNode::Ideal--------------------------------------
1988 //
1989 //  If the previous store is to the same address as this load,
1990 //  and the value stored was larger than a short, replace this load
1991 //  with the value stored truncated to a short.  If no truncation is
1992 //  needed, the replacement is done in LoadNode::Identity().
1993 //
1994 Node *LoadSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1995   Node* mem = in(MemNode::Memory);
1996   Node* value = can_see_stored_value(mem,phase);
1997   if( value && !phase->type(value)->higher_equal( _type ) ) {
1998     Node *result = phase->transform( new LShiftINode(value, phase->intcon(16)) );
1999     return new RShiftINode(result, phase->intcon(16));
2000   }
2001   // Identity call will handle the case where truncation is not needed.
2002   return LoadNode::Ideal(phase, can_reshape);
2003 }
2004 
2005 const Type* LoadSNode::Value(PhaseGVN* phase) const {
2006   Node* mem = in(MemNode::Memory);
2007   Node* value = can_see_stored_value(mem,phase);
2008   if (value != NULL && value->is_Con() &&
2009       !value->bottom_type()->higher_equal(_type)) {
2010     // If the input to the store does not fit with the load's result type,
2011     // it must be truncated. We can't delay until Ideal call since
2012     // a singleton Value is needed for split_thru_phi optimization.
2013     int con = value->get_int();
2014     return TypeInt::make((con << 16) >> 16);
2015   }
2016   return LoadNode::Value(phase);
2017 }
2018 
2019 //=============================================================================
2020 //----------------------------LoadKlassNode::make------------------------------
2021 // Polymorphic factory method:
2022 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) {
2023   // sanity check the alias category against the created node type
2024   const TypePtr *adr_type = adr->bottom_type()->isa_ptr();
2025   assert(adr_type != NULL, "expecting TypeKlassPtr");
2026 #ifdef _LP64
2027   if (adr_type->is_ptr_to_narrowklass()) {
2028     assert(UseCompressedClassPointers, "no compressed klasses");
2029     Node* load_klass = gvn.transform(new LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
2030     return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
2031   }
2032 #endif
2033   assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
2034   return new LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered);
2035 }
2036 
2037 //------------------------------Value------------------------------------------
2038 const Type* LoadKlassNode::Value(PhaseGVN* phase) const {
2039   return klass_value_common(phase);
2040 }
2041 
2042 // In most cases, LoadKlassNode does not have the control input set. If the control
2043 // input is set, it must not be removed (by LoadNode::Ideal()).
2044 bool LoadKlassNode::can_remove_control() const {
2045   return false;
2046 }
2047 
2048 const Type* LoadNode::klass_value_common(PhaseGVN* phase) const {
2049   // Either input is TOP ==> the result is TOP
2050   const Type *t1 = phase->type( in(MemNode::Memory) );
2051   if (t1 == Type::TOP)  return Type::TOP;
2052   Node *adr = in(MemNode::Address);
2053   const Type *t2 = phase->type( adr );
2054   if (t2 == Type::TOP)  return Type::TOP;
2055   const TypePtr *tp = t2->is_ptr();
2056   if (TypePtr::above_centerline(tp->ptr()) ||
2057       tp->ptr() == TypePtr::Null)  return Type::TOP;
2058 
2059   // Return a more precise klass, if possible
2060   const TypeInstPtr *tinst = tp->isa_instptr();
2061   if (tinst != NULL) {
2062     ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
2063     int offset = tinst->offset();
2064     if (ik == phase->C->env()->Class_klass()
2065         && (offset == java_lang_Class::klass_offset_in_bytes() ||
2066             offset == java_lang_Class::array_klass_offset_in_bytes())) {
2067       // We are loading a special hidden field from a Class mirror object,
2068       // the field which points to the VM's Klass metaobject.
2069       ciType* t = tinst->java_mirror_type();
2070       // java_mirror_type returns non-null for compile-time Class constants.
2071       if (t != NULL) {
2072         // constant oop => constant klass
2073         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
2074           if (t->is_void()) {
2075             // We cannot create a void array.  Since void is a primitive type return null
2076             // klass.  Users of this result need to do a null check on the returned klass.
2077             return TypePtr::NULL_PTR;
2078           }
2079           return TypeKlassPtr::make(ciArrayKlass::make(t));
2080         }
2081         if (!t->is_klass()) {
2082           // a primitive Class (e.g., int.class) has NULL for a klass field
2083           return TypePtr::NULL_PTR;
2084         }
2085         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
2086         return TypeKlassPtr::make(t->as_klass());
2087       }
2088       // non-constant mirror, so we can't tell what's going on
2089     }
2090     if( !ik->is_loaded() )
2091       return _type;             // Bail out if not loaded
2092     if (offset == oopDesc::klass_offset_in_bytes()) {
2093       if (tinst->klass_is_exact()) {
2094         return TypeKlassPtr::make(ik);
2095       }
2096       // See if we can become precise: no subklasses and no interface
2097       // (Note:  We need to support verified interfaces.)
2098       if (!ik->is_interface() && !ik->has_subklass()) {
2099         //assert(!UseExactTypes, "this code should be useless with exact types");
2100         // Add a dependence; if any subclass added we need to recompile
2101         if (!ik->is_final()) {
2102           // %%% should use stronger assert_unique_concrete_subtype instead
2103           phase->C->dependencies()->assert_leaf_type(ik);
2104         }
2105         // Return precise klass
2106         return TypeKlassPtr::make(ik);
2107       }
2108 
2109       // Return root of possible klass
2110       return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
2111     }
2112   }
2113 
2114   // Check for loading klass from an array
2115   const TypeAryPtr *tary = tp->isa_aryptr();
2116   if( tary != NULL ) {
2117     ciKlass *tary_klass = tary->klass();
2118     if (tary_klass != NULL   // can be NULL when at BOTTOM or TOP
2119         && tary->offset() == oopDesc::klass_offset_in_bytes()) {
2120       if (tary->klass_is_exact()) {
2121         return TypeKlassPtr::make(tary_klass);
2122       }
2123       ciArrayKlass *ak = tary->klass()->as_array_klass();
2124       // If the klass is an object array, we defer the question to the
2125       // array component klass.
2126       if( ak->is_obj_array_klass() ) {
2127         assert( ak->is_loaded(), "" );
2128         ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
2129         if( base_k->is_loaded() && base_k->is_instance_klass() ) {
2130           ciInstanceKlass* ik = base_k->as_instance_klass();
2131           // See if we can become precise: no subklasses and no interface
2132           if (!ik->is_interface() && !ik->has_subklass()) {
2133             //assert(!UseExactTypes, "this code should be useless with exact types");
2134             // Add a dependence; if any subclass added we need to recompile
2135             if (!ik->is_final()) {
2136               phase->C->dependencies()->assert_leaf_type(ik);
2137             }
2138             // Return precise array klass
2139             return TypeKlassPtr::make(ak);
2140           }
2141         }
2142         return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
2143       } else {                  // Found a type-array?
2144         //assert(!UseExactTypes, "this code should be useless with exact types");
2145         assert( ak->is_type_array_klass(), "" );
2146         return TypeKlassPtr::make(ak); // These are always precise
2147       }
2148     }
2149   }
2150 
2151   // Check for loading klass from an array klass
2152   const TypeKlassPtr *tkls = tp->isa_klassptr();
2153   if (tkls != NULL && !StressReflectiveCode) {
2154     ciKlass* klass = tkls->klass();
2155     if( !klass->is_loaded() )
2156       return _type;             // Bail out if not loaded
2157     if( klass->is_obj_array_klass() &&
2158         tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
2159       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
2160       // // Always returning precise element type is incorrect,
2161       // // e.g., element type could be object and array may contain strings
2162       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
2163 
2164       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
2165       // according to the element type's subclassing.
2166       return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
2167     }
2168     if( klass->is_instance_klass() && tkls->klass_is_exact() &&
2169         tkls->offset() == in_bytes(Klass::super_offset())) {
2170       ciKlass* sup = klass->as_instance_klass()->super();
2171       // The field is Klass::_super.  Return its (constant) value.
2172       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
2173       return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
2174     }
2175   }
2176 
2177   // Bailout case
2178   return LoadNode::Value(phase);
2179 }
2180 
2181 //------------------------------Identity---------------------------------------
2182 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
2183 // Also feed through the klass in Allocate(...klass...)._klass.
2184 Node* LoadKlassNode::Identity(PhaseGVN* phase) {
2185   return klass_identity_common(phase);
2186 }
2187 
2188 Node* LoadNode::klass_identity_common(PhaseGVN* phase) {
2189   Node* x = LoadNode::Identity(phase);
2190   if (x != this)  return x;
2191 
2192   // Take apart the address into an oop and and offset.
2193   // Return 'this' if we cannot.
2194   Node*    adr    = in(MemNode::Address);
2195   intptr_t offset = 0;
2196   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2197   if (base == NULL)     return this;
2198   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
2199   if (toop == NULL)     return this;
2200 
2201   // We can fetch the klass directly through an AllocateNode.
2202   // This works even if the klass is not constant (clone or newArray).
2203   if (offset == oopDesc::klass_offset_in_bytes()) {
2204     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
2205     if (allocated_klass != NULL) {
2206       return allocated_klass;
2207     }
2208   }
2209 
2210   // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
2211   // See inline_native_Class_query for occurrences of these patterns.
2212   // Java Example:  x.getClass().isAssignableFrom(y)
2213   //
2214   // This improves reflective code, often making the Class
2215   // mirror go completely dead.  (Current exception:  Class
2216   // mirrors may appear in debug info, but we could clean them out by
2217   // introducing a new debug info operator for Klass.java_mirror).
2218 
2219   if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
2220       && offset == java_lang_Class::klass_offset_in_bytes()) {


2221     if (base->is_Load()) {
2222       Node* base2 = base->in(MemNode::Address);
2223       if (base2->is_Load()) { /* direct load of a load which is the oophandle */
2224         Node* adr2 = base2->in(MemNode::Address);
2225         const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2226         if (tkls != NULL && !tkls->empty()
2227             && (tkls->klass()->is_instance_klass() ||
2228               tkls->klass()->is_array_klass())
2229             && adr2->is_AddP()
2230            ) {
2231           int mirror_field = in_bytes(Klass::java_mirror_offset());
2232           if (tkls->offset() == mirror_field) {
2233             return adr2->in(AddPNode::Base);
2234           }
2235         }
2236       }
2237     }
2238   }
2239 
2240   return this;
2241 }
2242 
2243 
2244 //------------------------------Value------------------------------------------
2245 const Type* LoadNKlassNode::Value(PhaseGVN* phase) const {
2246   const Type *t = klass_value_common(phase);
2247   if (t == Type::TOP)
2248     return t;
2249 
2250   return t->make_narrowklass();
2251 }
2252 
2253 //------------------------------Identity---------------------------------------
2254 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
2255 // Also feed through the klass in Allocate(...klass...)._klass.
2256 Node* LoadNKlassNode::Identity(PhaseGVN* phase) {
2257   Node *x = klass_identity_common(phase);
2258 
2259   const Type *t = phase->type( x );
2260   if( t == Type::TOP ) return x;
2261   if( t->isa_narrowklass()) return x;
2262   assert (!t->isa_narrowoop(), "no narrow oop here");
2263 
2264   return phase->transform(new EncodePKlassNode(x, t->make_narrowklass()));
2265 }
2266 
2267 //------------------------------Value-----------------------------------------
2268 const Type* LoadRangeNode::Value(PhaseGVN* phase) const {
2269   // Either input is TOP ==> the result is TOP
2270   const Type *t1 = phase->type( in(MemNode::Memory) );
2271   if( t1 == Type::TOP ) return Type::TOP;
2272   Node *adr = in(MemNode::Address);
2273   const Type *t2 = phase->type( adr );
2274   if( t2 == Type::TOP ) return Type::TOP;
2275   const TypePtr *tp = t2->is_ptr();
2276   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
2277   const TypeAryPtr *tap = tp->isa_aryptr();
2278   if( !tap ) return _type;
2279   return tap->size();
2280 }
2281 
2282 //-------------------------------Ideal---------------------------------------
2283 // Feed through the length in AllocateArray(...length...)._length.
2284 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2285   Node* p = MemNode::Ideal_common(phase, can_reshape);
2286   if (p)  return (p == NodeSentinel) ? NULL : p;
2287 
2288   // Take apart the address into an oop and and offset.
2289   // Return 'this' if we cannot.
2290   Node*    adr    = in(MemNode::Address);
2291   intptr_t offset = 0;
2292   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase,  offset);
2293   if (base == NULL)     return NULL;
2294   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2295   if (tary == NULL)     return NULL;
2296 
2297   // We can fetch the length directly through an AllocateArrayNode.
2298   // This works even if the length is not constant (clone or newArray).
2299   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2300     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2301     if (alloc != NULL) {
2302       Node* allocated_length = alloc->Ideal_length();
2303       Node* len = alloc->make_ideal_length(tary, phase);
2304       if (allocated_length != len) {
2305         // New CastII improves on this.
2306         return len;
2307       }
2308     }
2309   }
2310 
2311   return NULL;
2312 }
2313 
2314 //------------------------------Identity---------------------------------------
2315 // Feed through the length in AllocateArray(...length...)._length.
2316 Node* LoadRangeNode::Identity(PhaseGVN* phase) {
2317   Node* x = LoadINode::Identity(phase);
2318   if (x != this)  return x;
2319 
2320   // Take apart the address into an oop and and offset.
2321   // Return 'this' if we cannot.
2322   Node*    adr    = in(MemNode::Address);
2323   intptr_t offset = 0;
2324   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2325   if (base == NULL)     return this;
2326   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2327   if (tary == NULL)     return this;
2328 
2329   // We can fetch the length directly through an AllocateArrayNode.
2330   // This works even if the length is not constant (clone or newArray).
2331   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2332     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2333     if (alloc != NULL) {
2334       Node* allocated_length = alloc->Ideal_length();
2335       // Do not allow make_ideal_length to allocate a CastII node.
2336       Node* len = alloc->make_ideal_length(tary, phase, false);
2337       if (allocated_length == len) {
2338         // Return allocated_length only if it would not be improved by a CastII.
2339         return allocated_length;
2340       }
2341     }
2342   }
2343 
2344   return this;
2345 
2346 }
2347 
2348 //=============================================================================
2349 //---------------------------StoreNode::make-----------------------------------
2350 // Polymorphic factory method:
2351 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo) {
2352   assert((mo == unordered || mo == release), "unexpected");
2353   Compile* C = gvn.C;
2354   assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
2355          ctl != NULL, "raw memory operations should have control edge");
2356 
2357   switch (bt) {
2358   case T_BOOLEAN: val = gvn.transform(new AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case
2359   case T_BYTE:    return new StoreBNode(ctl, mem, adr, adr_type, val, mo);
2360   case T_INT:     return new StoreINode(ctl, mem, adr, adr_type, val, mo);
2361   case T_CHAR:
2362   case T_SHORT:   return new StoreCNode(ctl, mem, adr, adr_type, val, mo);
2363   case T_LONG:    return new StoreLNode(ctl, mem, adr, adr_type, val, mo);
2364   case T_FLOAT:   return new StoreFNode(ctl, mem, adr, adr_type, val, mo);
2365   case T_DOUBLE:  return new StoreDNode(ctl, mem, adr, adr_type, val, mo);
2366   case T_METADATA:
2367   case T_ADDRESS:
2368   case T_OBJECT:
2369 #ifdef _LP64
2370     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2371       val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop()));
2372       return new StoreNNode(ctl, mem, adr, adr_type, val, mo);
2373     } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
2374                (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
2375                 adr->bottom_type()->isa_rawptr())) {
2376       val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
2377       return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
2378     }
2379 #endif
2380     {
2381       return new StorePNode(ctl, mem, adr, adr_type, val, mo);
2382     }
2383   default:
2384     ShouldNotReachHere();
2385     return (StoreNode*)NULL;
2386   }
2387 }
2388 
2389 StoreLNode* StoreLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2390   bool require_atomic = true;
2391   return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2392 }
2393 
2394 StoreDNode* StoreDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2395   bool require_atomic = true;
2396   return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2397 }
2398 
2399 
2400 //--------------------------bottom_type----------------------------------------
2401 const Type *StoreNode::bottom_type() const {
2402   return Type::MEMORY;
2403 }
2404 
2405 //------------------------------hash-------------------------------------------
2406 uint StoreNode::hash() const {
2407   // unroll addition of interesting fields
2408   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
2409 
2410   // Since they are not commoned, do not hash them:
2411   return NO_HASH;
2412 }
2413 
2414 //------------------------------Ideal------------------------------------------
2415 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
2416 // When a store immediately follows a relevant allocation/initialization,
2417 // try to capture it into the initialization, or hoist it above.
2418 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2419   Node* p = MemNode::Ideal_common(phase, can_reshape);
2420   if (p)  return (p == NodeSentinel) ? NULL : p;
2421 
2422   Node* mem     = in(MemNode::Memory);
2423   Node* address = in(MemNode::Address);
2424   // Back-to-back stores to same address?  Fold em up.  Generally
2425   // unsafe if I have intervening uses...  Also disallowed for StoreCM
2426   // since they must follow each StoreP operation.  Redundant StoreCMs
2427   // are eliminated just before matching in final_graph_reshape.
2428   {
2429     Node* st = mem;
2430     // If Store 'st' has more than one use, we cannot fold 'st' away.
2431     // For example, 'st' might be the final state at a conditional
2432     // return.  Or, 'st' might be used by some node which is live at
2433     // the same time 'st' is live, which might be unschedulable.  So,
2434     // require exactly ONE user until such time as we clone 'mem' for
2435     // each of 'mem's uses (thus making the exactly-1-user-rule hold
2436     // true).
2437     while (st->is_Store() && st->outcnt() == 1 && st->Opcode() != Op_StoreCM) {
2438       // Looking at a dead closed cycle of memory?
2439       assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
2440       assert(Opcode() == st->Opcode() ||
2441              st->Opcode() == Op_StoreVector ||
2442              Opcode() == Op_StoreVector ||
2443              phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw ||
2444              (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode
2445              (Opcode() == Op_StoreI && st->Opcode() == Op_StoreL) || // initialization by arraycopy
2446              (is_mismatched_access() || st->as_Store()->is_mismatched_access()),
2447              "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]);
2448 
2449       if (st->in(MemNode::Address)->eqv_uncast(address) &&
2450           st->as_Store()->memory_size() <= this->memory_size()) {
2451         Node* use = st->raw_out(0);
2452         phase->igvn_rehash_node_delayed(use);
2453         if (can_reshape) {
2454           use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase->is_IterGVN());
2455         } else {
2456           // It's OK to do this in the parser, since DU info is always accurate,
2457           // and the parser always refers to nodes via SafePointNode maps.
2458           use->set_req(MemNode::Memory, st->in(MemNode::Memory));
2459         }
2460         return this;
2461       }
2462       st = st->in(MemNode::Memory);
2463     }
2464   }
2465 
2466 
2467   // Capture an unaliased, unconditional, simple store into an initializer.
2468   // Or, if it is independent of the allocation, hoist it above the allocation.
2469   if (ReduceFieldZeroing && /*can_reshape &&*/
2470       mem->is_Proj() && mem->in(0)->is_Initialize()) {
2471     InitializeNode* init = mem->in(0)->as_Initialize();
2472     intptr_t offset = init->can_capture_store(this, phase, can_reshape);
2473     if (offset > 0) {
2474       Node* moved = init->capture_store(this, offset, phase, can_reshape);
2475       // If the InitializeNode captured me, it made a raw copy of me,
2476       // and I need to disappear.
2477       if (moved != NULL) {
2478         // %%% hack to ensure that Ideal returns a new node:
2479         mem = MergeMemNode::make(mem);
2480         return mem;             // fold me away
2481       }
2482     }
2483   }
2484 
2485   return NULL;                  // No further progress
2486 }
2487 
2488 //------------------------------Value-----------------------------------------
2489 const Type* StoreNode::Value(PhaseGVN* phase) const {
2490   // Either input is TOP ==> the result is TOP
2491   const Type *t1 = phase->type( in(MemNode::Memory) );
2492   if( t1 == Type::TOP ) return Type::TOP;
2493   const Type *t2 = phase->type( in(MemNode::Address) );
2494   if( t2 == Type::TOP ) return Type::TOP;
2495   const Type *t3 = phase->type( in(MemNode::ValueIn) );
2496   if( t3 == Type::TOP ) return Type::TOP;
2497   return Type::MEMORY;
2498 }
2499 
2500 //------------------------------Identity---------------------------------------
2501 // Remove redundant stores:
2502 //   Store(m, p, Load(m, p)) changes to m.
2503 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
2504 Node* StoreNode::Identity(PhaseGVN* phase) {
2505   Node* mem = in(MemNode::Memory);
2506   Node* adr = in(MemNode::Address);
2507   Node* val = in(MemNode::ValueIn);
2508 
2509   // Load then Store?  Then the Store is useless
2510   if (val->is_Load() &&
2511       val->in(MemNode::Address)->eqv_uncast(adr) &&
2512       val->in(MemNode::Memory )->eqv_uncast(mem) &&
2513       val->as_Load()->store_Opcode() == Opcode()) {
2514     return mem;
2515   }
2516 
2517   // Two stores in a row of the same value?
2518   if (mem->is_Store() &&
2519       mem->in(MemNode::Address)->eqv_uncast(adr) &&
2520       mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
2521       mem->Opcode() == Opcode()) {
2522     return mem;
2523   }
2524 
2525   // Store of zero anywhere into a freshly-allocated object?
2526   // Then the store is useless.
2527   // (It must already have been captured by the InitializeNode.)
2528   if (ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
2529     // a newly allocated object is already all-zeroes everywhere
2530     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
2531       return mem;
2532     }
2533 
2534     // the store may also apply to zero-bits in an earlier object
2535     Node* prev_mem = find_previous_store(phase);
2536     // Steps (a), (b):  Walk past independent stores to find an exact match.
2537     if (prev_mem != NULL) {
2538       Node* prev_val = can_see_stored_value(prev_mem, phase);
2539       if (prev_val != NULL && phase->eqv(prev_val, val)) {
2540         // prev_val and val might differ by a cast; it would be good
2541         // to keep the more informative of the two.
2542         return mem;
2543       }
2544     }
2545   }
2546 
2547   return this;
2548 }
2549 
2550 //------------------------------match_edge-------------------------------------
2551 // Do we Match on this edge index or not?  Match only memory & value
2552 uint StoreNode::match_edge(uint idx) const {
2553   return idx == MemNode::Address || idx == MemNode::ValueIn;
2554 }
2555 
2556 //------------------------------cmp--------------------------------------------
2557 // Do not common stores up together.  They generally have to be split
2558 // back up anyways, so do not bother.
2559 uint StoreNode::cmp( const Node &n ) const {
2560   return (&n == this);          // Always fail except on self
2561 }
2562 
2563 //------------------------------Ideal_masked_input-----------------------------
2564 // Check for a useless mask before a partial-word store
2565 // (StoreB ... (AndI valIn conIa) )
2566 // If (conIa & mask == mask) this simplifies to
2567 // (StoreB ... (valIn) )
2568 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
2569   Node *val = in(MemNode::ValueIn);
2570   if( val->Opcode() == Op_AndI ) {
2571     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2572     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
2573       set_req(MemNode::ValueIn, val->in(1));
2574       return this;
2575     }
2576   }
2577   return NULL;
2578 }
2579 
2580 
2581 //------------------------------Ideal_sign_extended_input----------------------
2582 // Check for useless sign-extension before a partial-word store
2583 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
2584 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
2585 // (StoreB ... (valIn) )
2586 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
2587   Node *val = in(MemNode::ValueIn);
2588   if( val->Opcode() == Op_RShiftI ) {
2589     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2590     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
2591       Node *shl = val->in(1);
2592       if( shl->Opcode() == Op_LShiftI ) {
2593         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
2594         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
2595           set_req(MemNode::ValueIn, shl->in(1));
2596           return this;
2597         }
2598       }
2599     }
2600   }
2601   return NULL;
2602 }
2603 
2604 //------------------------------value_never_loaded-----------------------------------
2605 // Determine whether there are any possible loads of the value stored.
2606 // For simplicity, we actually check if there are any loads from the
2607 // address stored to, not just for loads of the value stored by this node.
2608 //
2609 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
2610   Node *adr = in(Address);
2611   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
2612   if (adr_oop == NULL)
2613     return false;
2614   if (!adr_oop->is_known_instance_field())
2615     return false; // if not a distinct instance, there may be aliases of the address
2616   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
2617     Node *use = adr->fast_out(i);
2618     if (use->is_Load() || use->is_LoadStore()) {
2619       return false;
2620     }
2621   }
2622   return true;
2623 }
2624 
2625 //=============================================================================
2626 //------------------------------Ideal------------------------------------------
2627 // If the store is from an AND mask that leaves the low bits untouched, then
2628 // we can skip the AND operation.  If the store is from a sign-extension
2629 // (a left shift, then right shift) we can skip both.
2630 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
2631   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
2632   if( progress != NULL ) return progress;
2633 
2634   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
2635   if( progress != NULL ) return progress;
2636 
2637   // Finally check the default case
2638   return StoreNode::Ideal(phase, can_reshape);
2639 }
2640 
2641 //=============================================================================
2642 //------------------------------Ideal------------------------------------------
2643 // If the store is from an AND mask that leaves the low bits untouched, then
2644 // we can skip the AND operation
2645 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
2646   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
2647   if( progress != NULL ) return progress;
2648 
2649   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
2650   if( progress != NULL ) return progress;
2651 
2652   // Finally check the default case
2653   return StoreNode::Ideal(phase, can_reshape);
2654 }
2655 
2656 //=============================================================================
2657 //------------------------------Identity---------------------------------------
2658 Node* StoreCMNode::Identity(PhaseGVN* phase) {
2659   // No need to card mark when storing a null ptr
2660   Node* my_store = in(MemNode::OopStore);
2661   if (my_store->is_Store()) {
2662     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
2663     if( t1 == TypePtr::NULL_PTR ) {
2664       return in(MemNode::Memory);
2665     }
2666   }
2667   return this;
2668 }
2669 
2670 //=============================================================================
2671 //------------------------------Ideal---------------------------------------
2672 Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
2673   Node* progress = StoreNode::Ideal(phase, can_reshape);
2674   if (progress != NULL) return progress;
2675 
2676   Node* my_store = in(MemNode::OopStore);
2677   if (my_store->is_MergeMem()) {
2678     Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
2679     set_req(MemNode::OopStore, mem);
2680     return this;
2681   }
2682 
2683   return NULL;
2684 }
2685 
2686 //------------------------------Value-----------------------------------------
2687 const Type* StoreCMNode::Value(PhaseGVN* phase) const {
2688   // Either input is TOP ==> the result is TOP
2689   const Type *t = phase->type( in(MemNode::Memory) );
2690   if( t == Type::TOP ) return Type::TOP;
2691   t = phase->type( in(MemNode::Address) );
2692   if( t == Type::TOP ) return Type::TOP;
2693   t = phase->type( in(MemNode::ValueIn) );
2694   if( t == Type::TOP ) return Type::TOP;
2695   // If extra input is TOP ==> the result is TOP
2696   t = phase->type( in(MemNode::OopStore) );
2697   if( t == Type::TOP ) return Type::TOP;
2698 
2699   return StoreNode::Value( phase );
2700 }
2701 
2702 
2703 //=============================================================================
2704 //----------------------------------SCMemProjNode------------------------------
2705 const Type* SCMemProjNode::Value(PhaseGVN* phase) const
2706 {
2707   return bottom_type();
2708 }
2709 
2710 //=============================================================================
2711 //----------------------------------LoadStoreNode------------------------------
2712 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
2713   : Node(required),
2714     _type(rt),
2715     _adr_type(at)
2716 {
2717   init_req(MemNode::Control, c  );
2718   init_req(MemNode::Memory , mem);
2719   init_req(MemNode::Address, adr);
2720   init_req(MemNode::ValueIn, val);
2721   init_class_id(Class_LoadStore);
2722 }
2723 
2724 uint LoadStoreNode::ideal_reg() const {
2725   return _type->ideal_reg();
2726 }
2727 
2728 bool LoadStoreNode::result_not_used() const {
2729   for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
2730     Node *x = fast_out(i);
2731     if (x->Opcode() == Op_SCMemProj) continue;
2732     return false;
2733   }
2734   return true;
2735 }
2736 
2737 uint LoadStoreNode::size_of() const { return sizeof(*this); }
2738 
2739 //=============================================================================
2740 //----------------------------------LoadStoreConditionalNode--------------------
2741 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, NULL, TypeInt::BOOL, 5) {
2742   init_req(ExpectedIn, ex );
2743 }
2744 
2745 //=============================================================================
2746 //-------------------------------adr_type--------------------------------------
2747 const TypePtr* ClearArrayNode::adr_type() const {
2748   Node *adr = in(3);
2749   if (adr == NULL)  return NULL; // node is dead
2750   return MemNode::calculate_adr_type(adr->bottom_type());
2751 }
2752 
2753 //------------------------------match_edge-------------------------------------
2754 // Do we Match on this edge index or not?  Do not match memory
2755 uint ClearArrayNode::match_edge(uint idx) const {
2756   return idx > 1;
2757 }
2758 
2759 //------------------------------Identity---------------------------------------
2760 // Clearing a zero length array does nothing
2761 Node* ClearArrayNode::Identity(PhaseGVN* phase) {
2762   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
2763 }
2764 
2765 //------------------------------Idealize---------------------------------------
2766 // Clearing a short array is faster with stores
2767 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2768   // Already know this is a large node, do not try to ideal it
2769   if (!IdealizeClearArrayNode || _is_large) return NULL;
2770 
2771   const int unit = BytesPerLong;
2772   const TypeX* t = phase->type(in(2))->isa_intptr_t();
2773   if (!t)  return NULL;
2774   if (!t->is_con())  return NULL;
2775   intptr_t raw_count = t->get_con();
2776   intptr_t size = raw_count;
2777   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
2778   // Clearing nothing uses the Identity call.
2779   // Negative clears are possible on dead ClearArrays
2780   // (see jck test stmt114.stmt11402.val).
2781   if (size <= 0 || size % unit != 0)  return NULL;
2782   intptr_t count = size / unit;
2783   // Length too long; communicate this to matchers and assemblers.
2784   // Assemblers are responsible to produce fast hardware clears for it.
2785   if (size > InitArrayShortSize) {
2786     return new ClearArrayNode(in(0), in(1), in(2), in(3), true);
2787   }
2788   Node *mem = in(1);
2789   if( phase->type(mem)==Type::TOP ) return NULL;
2790   Node *adr = in(3);
2791   const Type* at = phase->type(adr);
2792   if( at==Type::TOP ) return NULL;
2793   const TypePtr* atp = at->isa_ptr();
2794   // adjust atp to be the correct array element address type
2795   if (atp == NULL)  atp = TypePtr::BOTTOM;
2796   else              atp = atp->add_offset(Type::OffsetBot);
2797   // Get base for derived pointer purposes
2798   if( adr->Opcode() != Op_AddP ) Unimplemented();
2799   Node *base = adr->in(1);
2800 
2801   Node *zero = phase->makecon(TypeLong::ZERO);
2802   Node *off  = phase->MakeConX(BytesPerLong);
2803   mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
2804   count--;
2805   while( count-- ) {
2806     mem = phase->transform(mem);
2807     adr = phase->transform(new AddPNode(base,adr,off));
2808     mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
2809   }
2810   return mem;
2811 }
2812 
2813 //----------------------------step_through----------------------------------
2814 // Return allocation input memory edge if it is different instance
2815 // or itself if it is the one we are looking for.
2816 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseTransform* phase) {
2817   Node* n = *np;
2818   assert(n->is_ClearArray(), "sanity");
2819   intptr_t offset;
2820   AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
2821   // This method is called only before Allocate nodes are expanded
2822   // during macro nodes expansion. Before that ClearArray nodes are
2823   // only generated in PhaseMacroExpand::generate_arraycopy() (before
2824   // Allocate nodes are expanded) which follows allocations.
2825   assert(alloc != NULL, "should have allocation");
2826   if (alloc->_idx == instance_id) {
2827     // Can not bypass initialization of the instance we are looking for.
2828     return false;
2829   }
2830   // Otherwise skip it.
2831   InitializeNode* init = alloc->initialization();
2832   if (init != NULL)
2833     *np = init->in(TypeFunc::Memory);
2834   else
2835     *np = alloc->in(TypeFunc::Memory);
2836   return true;
2837 }
2838 
2839 //----------------------------clear_memory-------------------------------------
2840 // Generate code to initialize object storage to zero.
2841 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2842                                    intptr_t start_offset,
2843                                    Node* end_offset,
2844                                    PhaseGVN* phase) {
2845   intptr_t offset = start_offset;
2846 
2847   int unit = BytesPerLong;
2848   if ((offset % unit) != 0) {
2849     Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset));
2850     adr = phase->transform(adr);
2851     const TypePtr* atp = TypeRawPtr::BOTTOM;
2852     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
2853     mem = phase->transform(mem);
2854     offset += BytesPerInt;
2855   }
2856   assert((offset % unit) == 0, "");
2857 
2858   // Initialize the remaining stuff, if any, with a ClearArray.
2859   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
2860 }
2861 
2862 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2863                                    Node* start_offset,
2864                                    Node* end_offset,
2865                                    PhaseGVN* phase) {
2866   if (start_offset == end_offset) {
2867     // nothing to do
2868     return mem;
2869   }
2870 
2871   int unit = BytesPerLong;
2872   Node* zbase = start_offset;
2873   Node* zend  = end_offset;
2874 
2875   // Scale to the unit required by the CPU:
2876   if (!Matcher::init_array_count_is_in_bytes) {
2877     Node* shift = phase->intcon(exact_log2(unit));
2878     zbase = phase->transform(new URShiftXNode(zbase, shift) );
2879     zend  = phase->transform(new URShiftXNode(zend,  shift) );
2880   }
2881 
2882   // Bulk clear double-words
2883   Node* zsize = phase->transform(new SubXNode(zend, zbase) );
2884   Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) );
2885   mem = new ClearArrayNode(ctl, mem, zsize, adr, false);
2886   return phase->transform(mem);
2887 }
2888 
2889 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2890                                    intptr_t start_offset,
2891                                    intptr_t end_offset,
2892                                    PhaseGVN* phase) {
2893   if (start_offset == end_offset) {
2894     // nothing to do
2895     return mem;
2896   }
2897 
2898   assert((end_offset % BytesPerInt) == 0, "odd end offset");
2899   intptr_t done_offset = end_offset;
2900   if ((done_offset % BytesPerLong) != 0) {
2901     done_offset -= BytesPerInt;
2902   }
2903   if (done_offset > start_offset) {
2904     mem = clear_memory(ctl, mem, dest,
2905                        start_offset, phase->MakeConX(done_offset), phase);
2906   }
2907   if (done_offset < end_offset) { // emit the final 32-bit store
2908     Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset));
2909     adr = phase->transform(adr);
2910     const TypePtr* atp = TypeRawPtr::BOTTOM;
2911     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
2912     mem = phase->transform(mem);
2913     done_offset += BytesPerInt;
2914   }
2915   assert(done_offset == end_offset, "");
2916   return mem;
2917 }
2918 
2919 //=============================================================================
2920 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
2921   : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
2922     _adr_type(C->get_adr_type(alias_idx))
2923 {
2924   init_class_id(Class_MemBar);
2925   Node* top = C->top();
2926   init_req(TypeFunc::I_O,top);
2927   init_req(TypeFunc::FramePtr,top);
2928   init_req(TypeFunc::ReturnAdr,top);
2929   if (precedent != NULL)
2930     init_req(TypeFunc::Parms, precedent);
2931 }
2932 
2933 //------------------------------cmp--------------------------------------------
2934 uint MemBarNode::hash() const { return NO_HASH; }
2935 uint MemBarNode::cmp( const Node &n ) const {
2936   return (&n == this);          // Always fail except on self
2937 }
2938 
2939 //------------------------------make-------------------------------------------
2940 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
2941   switch (opcode) {
2942   case Op_MemBarAcquire:     return new MemBarAcquireNode(C, atp, pn);
2943   case Op_LoadFence:         return new LoadFenceNode(C, atp, pn);
2944   case Op_MemBarRelease:     return new MemBarReleaseNode(C, atp, pn);
2945   case Op_StoreFence:        return new StoreFenceNode(C, atp, pn);
2946   case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn);
2947   case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn);
2948   case Op_MemBarVolatile:    return new MemBarVolatileNode(C, atp, pn);
2949   case Op_MemBarCPUOrder:    return new MemBarCPUOrderNode(C, atp, pn);
2950   case Op_OnSpinWait:        return new OnSpinWaitNode(C, atp, pn);
2951   case Op_Initialize:        return new InitializeNode(C, atp, pn);
2952   case Op_MemBarStoreStore:  return new MemBarStoreStoreNode(C, atp, pn);
2953   default: ShouldNotReachHere(); return NULL;
2954   }
2955 }
2956 
2957 //------------------------------Ideal------------------------------------------
2958 // Return a node which is more "ideal" than the current node.  Strip out
2959 // control copies
2960 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2961   if (remove_dead_region(phase, can_reshape)) return this;
2962   // Don't bother trying to transform a dead node
2963   if (in(0) && in(0)->is_top()) {
2964     return NULL;
2965   }
2966 
2967   bool progress = false;
2968   // Eliminate volatile MemBars for scalar replaced objects.
2969   if (can_reshape && req() == (Precedent+1)) {
2970     bool eliminate = false;
2971     int opc = Opcode();
2972     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
2973       // Volatile field loads and stores.
2974       Node* my_mem = in(MemBarNode::Precedent);
2975       // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
2976       if ((my_mem != NULL) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
2977         // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
2978         // replace this Precedent (decodeN) with the Load instead.
2979         if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1))  {
2980           Node* load_node = my_mem->in(1);
2981           set_req(MemBarNode::Precedent, load_node);
2982           phase->is_IterGVN()->_worklist.push(my_mem);
2983           my_mem = load_node;
2984         } else {
2985           assert(my_mem->unique_out() == this, "sanity");
2986           del_req(Precedent);
2987           phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
2988           my_mem = NULL;
2989         }
2990         progress = true;
2991       }
2992       if (my_mem != NULL && my_mem->is_Mem()) {
2993         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
2994         // Check for scalar replaced object reference.
2995         if( t_oop != NULL && t_oop->is_known_instance_field() &&
2996             t_oop->offset() != Type::OffsetBot &&
2997             t_oop->offset() != Type::OffsetTop) {
2998           eliminate = true;
2999         }
3000       }
3001     } else if (opc == Op_MemBarRelease) {
3002       // Final field stores.
3003       Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent), phase);
3004       if ((alloc != NULL) && alloc->is_Allocate() &&
3005           alloc->as_Allocate()->does_not_escape_thread()) {
3006         // The allocated object does not escape.
3007         eliminate = true;
3008       }
3009     }
3010     if (eliminate) {
3011       // Replace MemBar projections by its inputs.
3012       PhaseIterGVN* igvn = phase->is_IterGVN();
3013       igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
3014       igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
3015       // Must return either the original node (now dead) or a new node
3016       // (Do not return a top here, since that would break the uniqueness of top.)
3017       return new ConINode(TypeInt::ZERO);
3018     }
3019   }
3020   return progress ? this : NULL;
3021 }
3022 
3023 //------------------------------Value------------------------------------------
3024 const Type* MemBarNode::Value(PhaseGVN* phase) const {
3025   if( !in(0) ) return Type::TOP;
3026   if( phase->type(in(0)) == Type::TOP )
3027     return Type::TOP;
3028   return TypeTuple::MEMBAR;
3029 }
3030 
3031 //------------------------------match------------------------------------------
3032 // Construct projections for memory.
3033 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
3034   switch (proj->_con) {
3035   case TypeFunc::Control:
3036   case TypeFunc::Memory:
3037     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
3038   }
3039   ShouldNotReachHere();
3040   return NULL;
3041 }
3042 
3043 //===========================InitializeNode====================================
3044 // SUMMARY:
3045 // This node acts as a memory barrier on raw memory, after some raw stores.
3046 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
3047 // The Initialize can 'capture' suitably constrained stores as raw inits.
3048 // It can coalesce related raw stores into larger units (called 'tiles').
3049 // It can avoid zeroing new storage for memory units which have raw inits.
3050 // At macro-expansion, it is marked 'complete', and does not optimize further.
3051 //
3052 // EXAMPLE:
3053 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
3054 //   ctl = incoming control; mem* = incoming memory
3055 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
3056 // First allocate uninitialized memory and fill in the header:
3057 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
3058 //   ctl := alloc.Control; mem* := alloc.Memory*
3059 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
3060 // Then initialize to zero the non-header parts of the raw memory block:
3061 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
3062 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
3063 // After the initialize node executes, the object is ready for service:
3064 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
3065 // Suppose its body is immediately initialized as {1,2}:
3066 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3067 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3068 //   mem.SLICE(#short[*]) := store2
3069 //
3070 // DETAILS:
3071 // An InitializeNode collects and isolates object initialization after
3072 // an AllocateNode and before the next possible safepoint.  As a
3073 // memory barrier (MemBarNode), it keeps critical stores from drifting
3074 // down past any safepoint or any publication of the allocation.
3075 // Before this barrier, a newly-allocated object may have uninitialized bits.
3076 // After this barrier, it may be treated as a real oop, and GC is allowed.
3077 //
3078 // The semantics of the InitializeNode include an implicit zeroing of
3079 // the new object from object header to the end of the object.
3080 // (The object header and end are determined by the AllocateNode.)
3081 //
3082 // Certain stores may be added as direct inputs to the InitializeNode.
3083 // These stores must update raw memory, and they must be to addresses
3084 // derived from the raw address produced by AllocateNode, and with
3085 // a constant offset.  They must be ordered by increasing offset.
3086 // The first one is at in(RawStores), the last at in(req()-1).
3087 // Unlike most memory operations, they are not linked in a chain,
3088 // but are displayed in parallel as users of the rawmem output of
3089 // the allocation.
3090 //
3091 // (See comments in InitializeNode::capture_store, which continue
3092 // the example given above.)
3093 //
3094 // When the associated Allocate is macro-expanded, the InitializeNode
3095 // may be rewritten to optimize collected stores.  A ClearArrayNode
3096 // may also be created at that point to represent any required zeroing.
3097 // The InitializeNode is then marked 'complete', prohibiting further
3098 // capturing of nearby memory operations.
3099 //
3100 // During macro-expansion, all captured initializations which store
3101 // constant values of 32 bits or smaller are coalesced (if advantageous)
3102 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
3103 // initialized in fewer memory operations.  Memory words which are
3104 // covered by neither tiles nor non-constant stores are pre-zeroed
3105 // by explicit stores of zero.  (The code shape happens to do all
3106 // zeroing first, then all other stores, with both sequences occurring
3107 // in order of ascending offsets.)
3108 //
3109 // Alternatively, code may be inserted between an AllocateNode and its
3110 // InitializeNode, to perform arbitrary initialization of the new object.
3111 // E.g., the object copying intrinsics insert complex data transfers here.
3112 // The initialization must then be marked as 'complete' disable the
3113 // built-in zeroing semantics and the collection of initializing stores.
3114 //
3115 // While an InitializeNode is incomplete, reads from the memory state
3116 // produced by it are optimizable if they match the control edge and
3117 // new oop address associated with the allocation/initialization.
3118 // They return a stored value (if the offset matches) or else zero.
3119 // A write to the memory state, if it matches control and address,
3120 // and if it is to a constant offset, may be 'captured' by the
3121 // InitializeNode.  It is cloned as a raw memory operation and rewired
3122 // inside the initialization, to the raw oop produced by the allocation.
3123 // Operations on addresses which are provably distinct (e.g., to
3124 // other AllocateNodes) are allowed to bypass the initialization.
3125 //
3126 // The effect of all this is to consolidate object initialization
3127 // (both arrays and non-arrays, both piecewise and bulk) into a
3128 // single location, where it can be optimized as a unit.
3129 //
3130 // Only stores with an offset less than TrackedInitializationLimit words
3131 // will be considered for capture by an InitializeNode.  This puts a
3132 // reasonable limit on the complexity of optimized initializations.
3133 
3134 //---------------------------InitializeNode------------------------------------
3135 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
3136   : _is_complete(Incomplete), _does_not_escape(false),
3137     MemBarNode(C, adr_type, rawoop)
3138 {
3139   init_class_id(Class_Initialize);
3140 
3141   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
3142   assert(in(RawAddress) == rawoop, "proper init");
3143   // Note:  allocation() can be NULL, for secondary initialization barriers
3144 }
3145 
3146 // Since this node is not matched, it will be processed by the
3147 // register allocator.  Declare that there are no constraints
3148 // on the allocation of the RawAddress edge.
3149 const RegMask &InitializeNode::in_RegMask(uint idx) const {
3150   // This edge should be set to top, by the set_complete.  But be conservative.
3151   if (idx == InitializeNode::RawAddress)
3152     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
3153   return RegMask::Empty;
3154 }
3155 
3156 Node* InitializeNode::memory(uint alias_idx) {
3157   Node* mem = in(Memory);
3158   if (mem->is_MergeMem()) {
3159     return mem->as_MergeMem()->memory_at(alias_idx);
3160   } else {
3161     // incoming raw memory is not split
3162     return mem;
3163   }
3164 }
3165 
3166 bool InitializeNode::is_non_zero() {
3167   if (is_complete())  return false;
3168   remove_extra_zeroes();
3169   return (req() > RawStores);
3170 }
3171 
3172 void InitializeNode::set_complete(PhaseGVN* phase) {
3173   assert(!is_complete(), "caller responsibility");
3174   _is_complete = Complete;
3175 
3176   // After this node is complete, it contains a bunch of
3177   // raw-memory initializations.  There is no need for
3178   // it to have anything to do with non-raw memory effects.
3179   // Therefore, tell all non-raw users to re-optimize themselves,
3180   // after skipping the memory effects of this initialization.
3181   PhaseIterGVN* igvn = phase->is_IterGVN();
3182   if (igvn)  igvn->add_users_to_worklist(this);
3183 }
3184 
3185 // convenience function
3186 // return false if the init contains any stores already
3187 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
3188   InitializeNode* init = initialization();
3189   if (init == NULL || init->is_complete())  return false;
3190   init->remove_extra_zeroes();
3191   // for now, if this allocation has already collected any inits, bail:
3192   if (init->is_non_zero())  return false;
3193   init->set_complete(phase);
3194   return true;
3195 }
3196 
3197 void InitializeNode::remove_extra_zeroes() {
3198   if (req() == RawStores)  return;
3199   Node* zmem = zero_memory();
3200   uint fill = RawStores;
3201   for (uint i = fill; i < req(); i++) {
3202     Node* n = in(i);
3203     if (n->is_top() || n == zmem)  continue;  // skip
3204     if (fill < i)  set_req(fill, n);          // compact
3205     ++fill;
3206   }
3207   // delete any empty spaces created:
3208   while (fill < req()) {
3209     del_req(fill);
3210   }
3211 }
3212 
3213 // Helper for remembering which stores go with which offsets.
3214 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
3215   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
3216   intptr_t offset = -1;
3217   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
3218                                                phase, offset);
3219   if (base == NULL)     return -1;  // something is dead,
3220   if (offset < 0)       return -1;  //        dead, dead
3221   return offset;
3222 }
3223 
3224 // Helper for proving that an initialization expression is
3225 // "simple enough" to be folded into an object initialization.
3226 // Attempts to prove that a store's initial value 'n' can be captured
3227 // within the initialization without creating a vicious cycle, such as:
3228 //     { Foo p = new Foo(); p.next = p; }
3229 // True for constants and parameters and small combinations thereof.
3230 bool InitializeNode::detect_init_independence(Node* n, int& count) {
3231   if (n == NULL)      return true;   // (can this really happen?)
3232   if (n->is_Proj())   n = n->in(0);
3233   if (n == this)      return false;  // found a cycle
3234   if (n->is_Con())    return true;
3235   if (n->is_Start())  return true;   // params, etc., are OK
3236   if (n->is_Root())   return true;   // even better
3237 
3238   Node* ctl = n->in(0);
3239   if (ctl != NULL && !ctl->is_top()) {
3240     if (ctl->is_Proj())  ctl = ctl->in(0);
3241     if (ctl == this)  return false;
3242 
3243     // If we already know that the enclosing memory op is pinned right after
3244     // the init, then any control flow that the store has picked up
3245     // must have preceded the init, or else be equal to the init.
3246     // Even after loop optimizations (which might change control edges)
3247     // a store is never pinned *before* the availability of its inputs.
3248     if (!MemNode::all_controls_dominate(n, this))
3249       return false;                  // failed to prove a good control
3250   }
3251 
3252   // Check data edges for possible dependencies on 'this'.
3253   if ((count += 1) > 20)  return false;  // complexity limit
3254   for (uint i = 1; i < n->req(); i++) {
3255     Node* m = n->in(i);
3256     if (m == NULL || m == n || m->is_top())  continue;
3257     uint first_i = n->find_edge(m);
3258     if (i != first_i)  continue;  // process duplicate edge just once
3259     if (!detect_init_independence(m, count)) {
3260       return false;
3261     }
3262   }
3263 
3264   return true;
3265 }
3266 
3267 // Here are all the checks a Store must pass before it can be moved into
3268 // an initialization.  Returns zero if a check fails.
3269 // On success, returns the (constant) offset to which the store applies,
3270 // within the initialized memory.
3271 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase, bool can_reshape) {
3272   const int FAIL = 0;
3273   if (st->is_unaligned_access()) {
3274     return FAIL;
3275   }
3276   if (st->req() != MemNode::ValueIn + 1)
3277     return FAIL;                // an inscrutable StoreNode (card mark?)
3278   Node* ctl = st->in(MemNode::Control);
3279   if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
3280     return FAIL;                // must be unconditional after the initialization
3281   Node* mem = st->in(MemNode::Memory);
3282   if (!(mem->is_Proj() && mem->in(0) == this))
3283     return FAIL;                // must not be preceded by other stores
3284   Node* adr = st->in(MemNode::Address);
3285   intptr_t offset;
3286   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
3287   if (alloc == NULL)
3288     return FAIL;                // inscrutable address
3289   if (alloc != allocation())
3290     return FAIL;                // wrong allocation!  (store needs to float up)
3291   Node* val = st->in(MemNode::ValueIn);
3292   int complexity_count = 0;
3293   if (!detect_init_independence(val, complexity_count))
3294     return FAIL;                // stored value must be 'simple enough'
3295 
3296   // The Store can be captured only if nothing after the allocation
3297   // and before the Store is using the memory location that the store
3298   // overwrites.
3299   bool failed = false;
3300   // If is_complete_with_arraycopy() is true the shape of the graph is
3301   // well defined and is safe so no need for extra checks.
3302   if (!is_complete_with_arraycopy()) {
3303     // We are going to look at each use of the memory state following
3304     // the allocation to make sure nothing reads the memory that the
3305     // Store writes.
3306     const TypePtr* t_adr = phase->type(adr)->isa_ptr();
3307     int alias_idx = phase->C->get_alias_index(t_adr);
3308     ResourceMark rm;
3309     Unique_Node_List mems;
3310     mems.push(mem);
3311     Node* unique_merge = NULL;
3312     for (uint next = 0; next < mems.size(); ++next) {
3313       Node *m  = mems.at(next);
3314       for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
3315         Node *n = m->fast_out(j);
3316         if (n->outcnt() == 0) {
3317           continue;
3318         }
3319         if (n == st) {
3320           continue;
3321         } else if (n->in(0) != NULL && n->in(0) != ctl) {
3322           // If the control of this use is different from the control
3323           // of the Store which is right after the InitializeNode then
3324           // this node cannot be between the InitializeNode and the
3325           // Store.
3326           continue;
3327         } else if (n->is_MergeMem()) {
3328           if (n->as_MergeMem()->memory_at(alias_idx) == m) {
3329             // We can hit a MergeMemNode (that will likely go away
3330             // later) that is a direct use of the memory state
3331             // following the InitializeNode on the same slice as the
3332             // store node that we'd like to capture. We need to check
3333             // the uses of the MergeMemNode.
3334             mems.push(n);
3335           }
3336         } else if (n->is_Mem()) {
3337           Node* other_adr = n->in(MemNode::Address);
3338           if (other_adr == adr) {
3339             failed = true;
3340             break;
3341           } else {
3342             const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
3343             if (other_t_adr != NULL) {
3344               int other_alias_idx = phase->C->get_alias_index(other_t_adr);
3345               if (other_alias_idx == alias_idx) {
3346                 // A load from the same memory slice as the store right
3347                 // after the InitializeNode. We check the control of the
3348                 // object/array that is loaded from. If it's the same as
3349                 // the store control then we cannot capture the store.
3350                 assert(!n->is_Store(), "2 stores to same slice on same control?");
3351                 Node* base = other_adr;
3352                 assert(base->is_AddP(), "should be addp but is %s", base->Name());
3353                 base = base->in(AddPNode::Base);
3354                 if (base != NULL) {
3355                   base = base->uncast();
3356                   if (base->is_Proj() && base->in(0) == alloc) {
3357                     failed = true;
3358                     break;
3359                   }
3360                 }
3361               }
3362             }
3363           }
3364         } else {
3365           failed = true;
3366           break;
3367         }
3368       }
3369     }
3370   }
3371   if (failed) {
3372     if (!can_reshape) {
3373       // We decided we couldn't capture the store during parsing. We
3374       // should try again during the next IGVN once the graph is
3375       // cleaner.
3376       phase->C->record_for_igvn(st);
3377     }
3378     return FAIL;
3379   }
3380 
3381   return offset;                // success
3382 }
3383 
3384 // Find the captured store in(i) which corresponds to the range
3385 // [start..start+size) in the initialized object.
3386 // If there is one, return its index i.  If there isn't, return the
3387 // negative of the index where it should be inserted.
3388 // Return 0 if the queried range overlaps an initialization boundary
3389 // or if dead code is encountered.
3390 // If size_in_bytes is zero, do not bother with overlap checks.
3391 int InitializeNode::captured_store_insertion_point(intptr_t start,
3392                                                    int size_in_bytes,
3393                                                    PhaseTransform* phase) {
3394   const int FAIL = 0, MAX_STORE = BytesPerLong;
3395 
3396   if (is_complete())
3397     return FAIL;                // arraycopy got here first; punt
3398 
3399   assert(allocation() != NULL, "must be present");
3400 
3401   // no negatives, no header fields:
3402   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
3403 
3404   // after a certain size, we bail out on tracking all the stores:
3405   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3406   if (start >= ti_limit)  return FAIL;
3407 
3408   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
3409     if (i >= limit)  return -(int)i; // not found; here is where to put it
3410 
3411     Node*    st     = in(i);
3412     intptr_t st_off = get_store_offset(st, phase);
3413     if (st_off < 0) {
3414       if (st != zero_memory()) {
3415         return FAIL;            // bail out if there is dead garbage
3416       }
3417     } else if (st_off > start) {
3418       // ...we are done, since stores are ordered
3419       if (st_off < start + size_in_bytes) {
3420         return FAIL;            // the next store overlaps
3421       }
3422       return -(int)i;           // not found; here is where to put it
3423     } else if (st_off < start) {
3424       if (size_in_bytes != 0 &&
3425           start < st_off + MAX_STORE &&
3426           start < st_off + st->as_Store()->memory_size()) {
3427         return FAIL;            // the previous store overlaps
3428       }
3429     } else {
3430       if (size_in_bytes != 0 &&
3431           st->as_Store()->memory_size() != size_in_bytes) {
3432         return FAIL;            // mismatched store size
3433       }
3434       return i;
3435     }
3436 
3437     ++i;
3438   }
3439 }
3440 
3441 // Look for a captured store which initializes at the offset 'start'
3442 // with the given size.  If there is no such store, and no other
3443 // initialization interferes, then return zero_memory (the memory
3444 // projection of the AllocateNode).
3445 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
3446                                           PhaseTransform* phase) {
3447   assert(stores_are_sane(phase), "");
3448   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3449   if (i == 0) {
3450     return NULL;                // something is dead
3451   } else if (i < 0) {
3452     return zero_memory();       // just primordial zero bits here
3453   } else {
3454     Node* st = in(i);           // here is the store at this position
3455     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
3456     return st;
3457   }
3458 }
3459 
3460 // Create, as a raw pointer, an address within my new object at 'offset'.
3461 Node* InitializeNode::make_raw_address(intptr_t offset,
3462                                        PhaseTransform* phase) {
3463   Node* addr = in(RawAddress);
3464   if (offset != 0) {
3465     Compile* C = phase->C;
3466     addr = phase->transform( new AddPNode(C->top(), addr,
3467                                                  phase->MakeConX(offset)) );
3468   }
3469   return addr;
3470 }
3471 
3472 // Clone the given store, converting it into a raw store
3473 // initializing a field or element of my new object.
3474 // Caller is responsible for retiring the original store,
3475 // with subsume_node or the like.
3476 //
3477 // From the example above InitializeNode::InitializeNode,
3478 // here are the old stores to be captured:
3479 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3480 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3481 //
3482 // Here is the changed code; note the extra edges on init:
3483 //   alloc = (Allocate ...)
3484 //   rawoop = alloc.RawAddress
3485 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
3486 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
3487 //   init = (Initialize alloc.Control alloc.Memory rawoop
3488 //                      rawstore1 rawstore2)
3489 //
3490 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
3491                                     PhaseTransform* phase, bool can_reshape) {
3492   assert(stores_are_sane(phase), "");
3493 
3494   if (start < 0)  return NULL;
3495   assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
3496 
3497   Compile* C = phase->C;
3498   int size_in_bytes = st->memory_size();
3499   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3500   if (i == 0)  return NULL;     // bail out
3501   Node* prev_mem = NULL;        // raw memory for the captured store
3502   if (i > 0) {
3503     prev_mem = in(i);           // there is a pre-existing store under this one
3504     set_req(i, C->top());       // temporarily disconnect it
3505     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
3506   } else {
3507     i = -i;                     // no pre-existing store
3508     prev_mem = zero_memory();   // a slice of the newly allocated object
3509     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
3510       set_req(--i, C->top());   // reuse this edge; it has been folded away
3511     else
3512       ins_req(i, C->top());     // build a new edge
3513   }
3514   Node* new_st = st->clone();
3515   new_st->set_req(MemNode::Control, in(Control));
3516   new_st->set_req(MemNode::Memory,  prev_mem);
3517   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
3518   new_st = phase->transform(new_st);
3519 
3520   // At this point, new_st might have swallowed a pre-existing store
3521   // at the same offset, or perhaps new_st might have disappeared,
3522   // if it redundantly stored the same value (or zero to fresh memory).
3523 
3524   // In any case, wire it in:
3525   phase->igvn_rehash_node_delayed(this);
3526   set_req(i, new_st);
3527 
3528   // The caller may now kill the old guy.
3529   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
3530   assert(check_st == new_st || check_st == NULL, "must be findable");
3531   assert(!is_complete(), "");
3532   return new_st;
3533 }
3534 
3535 static bool store_constant(jlong* tiles, int num_tiles,
3536                            intptr_t st_off, int st_size,
3537                            jlong con) {
3538   if ((st_off & (st_size-1)) != 0)
3539     return false;               // strange store offset (assume size==2**N)
3540   address addr = (address)tiles + st_off;
3541   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
3542   switch (st_size) {
3543   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
3544   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
3545   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
3546   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
3547   default: return false;        // strange store size (detect size!=2**N here)
3548   }
3549   return true;                  // return success to caller
3550 }
3551 
3552 // Coalesce subword constants into int constants and possibly
3553 // into long constants.  The goal, if the CPU permits,
3554 // is to initialize the object with a small number of 64-bit tiles.
3555 // Also, convert floating-point constants to bit patterns.
3556 // Non-constants are not relevant to this pass.
3557 //
3558 // In terms of the running example on InitializeNode::InitializeNode
3559 // and InitializeNode::capture_store, here is the transformation
3560 // of rawstore1 and rawstore2 into rawstore12:
3561 //   alloc = (Allocate ...)
3562 //   rawoop = alloc.RawAddress
3563 //   tile12 = 0x00010002
3564 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
3565 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
3566 //
3567 void
3568 InitializeNode::coalesce_subword_stores(intptr_t header_size,
3569                                         Node* size_in_bytes,
3570                                         PhaseGVN* phase) {
3571   Compile* C = phase->C;
3572 
3573   assert(stores_are_sane(phase), "");
3574   // Note:  After this pass, they are not completely sane,
3575   // since there may be some overlaps.
3576 
3577   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
3578 
3579   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3580   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
3581   size_limit = MIN2(size_limit, ti_limit);
3582   size_limit = align_up(size_limit, BytesPerLong);
3583   int num_tiles = size_limit / BytesPerLong;
3584 
3585   // allocate space for the tile map:
3586   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
3587   jlong  tiles_buf[small_len];
3588   Node*  nodes_buf[small_len];
3589   jlong  inits_buf[small_len];
3590   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
3591                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3592   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
3593                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
3594   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
3595                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3596   // tiles: exact bitwise model of all primitive constants
3597   // nodes: last constant-storing node subsumed into the tiles model
3598   // inits: which bytes (in each tile) are touched by any initializations
3599 
3600   //// Pass A: Fill in the tile model with any relevant stores.
3601 
3602   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
3603   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
3604   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
3605   Node* zmem = zero_memory(); // initially zero memory state
3606   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3607     Node* st = in(i);
3608     intptr_t st_off = get_store_offset(st, phase);
3609 
3610     // Figure out the store's offset and constant value:
3611     if (st_off < header_size)             continue; //skip (ignore header)
3612     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
3613     int st_size = st->as_Store()->memory_size();
3614     if (st_off + st_size > size_limit)    break;
3615 
3616     // Record which bytes are touched, whether by constant or not.
3617     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
3618       continue;                 // skip (strange store size)
3619 
3620     const Type* val = phase->type(st->in(MemNode::ValueIn));
3621     if (!val->singleton())                continue; //skip (non-con store)
3622     BasicType type = val->basic_type();
3623 
3624     jlong con = 0;
3625     switch (type) {
3626     case T_INT:    con = val->is_int()->get_con();  break;
3627     case T_LONG:   con = val->is_long()->get_con(); break;
3628     case T_FLOAT:  con = jint_cast(val->getf());    break;
3629     case T_DOUBLE: con = jlong_cast(val->getd());   break;
3630     default:                              continue; //skip (odd store type)
3631     }
3632 
3633     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
3634         st->Opcode() == Op_StoreL) {
3635       continue;                 // This StoreL is already optimal.
3636     }
3637 
3638     // Store down the constant.
3639     store_constant(tiles, num_tiles, st_off, st_size, con);
3640 
3641     intptr_t j = st_off >> LogBytesPerLong;
3642 
3643     if (type == T_INT && st_size == BytesPerInt
3644         && (st_off & BytesPerInt) == BytesPerInt) {
3645       jlong lcon = tiles[j];
3646       if (!Matcher::isSimpleConstant64(lcon) &&
3647           st->Opcode() == Op_StoreI) {
3648         // This StoreI is already optimal by itself.
3649         jint* intcon = (jint*) &tiles[j];
3650         intcon[1] = 0;  // undo the store_constant()
3651 
3652         // If the previous store is also optimal by itself, back up and
3653         // undo the action of the previous loop iteration... if we can.
3654         // But if we can't, just let the previous half take care of itself.
3655         st = nodes[j];
3656         st_off -= BytesPerInt;
3657         con = intcon[0];
3658         if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
3659           assert(st_off >= header_size, "still ignoring header");
3660           assert(get_store_offset(st, phase) == st_off, "must be");
3661           assert(in(i-1) == zmem, "must be");
3662           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
3663           assert(con == tcon->is_int()->get_con(), "must be");
3664           // Undo the effects of the previous loop trip, which swallowed st:
3665           intcon[0] = 0;        // undo store_constant()
3666           set_req(i-1, st);     // undo set_req(i, zmem)
3667           nodes[j] = NULL;      // undo nodes[j] = st
3668           --old_subword;        // undo ++old_subword
3669         }
3670         continue;               // This StoreI is already optimal.
3671       }
3672     }
3673 
3674     // This store is not needed.
3675     set_req(i, zmem);
3676     nodes[j] = st;              // record for the moment
3677     if (st_size < BytesPerLong) // something has changed
3678           ++old_subword;        // includes int/float, but who's counting...
3679     else  ++old_long;
3680   }
3681 
3682   if ((old_subword + old_long) == 0)
3683     return;                     // nothing more to do
3684 
3685   //// Pass B: Convert any non-zero tiles into optimal constant stores.
3686   // Be sure to insert them before overlapping non-constant stores.
3687   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
3688   for (int j = 0; j < num_tiles; j++) {
3689     jlong con  = tiles[j];
3690     jlong init = inits[j];
3691     if (con == 0)  continue;
3692     jint con0,  con1;           // split the constant, address-wise
3693     jint init0, init1;          // split the init map, address-wise
3694     { union { jlong con; jint intcon[2]; } u;
3695       u.con = con;
3696       con0  = u.intcon[0];
3697       con1  = u.intcon[1];
3698       u.con = init;
3699       init0 = u.intcon[0];
3700       init1 = u.intcon[1];
3701     }
3702 
3703     Node* old = nodes[j];
3704     assert(old != NULL, "need the prior store");
3705     intptr_t offset = (j * BytesPerLong);
3706 
3707     bool split = !Matcher::isSimpleConstant64(con);
3708 
3709     if (offset < header_size) {
3710       assert(offset + BytesPerInt >= header_size, "second int counts");
3711       assert(*(jint*)&tiles[j] == 0, "junk in header");
3712       split = true;             // only the second word counts
3713       // Example:  int a[] = { 42 ... }
3714     } else if (con0 == 0 && init0 == -1) {
3715       split = true;             // first word is covered by full inits
3716       // Example:  int a[] = { ... foo(), 42 ... }
3717     } else if (con1 == 0 && init1 == -1) {
3718       split = true;             // second word is covered by full inits
3719       // Example:  int a[] = { ... 42, foo() ... }
3720     }
3721 
3722     // Here's a case where init0 is neither 0 nor -1:
3723     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
3724     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
3725     // In this case the tile is not split; it is (jlong)42.
3726     // The big tile is stored down, and then the foo() value is inserted.
3727     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
3728 
3729     Node* ctl = old->in(MemNode::Control);
3730     Node* adr = make_raw_address(offset, phase);
3731     const TypePtr* atp = TypeRawPtr::BOTTOM;
3732 
3733     // One or two coalesced stores to plop down.
3734     Node*    st[2];
3735     intptr_t off[2];
3736     int  nst = 0;
3737     if (!split) {
3738       ++new_long;
3739       off[nst] = offset;
3740       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3741                                   phase->longcon(con), T_LONG, MemNode::unordered);
3742     } else {
3743       // Omit either if it is a zero.
3744       if (con0 != 0) {
3745         ++new_int;
3746         off[nst]  = offset;
3747         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3748                                     phase->intcon(con0), T_INT, MemNode::unordered);
3749       }
3750       if (con1 != 0) {
3751         ++new_int;
3752         offset += BytesPerInt;
3753         adr = make_raw_address(offset, phase);
3754         off[nst]  = offset;
3755         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3756                                     phase->intcon(con1), T_INT, MemNode::unordered);
3757       }
3758     }
3759 
3760     // Insert second store first, then the first before the second.
3761     // Insert each one just before any overlapping non-constant stores.
3762     while (nst > 0) {
3763       Node* st1 = st[--nst];
3764       C->copy_node_notes_to(st1, old);
3765       st1 = phase->transform(st1);
3766       offset = off[nst];
3767       assert(offset >= header_size, "do not smash header");
3768       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
3769       guarantee(ins_idx != 0, "must re-insert constant store");
3770       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
3771       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
3772         set_req(--ins_idx, st1);
3773       else
3774         ins_req(ins_idx, st1);
3775     }
3776   }
3777 
3778   if (PrintCompilation && WizardMode)
3779     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
3780                   old_subword, old_long, new_int, new_long);
3781   if (C->log() != NULL)
3782     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
3783                    old_subword, old_long, new_int, new_long);
3784 
3785   // Clean up any remaining occurrences of zmem:
3786   remove_extra_zeroes();
3787 }
3788 
3789 // Explore forward from in(start) to find the first fully initialized
3790 // word, and return its offset.  Skip groups of subword stores which
3791 // together initialize full words.  If in(start) is itself part of a
3792 // fully initialized word, return the offset of in(start).  If there
3793 // are no following full-word stores, or if something is fishy, return
3794 // a negative value.
3795 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
3796   int       int_map = 0;
3797   intptr_t  int_map_off = 0;
3798   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
3799 
3800   for (uint i = start, limit = req(); i < limit; i++) {
3801     Node* st = in(i);
3802 
3803     intptr_t st_off = get_store_offset(st, phase);
3804     if (st_off < 0)  break;  // return conservative answer
3805 
3806     int st_size = st->as_Store()->memory_size();
3807     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
3808       return st_off;            // we found a complete word init
3809     }
3810 
3811     // update the map:
3812 
3813     intptr_t this_int_off = align_down(st_off, BytesPerInt);
3814     if (this_int_off != int_map_off) {
3815       // reset the map:
3816       int_map = 0;
3817       int_map_off = this_int_off;
3818     }
3819 
3820     int subword_off = st_off - this_int_off;
3821     int_map |= right_n_bits(st_size) << subword_off;
3822     if ((int_map & FULL_MAP) == FULL_MAP) {
3823       return this_int_off;      // we found a complete word init
3824     }
3825 
3826     // Did this store hit or cross the word boundary?
3827     intptr_t next_int_off = align_down(st_off + st_size, BytesPerInt);
3828     if (next_int_off == this_int_off + BytesPerInt) {
3829       // We passed the current int, without fully initializing it.
3830       int_map_off = next_int_off;
3831       int_map >>= BytesPerInt;
3832     } else if (next_int_off > this_int_off + BytesPerInt) {
3833       // We passed the current and next int.
3834       return this_int_off + BytesPerInt;
3835     }
3836   }
3837 
3838   return -1;
3839 }
3840 
3841 
3842 // Called when the associated AllocateNode is expanded into CFG.
3843 // At this point, we may perform additional optimizations.
3844 // Linearize the stores by ascending offset, to make memory
3845 // activity as coherent as possible.
3846 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
3847                                       intptr_t header_size,
3848                                       Node* size_in_bytes,
3849                                       PhaseGVN* phase) {
3850   assert(!is_complete(), "not already complete");
3851   assert(stores_are_sane(phase), "");
3852   assert(allocation() != NULL, "must be present");
3853 
3854   remove_extra_zeroes();
3855 
3856   if (ReduceFieldZeroing || ReduceBulkZeroing)
3857     // reduce instruction count for common initialization patterns
3858     coalesce_subword_stores(header_size, size_in_bytes, phase);
3859 
3860   Node* zmem = zero_memory();   // initially zero memory state
3861   Node* inits = zmem;           // accumulating a linearized chain of inits
3862   #ifdef ASSERT
3863   intptr_t first_offset = allocation()->minimum_header_size();
3864   intptr_t last_init_off = first_offset;  // previous init offset
3865   intptr_t last_init_end = first_offset;  // previous init offset+size
3866   intptr_t last_tile_end = first_offset;  // previous tile offset+size
3867   #endif
3868   intptr_t zeroes_done = header_size;
3869 
3870   bool do_zeroing = true;       // we might give up if inits are very sparse
3871   int  big_init_gaps = 0;       // how many large gaps have we seen?
3872 
3873   if (UseTLAB && ZeroTLAB)  do_zeroing = false;
3874   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
3875 
3876   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3877     Node* st = in(i);
3878     intptr_t st_off = get_store_offset(st, phase);
3879     if (st_off < 0)
3880       break;                    // unknown junk in the inits
3881     if (st->in(MemNode::Memory) != zmem)
3882       break;                    // complicated store chains somehow in list
3883 
3884     int st_size = st->as_Store()->memory_size();
3885     intptr_t next_init_off = st_off + st_size;
3886 
3887     if (do_zeroing && zeroes_done < next_init_off) {
3888       // See if this store needs a zero before it or under it.
3889       intptr_t zeroes_needed = st_off;
3890 
3891       if (st_size < BytesPerInt) {
3892         // Look for subword stores which only partially initialize words.
3893         // If we find some, we must lay down some word-level zeroes first,
3894         // underneath the subword stores.
3895         //
3896         // Examples:
3897         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
3898         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
3899         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
3900         //
3901         // Note:  coalesce_subword_stores may have already done this,
3902         // if it was prompted by constant non-zero subword initializers.
3903         // But this case can still arise with non-constant stores.
3904 
3905         intptr_t next_full_store = find_next_fullword_store(i, phase);
3906 
3907         // In the examples above:
3908         //   in(i)          p   q   r   s     x   y     z
3909         //   st_off        12  13  14  15    12  13    14
3910         //   st_size        1   1   1   1     1   1     1
3911         //   next_full_s.  12  16  16  16    16  16    16
3912         //   z's_done      12  16  16  16    12  16    12
3913         //   z's_needed    12  16  16  16    16  16    16
3914         //   zsize          0   0   0   0     4   0     4
3915         if (next_full_store < 0) {
3916           // Conservative tack:  Zero to end of current word.
3917           zeroes_needed = align_up(zeroes_needed, BytesPerInt);
3918         } else {
3919           // Zero to beginning of next fully initialized word.
3920           // Or, don't zero at all, if we are already in that word.
3921           assert(next_full_store >= zeroes_needed, "must go forward");
3922           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
3923           zeroes_needed = next_full_store;
3924         }
3925       }
3926 
3927       if (zeroes_needed > zeroes_done) {
3928         intptr_t zsize = zeroes_needed - zeroes_done;
3929         // Do some incremental zeroing on rawmem, in parallel with inits.
3930         zeroes_done = align_down(zeroes_done, BytesPerInt);
3931         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3932                                               zeroes_done, zeroes_needed,
3933                                               phase);
3934         zeroes_done = zeroes_needed;
3935         if (zsize > InitArrayShortSize && ++big_init_gaps > 2)
3936           do_zeroing = false;   // leave the hole, next time
3937       }
3938     }
3939 
3940     // Collect the store and move on:
3941     st->set_req(MemNode::Memory, inits);
3942     inits = st;                 // put it on the linearized chain
3943     set_req(i, zmem);           // unhook from previous position
3944 
3945     if (zeroes_done == st_off)
3946       zeroes_done = next_init_off;
3947 
3948     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
3949 
3950     #ifdef ASSERT
3951     // Various order invariants.  Weaker than stores_are_sane because
3952     // a large constant tile can be filled in by smaller non-constant stores.
3953     assert(st_off >= last_init_off, "inits do not reverse");
3954     last_init_off = st_off;
3955     const Type* val = NULL;
3956     if (st_size >= BytesPerInt &&
3957         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
3958         (int)val->basic_type() < (int)T_OBJECT) {
3959       assert(st_off >= last_tile_end, "tiles do not overlap");
3960       assert(st_off >= last_init_end, "tiles do not overwrite inits");
3961       last_tile_end = MAX2(last_tile_end, next_init_off);
3962     } else {
3963       intptr_t st_tile_end = align_up(next_init_off, BytesPerLong);
3964       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
3965       assert(st_off      >= last_init_end, "inits do not overlap");
3966       last_init_end = next_init_off;  // it's a non-tile
3967     }
3968     #endif //ASSERT
3969   }
3970 
3971   remove_extra_zeroes();        // clear out all the zmems left over
3972   add_req(inits);
3973 
3974   if (!(UseTLAB && ZeroTLAB)) {
3975     // If anything remains to be zeroed, zero it all now.
3976     zeroes_done = align_down(zeroes_done, BytesPerInt);
3977     // if it is the last unused 4 bytes of an instance, forget about it
3978     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
3979     if (zeroes_done + BytesPerLong >= size_limit) {
3980       AllocateNode* alloc = allocation();
3981       assert(alloc != NULL, "must be present");
3982       if (alloc != NULL && alloc->Opcode() == Op_Allocate) {
3983         Node* klass_node = alloc->in(AllocateNode::KlassNode);
3984         ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
3985         if (zeroes_done == k->layout_helper())
3986           zeroes_done = size_limit;
3987       }
3988     }
3989     if (zeroes_done < size_limit) {
3990       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3991                                             zeroes_done, size_in_bytes, phase);
3992     }
3993   }
3994 
3995   set_complete(phase);
3996   return rawmem;
3997 }
3998 
3999 
4000 #ifdef ASSERT
4001 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
4002   if (is_complete())
4003     return true;                // stores could be anything at this point
4004   assert(allocation() != NULL, "must be present");
4005   intptr_t last_off = allocation()->minimum_header_size();
4006   for (uint i = InitializeNode::RawStores; i < req(); i++) {
4007     Node* st = in(i);
4008     intptr_t st_off = get_store_offset(st, phase);
4009     if (st_off < 0)  continue;  // ignore dead garbage
4010     if (last_off > st_off) {
4011       tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
4012       this->dump(2);
4013       assert(false, "ascending store offsets");
4014       return false;
4015     }
4016     last_off = st_off + st->as_Store()->memory_size();
4017   }
4018   return true;
4019 }
4020 #endif //ASSERT
4021 
4022 
4023 
4024 
4025 //============================MergeMemNode=====================================
4026 //
4027 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
4028 // contributing store or call operations.  Each contributor provides the memory
4029 // state for a particular "alias type" (see Compile::alias_type).  For example,
4030 // if a MergeMem has an input X for alias category #6, then any memory reference
4031 // to alias category #6 may use X as its memory state input, as an exact equivalent
4032 // to using the MergeMem as a whole.
4033 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
4034 //
4035 // (Here, the <N> notation gives the index of the relevant adr_type.)
4036 //
4037 // In one special case (and more cases in the future), alias categories overlap.
4038 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
4039 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
4040 // it is exactly equivalent to that state W:
4041 //   MergeMem(<Bot>: W) <==> W
4042 //
4043 // Usually, the merge has more than one input.  In that case, where inputs
4044 // overlap (i.e., one is Bot), the narrower alias type determines the memory
4045 // state for that type, and the wider alias type (Bot) fills in everywhere else:
4046 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
4047 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
4048 //
4049 // A merge can take a "wide" memory state as one of its narrow inputs.
4050 // This simply means that the merge observes out only the relevant parts of
4051 // the wide input.  That is, wide memory states arriving at narrow merge inputs
4052 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
4053 //
4054 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
4055 // and that memory slices "leak through":
4056 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
4057 //
4058 // But, in such a cascade, repeated memory slices can "block the leak":
4059 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
4060 //
4061 // In the last example, Y is not part of the combined memory state of the
4062 // outermost MergeMem.  The system must, of course, prevent unschedulable
4063 // memory states from arising, so you can be sure that the state Y is somehow
4064 // a precursor to state Y'.
4065 //
4066 //
4067 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
4068 // of each MergeMemNode array are exactly the numerical alias indexes, including
4069 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
4070 // Compile::alias_type (and kin) produce and manage these indexes.
4071 //
4072 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
4073 // (Note that this provides quick access to the top node inside MergeMem methods,
4074 // without the need to reach out via TLS to Compile::current.)
4075 //
4076 // As a consequence of what was just described, a MergeMem that represents a full
4077 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
4078 // containing all alias categories.
4079 //
4080 // MergeMem nodes never (?) have control inputs, so in(0) is NULL.
4081 //
4082 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
4083 // a memory state for the alias type <N>, or else the top node, meaning that
4084 // there is no particular input for that alias type.  Note that the length of
4085 // a MergeMem is variable, and may be extended at any time to accommodate new
4086 // memory states at larger alias indexes.  When merges grow, they are of course
4087 // filled with "top" in the unused in() positions.
4088 //
4089 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
4090 // (Top was chosen because it works smoothly with passes like GCM.)
4091 //
4092 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
4093 // the type of random VM bits like TLS references.)  Since it is always the
4094 // first non-Bot memory slice, some low-level loops use it to initialize an
4095 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
4096 //
4097 //
4098 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
4099 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
4100 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
4101 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
4102 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
4103 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
4104 //
4105 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
4106 // really that different from the other memory inputs.  An abbreviation called
4107 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
4108 //
4109 //
4110 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
4111 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
4112 // that "emerges though" the base memory will be marked as excluding the alias types
4113 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
4114 //
4115 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
4116 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
4117 //
4118 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
4119 // (It is currently unimplemented.)  As you can see, the resulting merge is
4120 // actually a disjoint union of memory states, rather than an overlay.
4121 //
4122 
4123 //------------------------------MergeMemNode-----------------------------------
4124 Node* MergeMemNode::make_empty_memory() {
4125   Node* empty_memory = (Node*) Compile::current()->top();
4126   assert(empty_memory->is_top(), "correct sentinel identity");
4127   return empty_memory;
4128 }
4129 
4130 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
4131   init_class_id(Class_MergeMem);
4132   // all inputs are nullified in Node::Node(int)
4133   // set_input(0, NULL);  // no control input
4134 
4135   // Initialize the edges uniformly to top, for starters.
4136   Node* empty_mem = make_empty_memory();
4137   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
4138     init_req(i,empty_mem);
4139   }
4140   assert(empty_memory() == empty_mem, "");
4141 
4142   if( new_base != NULL && new_base->is_MergeMem() ) {
4143     MergeMemNode* mdef = new_base->as_MergeMem();
4144     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
4145     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
4146       mms.set_memory(mms.memory2());
4147     }
4148     assert(base_memory() == mdef->base_memory(), "");
4149   } else {
4150     set_base_memory(new_base);
4151   }
4152 }
4153 
4154 // Make a new, untransformed MergeMem with the same base as 'mem'.
4155 // If mem is itself a MergeMem, populate the result with the same edges.
4156 MergeMemNode* MergeMemNode::make(Node* mem) {
4157   return new MergeMemNode(mem);
4158 }
4159 
4160 //------------------------------cmp--------------------------------------------
4161 uint MergeMemNode::hash() const { return NO_HASH; }
4162 uint MergeMemNode::cmp( const Node &n ) const {
4163   return (&n == this);          // Always fail except on self
4164 }
4165 
4166 //------------------------------Identity---------------------------------------
4167 Node* MergeMemNode::Identity(PhaseGVN* phase) {
4168   // Identity if this merge point does not record any interesting memory
4169   // disambiguations.
4170   Node* base_mem = base_memory();
4171   Node* empty_mem = empty_memory();
4172   if (base_mem != empty_mem) {  // Memory path is not dead?
4173     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4174       Node* mem = in(i);
4175       if (mem != empty_mem && mem != base_mem) {
4176         return this;            // Many memory splits; no change
4177       }
4178     }
4179   }
4180   return base_mem;              // No memory splits; ID on the one true input
4181 }
4182 
4183 //------------------------------Ideal------------------------------------------
4184 // This method is invoked recursively on chains of MergeMem nodes
4185 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4186   // Remove chain'd MergeMems
4187   //
4188   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
4189   // relative to the "in(Bot)".  Since we are patching both at the same time,
4190   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
4191   // but rewrite each "in(i)" relative to the new "in(Bot)".
4192   Node *progress = NULL;
4193 
4194 
4195   Node* old_base = base_memory();
4196   Node* empty_mem = empty_memory();
4197   if (old_base == empty_mem)
4198     return NULL; // Dead memory path.
4199 
4200   MergeMemNode* old_mbase;
4201   if (old_base != NULL && old_base->is_MergeMem())
4202     old_mbase = old_base->as_MergeMem();
4203   else
4204     old_mbase = NULL;
4205   Node* new_base = old_base;
4206 
4207   // simplify stacked MergeMems in base memory
4208   if (old_mbase)  new_base = old_mbase->base_memory();
4209 
4210   // the base memory might contribute new slices beyond my req()
4211   if (old_mbase)  grow_to_match(old_mbase);
4212 
4213   // Look carefully at the base node if it is a phi.
4214   PhiNode* phi_base;
4215   if (new_base != NULL && new_base->is_Phi())
4216     phi_base = new_base->as_Phi();
4217   else
4218     phi_base = NULL;
4219 
4220   Node*    phi_reg = NULL;
4221   uint     phi_len = (uint)-1;
4222   if (phi_base != NULL && !phi_base->is_copy()) {
4223     // do not examine phi if degraded to a copy
4224     phi_reg = phi_base->region();
4225     phi_len = phi_base->req();
4226     // see if the phi is unfinished
4227     for (uint i = 1; i < phi_len; i++) {
4228       if (phi_base->in(i) == NULL) {
4229         // incomplete phi; do not look at it yet!
4230         phi_reg = NULL;
4231         phi_len = (uint)-1;
4232         break;
4233       }
4234     }
4235   }
4236 
4237   // Note:  We do not call verify_sparse on entry, because inputs
4238   // can normalize to the base_memory via subsume_node or similar
4239   // mechanisms.  This method repairs that damage.
4240 
4241   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
4242 
4243   // Look at each slice.
4244   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4245     Node* old_in = in(i);
4246     // calculate the old memory value
4247     Node* old_mem = old_in;
4248     if (old_mem == empty_mem)  old_mem = old_base;
4249     assert(old_mem == memory_at(i), "");
4250 
4251     // maybe update (reslice) the old memory value
4252 
4253     // simplify stacked MergeMems
4254     Node* new_mem = old_mem;
4255     MergeMemNode* old_mmem;
4256     if (old_mem != NULL && old_mem->is_MergeMem())
4257       old_mmem = old_mem->as_MergeMem();
4258     else
4259       old_mmem = NULL;
4260     if (old_mmem == this) {
4261       // This can happen if loops break up and safepoints disappear.
4262       // A merge of BotPtr (default) with a RawPtr memory derived from a
4263       // safepoint can be rewritten to a merge of the same BotPtr with
4264       // the BotPtr phi coming into the loop.  If that phi disappears
4265       // also, we can end up with a self-loop of the mergemem.
4266       // In general, if loops degenerate and memory effects disappear,
4267       // a mergemem can be left looking at itself.  This simply means
4268       // that the mergemem's default should be used, since there is
4269       // no longer any apparent effect on this slice.
4270       // Note: If a memory slice is a MergeMem cycle, it is unreachable
4271       //       from start.  Update the input to TOP.
4272       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
4273     }
4274     else if (old_mmem != NULL) {
4275       new_mem = old_mmem->memory_at(i);
4276     }
4277     // else preceding memory was not a MergeMem
4278 
4279     // replace equivalent phis (unfortunately, they do not GVN together)
4280     if (new_mem != NULL && new_mem != new_base &&
4281         new_mem->req() == phi_len && new_mem->in(0) == phi_reg) {
4282       if (new_mem->is_Phi()) {
4283         PhiNode* phi_mem = new_mem->as_Phi();
4284         for (uint i = 1; i < phi_len; i++) {
4285           if (phi_base->in(i) != phi_mem->in(i)) {
4286             phi_mem = NULL;
4287             break;
4288           }
4289         }
4290         if (phi_mem != NULL) {
4291           // equivalent phi nodes; revert to the def
4292           new_mem = new_base;
4293         }
4294       }
4295     }
4296 
4297     // maybe store down a new value
4298     Node* new_in = new_mem;
4299     if (new_in == new_base)  new_in = empty_mem;
4300 
4301     if (new_in != old_in) {
4302       // Warning:  Do not combine this "if" with the previous "if"
4303       // A memory slice might have be be rewritten even if it is semantically
4304       // unchanged, if the base_memory value has changed.
4305       set_req(i, new_in);
4306       progress = this;          // Report progress
4307     }
4308   }
4309 
4310   if (new_base != old_base) {
4311     set_req(Compile::AliasIdxBot, new_base);
4312     // Don't use set_base_memory(new_base), because we need to update du.
4313     assert(base_memory() == new_base, "");
4314     progress = this;
4315   }
4316 
4317   if( base_memory() == this ) {
4318     // a self cycle indicates this memory path is dead
4319     set_req(Compile::AliasIdxBot, empty_mem);
4320   }
4321 
4322   // Resolve external cycles by calling Ideal on a MergeMem base_memory
4323   // Recursion must occur after the self cycle check above
4324   if( base_memory()->is_MergeMem() ) {
4325     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
4326     Node *m = phase->transform(new_mbase);  // Rollup any cycles
4327     if( m != NULL &&
4328         (m->is_top() ||
4329          (m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem)) ) {
4330       // propagate rollup of dead cycle to self
4331       set_req(Compile::AliasIdxBot, empty_mem);
4332     }
4333   }
4334 
4335   if( base_memory() == empty_mem ) {
4336     progress = this;
4337     // Cut inputs during Parse phase only.
4338     // During Optimize phase a dead MergeMem node will be subsumed by Top.
4339     if( !can_reshape ) {
4340       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4341         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
4342       }
4343     }
4344   }
4345 
4346   if( !progress && base_memory()->is_Phi() && can_reshape ) {
4347     // Check if PhiNode::Ideal's "Split phis through memory merges"
4348     // transform should be attempted. Look for this->phi->this cycle.
4349     uint merge_width = req();
4350     if (merge_width > Compile::AliasIdxRaw) {
4351       PhiNode* phi = base_memory()->as_Phi();
4352       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
4353         if (phi->in(i) == this) {
4354           phase->is_IterGVN()->_worklist.push(phi);
4355           break;
4356         }
4357       }
4358     }
4359   }
4360 
4361   assert(progress || verify_sparse(), "please, no dups of base");
4362   return progress;
4363 }
4364 
4365 //-------------------------set_base_memory-------------------------------------
4366 void MergeMemNode::set_base_memory(Node *new_base) {
4367   Node* empty_mem = empty_memory();
4368   set_req(Compile::AliasIdxBot, new_base);
4369   assert(memory_at(req()) == new_base, "must set default memory");
4370   // Clear out other occurrences of new_base:
4371   if (new_base != empty_mem) {
4372     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4373       if (in(i) == new_base)  set_req(i, empty_mem);
4374     }
4375   }
4376 }
4377 
4378 //------------------------------out_RegMask------------------------------------
4379 const RegMask &MergeMemNode::out_RegMask() const {
4380   return RegMask::Empty;
4381 }
4382 
4383 //------------------------------dump_spec--------------------------------------
4384 #ifndef PRODUCT
4385 void MergeMemNode::dump_spec(outputStream *st) const {
4386   st->print(" {");
4387   Node* base_mem = base_memory();
4388   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
4389     Node* mem = (in(i) != NULL) ? memory_at(i) : base_mem;
4390     if (mem == base_mem) { st->print(" -"); continue; }
4391     st->print( " N%d:", mem->_idx );
4392     Compile::current()->get_adr_type(i)->dump_on(st);
4393   }
4394   st->print(" }");
4395 }
4396 #endif // !PRODUCT
4397 
4398 
4399 #ifdef ASSERT
4400 static bool might_be_same(Node* a, Node* b) {
4401   if (a == b)  return true;
4402   if (!(a->is_Phi() || b->is_Phi()))  return false;
4403   // phis shift around during optimization
4404   return true;  // pretty stupid...
4405 }
4406 
4407 // verify a narrow slice (either incoming or outgoing)
4408 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
4409   if (!VerifyAliases)                return;  // don't bother to verify unless requested
4410   if (VMError::is_error_reported())  return;  // muzzle asserts when debugging an error
4411   if (Node::in_dump())               return;  // muzzle asserts when printing
4412   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
4413   assert(n != NULL, "");
4414   // Elide intervening MergeMem's
4415   while (n->is_MergeMem()) {
4416     n = n->as_MergeMem()->memory_at(alias_idx);
4417   }
4418   Compile* C = Compile::current();
4419   const TypePtr* n_adr_type = n->adr_type();
4420   if (n == m->empty_memory()) {
4421     // Implicit copy of base_memory()
4422   } else if (n_adr_type != TypePtr::BOTTOM) {
4423     assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
4424     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
4425   } else {
4426     // A few places like make_runtime_call "know" that VM calls are narrow,
4427     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
4428     bool expected_wide_mem = false;
4429     if (n == m->base_memory()) {
4430       expected_wide_mem = true;
4431     } else if (alias_idx == Compile::AliasIdxRaw ||
4432                n == m->memory_at(Compile::AliasIdxRaw)) {
4433       expected_wide_mem = true;
4434     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
4435       // memory can "leak through" calls on channels that
4436       // are write-once.  Allow this also.
4437       expected_wide_mem = true;
4438     }
4439     assert(expected_wide_mem, "expected narrow slice replacement");
4440   }
4441 }
4442 #else // !ASSERT
4443 #define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
4444 #endif
4445 
4446 
4447 //-----------------------------memory_at---------------------------------------
4448 Node* MergeMemNode::memory_at(uint alias_idx) const {
4449   assert(alias_idx >= Compile::AliasIdxRaw ||
4450          alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
4451          "must avoid base_memory and AliasIdxTop");
4452 
4453   // Otherwise, it is a narrow slice.
4454   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
4455   Compile *C = Compile::current();
4456   if (is_empty_memory(n)) {
4457     // the array is sparse; empty slots are the "top" node
4458     n = base_memory();
4459     assert(Node::in_dump()
4460            || n == NULL || n->bottom_type() == Type::TOP
4461            || n->adr_type() == NULL // address is TOP
4462            || n->adr_type() == TypePtr::BOTTOM
4463            || n->adr_type() == TypeRawPtr::BOTTOM
4464            || Compile::current()->AliasLevel() == 0,
4465            "must be a wide memory");
4466     // AliasLevel == 0 if we are organizing the memory states manually.
4467     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
4468   } else {
4469     // make sure the stored slice is sane
4470     #ifdef ASSERT
4471     if (VMError::is_error_reported() || Node::in_dump()) {
4472     } else if (might_be_same(n, base_memory())) {
4473       // Give it a pass:  It is a mostly harmless repetition of the base.
4474       // This can arise normally from node subsumption during optimization.
4475     } else {
4476       verify_memory_slice(this, alias_idx, n);
4477     }
4478     #endif
4479   }
4480   return n;
4481 }
4482 
4483 //---------------------------set_memory_at-------------------------------------
4484 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
4485   verify_memory_slice(this, alias_idx, n);
4486   Node* empty_mem = empty_memory();
4487   if (n == base_memory())  n = empty_mem;  // collapse default
4488   uint need_req = alias_idx+1;
4489   if (req() < need_req) {
4490     if (n == empty_mem)  return;  // already the default, so do not grow me
4491     // grow the sparse array
4492     do {
4493       add_req(empty_mem);
4494     } while (req() < need_req);
4495   }
4496   set_req( alias_idx, n );
4497 }
4498 
4499 
4500 
4501 //--------------------------iteration_setup------------------------------------
4502 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
4503   if (other != NULL) {
4504     grow_to_match(other);
4505     // invariant:  the finite support of mm2 is within mm->req()
4506     #ifdef ASSERT
4507     for (uint i = req(); i < other->req(); i++) {
4508       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
4509     }
4510     #endif
4511   }
4512   // Replace spurious copies of base_memory by top.
4513   Node* base_mem = base_memory();
4514   if (base_mem != NULL && !base_mem->is_top()) {
4515     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
4516       if (in(i) == base_mem)
4517         set_req(i, empty_memory());
4518     }
4519   }
4520 }
4521 
4522 //---------------------------grow_to_match-------------------------------------
4523 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
4524   Node* empty_mem = empty_memory();
4525   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
4526   // look for the finite support of the other memory
4527   for (uint i = other->req(); --i >= req(); ) {
4528     if (other->in(i) != empty_mem) {
4529       uint new_len = i+1;
4530       while (req() < new_len)  add_req(empty_mem);
4531       break;
4532     }
4533   }
4534 }
4535 
4536 //---------------------------verify_sparse-------------------------------------
4537 #ifndef PRODUCT
4538 bool MergeMemNode::verify_sparse() const {
4539   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
4540   Node* base_mem = base_memory();
4541   // The following can happen in degenerate cases, since empty==top.
4542   if (is_empty_memory(base_mem))  return true;
4543   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4544     assert(in(i) != NULL, "sane slice");
4545     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
4546   }
4547   return true;
4548 }
4549 
4550 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
4551   Node* n;
4552   n = mm->in(idx);
4553   if (mem == n)  return true;  // might be empty_memory()
4554   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
4555   if (mem == n)  return true;
4556   while (n->is_Phi() && (n = n->as_Phi()->is_copy()) != NULL) {
4557     if (mem == n)  return true;
4558     if (n == NULL)  break;
4559   }
4560   return false;
4561 }
4562 #endif // !PRODUCT
--- EOF ---