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