src/share/vm/opto/memnode.cpp

Wed, 10 Aug 2016 14:59:21 +0200

author
simonis
date
Wed, 10 Aug 2016 14:59:21 +0200
changeset 8608
0d78aecb0948
parent 8368
32b682649973
child 8604
04d83ba48607
child 8646
88235cdca8d7
permissions
-rw-r--r--

8152172: PPC64: Support AES intrinsics
Summary: Add support for AES intrinsics on PPC64.
Reviewed-by: kvn, mdoerr, simonis, zmajo
Contributed-by: Hiroshi H Horii <horii@jp.ibm.com>

     1 /*
     2  * Copyright (c) 1997, 2016, 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  */
    25 #include "precompiled.hpp"
    26 #include "classfile/systemDictionary.hpp"
    27 #include "compiler/compileLog.hpp"
    28 #include "memory/allocation.inline.hpp"
    29 #include "oops/objArrayKlass.hpp"
    30 #include "opto/addnode.hpp"
    31 #include "opto/cfgnode.hpp"
    32 #include "opto/compile.hpp"
    33 #include "opto/connode.hpp"
    34 #include "opto/loopnode.hpp"
    35 #include "opto/machnode.hpp"
    36 #include "opto/matcher.hpp"
    37 #include "opto/memnode.hpp"
    38 #include "opto/mulnode.hpp"
    39 #include "opto/phaseX.hpp"
    40 #include "opto/regmask.hpp"
    42 // Portions of code courtesy of Clifford Click
    44 // Optimization - Graph Style
    46 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
    48 //=============================================================================
    49 uint MemNode::size_of() const { return sizeof(*this); }
    51 const TypePtr *MemNode::adr_type() const {
    52   Node* adr = in(Address);
    53   const TypePtr* cross_check = NULL;
    54   DEBUG_ONLY(cross_check = _adr_type);
    55   return calculate_adr_type(adr->bottom_type(), cross_check);
    56 }
    58 #ifndef PRODUCT
    59 void MemNode::dump_spec(outputStream *st) const {
    60   if (in(Address) == NULL)  return; // node is dead
    61 #ifndef ASSERT
    62   // fake the missing field
    63   const TypePtr* _adr_type = NULL;
    64   if (in(Address) != NULL)
    65     _adr_type = in(Address)->bottom_type()->isa_ptr();
    66 #endif
    67   dump_adr_type(this, _adr_type, st);
    69   Compile* C = Compile::current();
    70   if( C->alias_type(_adr_type)->is_volatile() )
    71     st->print(" Volatile!");
    72 }
    74 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
    75   st->print(" @");
    76   if (adr_type == NULL) {
    77     st->print("NULL");
    78   } else {
    79     adr_type->dump_on(st);
    80     Compile* C = Compile::current();
    81     Compile::AliasType* atp = NULL;
    82     if (C->have_alias_type(adr_type))  atp = C->alias_type(adr_type);
    83     if (atp == NULL)
    84       st->print(", idx=?\?;");
    85     else if (atp->index() == Compile::AliasIdxBot)
    86       st->print(", idx=Bot;");
    87     else if (atp->index() == Compile::AliasIdxTop)
    88       st->print(", idx=Top;");
    89     else if (atp->index() == Compile::AliasIdxRaw)
    90       st->print(", idx=Raw;");
    91     else {
    92       ciField* field = atp->field();
    93       if (field) {
    94         st->print(", name=");
    95         field->print_name_on(st);
    96       }
    97       st->print(", idx=%d;", atp->index());
    98     }
    99   }
   100 }
   102 extern void print_alias_types();
   104 #endif
   106 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) {
   107   assert((t_oop != NULL), "sanity");
   108   bool is_instance = t_oop->is_known_instance_field();
   109   bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() &&
   110                              (load != NULL) && load->is_Load() &&
   111                              (phase->is_IterGVN() != NULL);
   112   if (!(is_instance || is_boxed_value_load))
   113     return mchain;  // don't try to optimize non-instance types
   114   uint instance_id = t_oop->instance_id();
   115   Node *start_mem = phase->C->start()->proj_out(TypeFunc::Memory);
   116   Node *prev = NULL;
   117   Node *result = mchain;
   118   while (prev != result) {
   119     prev = result;
   120     if (result == start_mem)
   121       break;  // hit one of our sentinels
   122     // skip over a call which does not affect this memory slice
   123     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
   124       Node *proj_in = result->in(0);
   125       if (proj_in->is_Allocate() && proj_in->_idx == instance_id) {
   126         break;  // hit one of our sentinels
   127       } else if (proj_in->is_Call()) {
   128         CallNode *call = proj_in->as_Call();
   129         if (!call->may_modify(t_oop, phase)) { // returns false for instances
   130           result = call->in(TypeFunc::Memory);
   131         }
   132       } else if (proj_in->is_Initialize()) {
   133         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
   134         // Stop if this is the initialization for the object instance which
   135         // which contains this memory slice, otherwise skip over it.
   136         if ((alloc == NULL) || (alloc->_idx == instance_id)) {
   137           break;
   138         }
   139         if (is_instance) {
   140           result = proj_in->in(TypeFunc::Memory);
   141         } else if (is_boxed_value_load) {
   142           Node* klass = alloc->in(AllocateNode::KlassNode);
   143           const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr();
   144           if (tklass->klass_is_exact() && !tklass->klass()->equals(t_oop->klass())) {
   145             result = proj_in->in(TypeFunc::Memory); // not related allocation
   146           }
   147         }
   148       } else if (proj_in->is_MemBar()) {
   149         result = proj_in->in(TypeFunc::Memory);
   150       } else {
   151         assert(false, "unexpected projection");
   152       }
   153     } else if (result->is_ClearArray()) {
   154       if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) {
   155         // Can not bypass initialization of the instance
   156         // we are looking for.
   157         break;
   158       }
   159       // Otherwise skip it (the call updated 'result' value).
   160     } else if (result->is_MergeMem()) {
   161       result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, NULL, tty);
   162     }
   163   }
   164   return result;
   165 }
   167 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) {
   168   const TypeOopPtr* t_oop = t_adr->isa_oopptr();
   169   if (t_oop == NULL)
   170     return mchain;  // don't try to optimize non-oop types
   171   Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase);
   172   bool is_instance = t_oop->is_known_instance_field();
   173   PhaseIterGVN *igvn = phase->is_IterGVN();
   174   if (is_instance && igvn != NULL  && result->is_Phi()) {
   175     PhiNode *mphi = result->as_Phi();
   176     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
   177     const TypePtr *t = mphi->adr_type();
   178     if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ||
   179         t->isa_oopptr() && !t->is_oopptr()->is_known_instance() &&
   180         t->is_oopptr()->cast_to_exactness(true)
   181          ->is_oopptr()->cast_to_ptr_type(t_oop->ptr())
   182          ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop) {
   183       // clone the Phi with our address type
   184       result = mphi->split_out_instance(t_adr, igvn);
   185     } else {
   186       assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
   187     }
   188   }
   189   return result;
   190 }
   192 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
   193   uint alias_idx = phase->C->get_alias_index(tp);
   194   Node *mem = mmem;
   195 #ifdef ASSERT
   196   {
   197     // Check that current type is consistent with the alias index used during graph construction
   198     assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
   199     bool consistent =  adr_check == NULL || adr_check->empty() ||
   200                        phase->C->must_alias(adr_check, alias_idx );
   201     // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
   202     if( !consistent && adr_check != NULL && !adr_check->empty() &&
   203                tp->isa_aryptr() &&        tp->offset() == Type::OffsetBot &&
   204         adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
   205         ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
   206           adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
   207           adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
   208       // don't assert if it is dead code.
   209       consistent = true;
   210     }
   211     if( !consistent ) {
   212       st->print("alias_idx==%d, adr_check==", alias_idx);
   213       if( adr_check == NULL ) {
   214         st->print("NULL");
   215       } else {
   216         adr_check->dump();
   217       }
   218       st->cr();
   219       print_alias_types();
   220       assert(consistent, "adr_check must match alias idx");
   221     }
   222   }
   223 #endif
   224   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
   225   // means an array I have not precisely typed yet.  Do not do any
   226   // alias stuff with it any time soon.
   227   const TypeOopPtr *toop = tp->isa_oopptr();
   228   if( tp->base() != Type::AnyPtr &&
   229       !(toop &&
   230         toop->klass() != NULL &&
   231         toop->klass()->is_java_lang_Object() &&
   232         toop->offset() == Type::OffsetBot) ) {
   233     // compress paths and change unreachable cycles to TOP
   234     // If not, we can update the input infinitely along a MergeMem cycle
   235     // Equivalent code in PhiNode::Ideal
   236     Node* m  = phase->transform(mmem);
   237     // If transformed to a MergeMem, get the desired slice
   238     // Otherwise the returned node represents memory for every slice
   239     mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
   240     // Update input if it is progress over what we have now
   241   }
   242   return mem;
   243 }
   245 //--------------------------Ideal_common---------------------------------------
   246 // Look for degenerate control and memory inputs.  Bypass MergeMem inputs.
   247 // Unhook non-raw memories from complete (macro-expanded) initializations.
   248 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
   249   // If our control input is a dead region, kill all below the region
   250   Node *ctl = in(MemNode::Control);
   251   if (ctl && remove_dead_region(phase, can_reshape))
   252     return this;
   253   ctl = in(MemNode::Control);
   254   // Don't bother trying to transform a dead node
   255   if (ctl && ctl->is_top())  return NodeSentinel;
   257   PhaseIterGVN *igvn = phase->is_IterGVN();
   258   // Wait if control on the worklist.
   259   if (ctl && can_reshape && igvn != NULL) {
   260     Node* bol = NULL;
   261     Node* cmp = NULL;
   262     if (ctl->in(0)->is_If()) {
   263       assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity");
   264       bol = ctl->in(0)->in(1);
   265       if (bol->is_Bool())
   266         cmp = ctl->in(0)->in(1)->in(1);
   267     }
   268     if (igvn->_worklist.member(ctl) ||
   269         (bol != NULL && igvn->_worklist.member(bol)) ||
   270         (cmp != NULL && igvn->_worklist.member(cmp)) ) {
   271       // This control path may be dead.
   272       // Delay this memory node transformation until the control is processed.
   273       phase->is_IterGVN()->_worklist.push(this);
   274       return NodeSentinel; // caller will return NULL
   275     }
   276   }
   277   // Ignore if memory is dead, or self-loop
   278   Node *mem = in(MemNode::Memory);
   279   if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return NULL
   280   assert(mem != this, "dead loop in MemNode::Ideal");
   282   if (can_reshape && igvn != NULL && igvn->_worklist.member(mem)) {
   283     // This memory slice may be dead.
   284     // Delay this mem node transformation until the memory is processed.
   285     phase->is_IterGVN()->_worklist.push(this);
   286     return NodeSentinel; // caller will return NULL
   287   }
   289   Node *address = in(MemNode::Address);
   290   const Type *t_adr = phase->type(address);
   291   if (t_adr == Type::TOP)              return NodeSentinel; // caller will return NULL
   293   if (can_reshape && igvn != NULL &&
   294       (igvn->_worklist.member(address) ||
   295        igvn->_worklist.size() > 0 && (t_adr != adr_type())) ) {
   296     // The address's base and type may change when the address is processed.
   297     // Delay this mem node transformation until the address is processed.
   298     phase->is_IterGVN()->_worklist.push(this);
   299     return NodeSentinel; // caller will return NULL
   300   }
   302   // Do NOT remove or optimize the next lines: ensure a new alias index
   303   // is allocated for an oop pointer type before Escape Analysis.
   304   // Note: C++ will not remove it since the call has side effect.
   305   if (t_adr->isa_oopptr()) {
   306     int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
   307   }
   309   Node* base = NULL;
   310   if (address->is_AddP()) {
   311     base = address->in(AddPNode::Base);
   312   }
   313   if (base != NULL && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
   314       !t_adr->isa_rawptr()) {
   315     // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
   316     // Skip this node optimization if its address has TOP base.
   317     return NodeSentinel; // caller will return NULL
   318   }
   320   // Avoid independent memory operations
   321   Node* old_mem = mem;
   323   // The code which unhooks non-raw memories from complete (macro-expanded)
   324   // initializations was removed. After macro-expansion all stores catched
   325   // by Initialize node became raw stores and there is no information
   326   // which memory slices they modify. So it is unsafe to move any memory
   327   // operation above these stores. Also in most cases hooked non-raw memories
   328   // were already unhooked by using information from detect_ptr_independence()
   329   // and find_previous_store().
   331   if (mem->is_MergeMem()) {
   332     MergeMemNode* mmem = mem->as_MergeMem();
   333     const TypePtr *tp = t_adr->is_ptr();
   335     mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
   336   }
   338   if (mem != old_mem) {
   339     set_req(MemNode::Memory, mem);
   340     if (can_reshape && old_mem->outcnt() == 0) {
   341         igvn->_worklist.push(old_mem);
   342     }
   343     if (phase->type( mem ) == Type::TOP) return NodeSentinel;
   344     return this;
   345   }
   347   // let the subclass continue analyzing...
   348   return NULL;
   349 }
   351 // Helper function for proving some simple control dominations.
   352 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
   353 // Already assumes that 'dom' is available at 'sub', and that 'sub'
   354 // is not a constant (dominated by the method's StartNode).
   355 // Used by MemNode::find_previous_store to prove that the
   356 // control input of a memory operation predates (dominates)
   357 // an allocation it wants to look past.
   358 bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
   359   if (dom == NULL || dom->is_top() || sub == NULL || sub->is_top())
   360     return false; // Conservative answer for dead code
   362   // Check 'dom'. Skip Proj and CatchProj nodes.
   363   dom = dom->find_exact_control(dom);
   364   if (dom == NULL || dom->is_top())
   365     return false; // Conservative answer for dead code
   367   if (dom == sub) {
   368     // For the case when, for example, 'sub' is Initialize and the original
   369     // 'dom' is Proj node of the 'sub'.
   370     return false;
   371   }
   373   if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub)
   374     return true;
   376   // 'dom' dominates 'sub' if its control edge and control edges
   377   // of all its inputs dominate or equal to sub's control edge.
   379   // Currently 'sub' is either Allocate, Initialize or Start nodes.
   380   // Or Region for the check in LoadNode::Ideal();
   381   // 'sub' should have sub->in(0) != NULL.
   382   assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() ||
   383          sub->is_Region() || sub->is_Call(), "expecting only these nodes");
   385   // Get control edge of 'sub'.
   386   Node* orig_sub = sub;
   387   sub = sub->find_exact_control(sub->in(0));
   388   if (sub == NULL || sub->is_top())
   389     return false; // Conservative answer for dead code
   391   assert(sub->is_CFG(), "expecting control");
   393   if (sub == dom)
   394     return true;
   396   if (sub->is_Start() || sub->is_Root())
   397     return false;
   399   {
   400     // Check all control edges of 'dom'.
   402     ResourceMark rm;
   403     Arena* arena = Thread::current()->resource_area();
   404     Node_List nlist(arena);
   405     Unique_Node_List dom_list(arena);
   407     dom_list.push(dom);
   408     bool only_dominating_controls = false;
   410     for (uint next = 0; next < dom_list.size(); next++) {
   411       Node* n = dom_list.at(next);
   412       if (n == orig_sub)
   413         return false; // One of dom's inputs dominated by sub.
   414       if (!n->is_CFG() && n->pinned()) {
   415         // Check only own control edge for pinned non-control nodes.
   416         n = n->find_exact_control(n->in(0));
   417         if (n == NULL || n->is_top())
   418           return false; // Conservative answer for dead code
   419         assert(n->is_CFG(), "expecting control");
   420         dom_list.push(n);
   421       } else if (n->is_Con() || n->is_Start() || n->is_Root()) {
   422         only_dominating_controls = true;
   423       } else if (n->is_CFG()) {
   424         if (n->dominates(sub, nlist))
   425           only_dominating_controls = true;
   426         else
   427           return false;
   428       } else {
   429         // First, own control edge.
   430         Node* m = n->find_exact_control(n->in(0));
   431         if (m != NULL) {
   432           if (m->is_top())
   433             return false; // Conservative answer for dead code
   434           dom_list.push(m);
   435         }
   436         // Now, the rest of edges.
   437         uint cnt = n->req();
   438         for (uint i = 1; i < cnt; i++) {
   439           m = n->find_exact_control(n->in(i));
   440           if (m == NULL || m->is_top())
   441             continue;
   442           dom_list.push(m);
   443         }
   444       }
   445     }
   446     return only_dominating_controls;
   447   }
   448 }
   450 //---------------------detect_ptr_independence---------------------------------
   451 // Used by MemNode::find_previous_store to prove that two base
   452 // pointers are never equal.
   453 // The pointers are accompanied by their associated allocations,
   454 // if any, which have been previously discovered by the caller.
   455 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
   456                                       Node* p2, AllocateNode* a2,
   457                                       PhaseTransform* phase) {
   458   // Attempt to prove that these two pointers cannot be aliased.
   459   // They may both manifestly be allocations, and they should differ.
   460   // Or, if they are not both allocations, they can be distinct constants.
   461   // Otherwise, one is an allocation and the other a pre-existing value.
   462   if (a1 == NULL && a2 == NULL) {           // neither an allocation
   463     return (p1 != p2) && p1->is_Con() && p2->is_Con();
   464   } else if (a1 != NULL && a2 != NULL) {    // both allocations
   465     return (a1 != a2);
   466   } else if (a1 != NULL) {                  // one allocation a1
   467     // (Note:  p2->is_Con implies p2->in(0)->is_Root, which dominates.)
   468     return all_controls_dominate(p2, a1);
   469   } else { //(a2 != NULL)                   // one allocation a2
   470     return all_controls_dominate(p1, a2);
   471   }
   472   return false;
   473 }
   476 // The logic for reordering loads and stores uses four steps:
   477 // (a) Walk carefully past stores and initializations which we
   478 //     can prove are independent of this load.
   479 // (b) Observe that the next memory state makes an exact match
   480 //     with self (load or store), and locate the relevant store.
   481 // (c) Ensure that, if we were to wire self directly to the store,
   482 //     the optimizer would fold it up somehow.
   483 // (d) Do the rewiring, and return, depending on some other part of
   484 //     the optimizer to fold up the load.
   485 // This routine handles steps (a) and (b).  Steps (c) and (d) are
   486 // specific to loads and stores, so they are handled by the callers.
   487 // (Currently, only LoadNode::Ideal has steps (c), (d).  More later.)
   488 //
   489 Node* MemNode::find_previous_store(PhaseTransform* phase) {
   490   Node*         ctrl   = in(MemNode::Control);
   491   Node*         adr    = in(MemNode::Address);
   492   intptr_t      offset = 0;
   493   Node*         base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
   494   AllocateNode* alloc  = AllocateNode::Ideal_allocation(base, phase);
   496   if (offset == Type::OffsetBot)
   497     return NULL;            // cannot unalias unless there are precise offsets
   499   const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
   501   intptr_t size_in_bytes = memory_size();
   503   Node* mem = in(MemNode::Memory);   // start searching here...
   505   int cnt = 50;             // Cycle limiter
   506   for (;;) {                // While we can dance past unrelated stores...
   507     if (--cnt < 0)  break;  // Caught in cycle or a complicated dance?
   509     if (mem->is_Store()) {
   510       Node* st_adr = mem->in(MemNode::Address);
   511       intptr_t st_offset = 0;
   512       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
   513       if (st_base == NULL)
   514         break;              // inscrutable pointer
   515       if (st_offset != offset && st_offset != Type::OffsetBot) {
   516         const int MAX_STORE = BytesPerLong;
   517         if (st_offset >= offset + size_in_bytes ||
   518             st_offset <= offset - MAX_STORE ||
   519             st_offset <= offset - mem->as_Store()->memory_size()) {
   520           // Success:  The offsets are provably independent.
   521           // (You may ask, why not just test st_offset != offset and be done?
   522           // The answer is that stores of different sizes can co-exist
   523           // in the same sequence of RawMem effects.  We sometimes initialize
   524           // a whole 'tile' of array elements with a single jint or jlong.)
   525           mem = mem->in(MemNode::Memory);
   526           continue;           // (a) advance through independent store memory
   527         }
   528       }
   529       if (st_base != base &&
   530           detect_ptr_independence(base, alloc,
   531                                   st_base,
   532                                   AllocateNode::Ideal_allocation(st_base, phase),
   533                                   phase)) {
   534         // Success:  The bases are provably independent.
   535         mem = mem->in(MemNode::Memory);
   536         continue;           // (a) advance through independent store memory
   537       }
   539       // (b) At this point, if the bases or offsets do not agree, we lose,
   540       // since we have not managed to prove 'this' and 'mem' independent.
   541       if (st_base == base && st_offset == offset) {
   542         return mem;         // let caller handle steps (c), (d)
   543       }
   545     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
   546       InitializeNode* st_init = mem->in(0)->as_Initialize();
   547       AllocateNode*  st_alloc = st_init->allocation();
   548       if (st_alloc == NULL)
   549         break;              // something degenerated
   550       bool known_identical = false;
   551       bool known_independent = false;
   552       if (alloc == st_alloc)
   553         known_identical = true;
   554       else if (alloc != NULL)
   555         known_independent = true;
   556       else if (all_controls_dominate(this, st_alloc))
   557         known_independent = true;
   559       if (known_independent) {
   560         // The bases are provably independent: Either they are
   561         // manifestly distinct allocations, or else the control
   562         // of this load dominates the store's allocation.
   563         int alias_idx = phase->C->get_alias_index(adr_type());
   564         if (alias_idx == Compile::AliasIdxRaw) {
   565           mem = st_alloc->in(TypeFunc::Memory);
   566         } else {
   567           mem = st_init->memory(alias_idx);
   568         }
   569         continue;           // (a) advance through independent store memory
   570       }
   572       // (b) at this point, if we are not looking at a store initializing
   573       // the same allocation we are loading from, we lose.
   574       if (known_identical) {
   575         // From caller, can_see_stored_value will consult find_captured_store.
   576         return mem;         // let caller handle steps (c), (d)
   577       }
   579     } else if (addr_t != NULL && addr_t->is_known_instance_field()) {
   580       // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
   581       if (mem->is_Proj() && mem->in(0)->is_Call()) {
   582         CallNode *call = mem->in(0)->as_Call();
   583         if (!call->may_modify(addr_t, phase)) {
   584           mem = call->in(TypeFunc::Memory);
   585           continue;         // (a) advance through independent call memory
   586         }
   587       } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
   588         mem = mem->in(0)->in(TypeFunc::Memory);
   589         continue;           // (a) advance through independent MemBar memory
   590       } else if (mem->is_ClearArray()) {
   591         if (ClearArrayNode::step_through(&mem, (uint)addr_t->instance_id(), phase)) {
   592           // (the call updated 'mem' value)
   593           continue;         // (a) advance through independent allocation memory
   594         } else {
   595           // Can not bypass initialization of the instance
   596           // we are looking for.
   597           return mem;
   598         }
   599       } else if (mem->is_MergeMem()) {
   600         int alias_idx = phase->C->get_alias_index(adr_type());
   601         mem = mem->as_MergeMem()->memory_at(alias_idx);
   602         continue;           // (a) advance through independent MergeMem memory
   603       }
   604     }
   606     // Unless there is an explicit 'continue', we must bail out here,
   607     // because 'mem' is an inscrutable memory state (e.g., a call).
   608     break;
   609   }
   611   return NULL;              // bail out
   612 }
   614 //----------------------calculate_adr_type-------------------------------------
   615 // Helper function.  Notices when the given type of address hits top or bottom.
   616 // Also, asserts a cross-check of the type against the expected address type.
   617 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
   618   if (t == Type::TOP)  return NULL; // does not touch memory any more?
   619   #ifdef PRODUCT
   620   cross_check = NULL;
   621   #else
   622   if (!VerifyAliases || is_error_reported() || Node::in_dump())  cross_check = NULL;
   623   #endif
   624   const TypePtr* tp = t->isa_ptr();
   625   if (tp == NULL) {
   626     assert(cross_check == NULL || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
   627     return TypePtr::BOTTOM;           // touches lots of memory
   628   } else {
   629     #ifdef ASSERT
   630     // %%%% [phh] We don't check the alias index if cross_check is
   631     //            TypeRawPtr::BOTTOM.  Needs to be investigated.
   632     if (cross_check != NULL &&
   633         cross_check != TypePtr::BOTTOM &&
   634         cross_check != TypeRawPtr::BOTTOM) {
   635       // Recheck the alias index, to see if it has changed (due to a bug).
   636       Compile* C = Compile::current();
   637       assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
   638              "must stay in the original alias category");
   639       // The type of the address must be contained in the adr_type,
   640       // disregarding "null"-ness.
   641       // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
   642       const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
   643       assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(),
   644              "real address must not escape from expected memory type");
   645     }
   646     #endif
   647     return tp;
   648   }
   649 }
   651 //------------------------adr_phi_is_loop_invariant----------------------------
   652 // A helper function for Ideal_DU_postCCP to check if a Phi in a counted
   653 // loop is loop invariant. Make a quick traversal of Phi and associated
   654 // CastPP nodes, looking to see if they are a closed group within the loop.
   655 bool MemNode::adr_phi_is_loop_invariant(Node* adr_phi, Node* cast) {
   656   // The idea is that the phi-nest must boil down to only CastPP nodes
   657   // with the same data. This implies that any path into the loop already
   658   // includes such a CastPP, and so the original cast, whatever its input,
   659   // must be covered by an equivalent cast, with an earlier control input.
   660   ResourceMark rm;
   662   // The loop entry input of the phi should be the unique dominating
   663   // node for every Phi/CastPP in the loop.
   664   Unique_Node_List closure;
   665   closure.push(adr_phi->in(LoopNode::EntryControl));
   667   // Add the phi node and the cast to the worklist.
   668   Unique_Node_List worklist;
   669   worklist.push(adr_phi);
   670   if( cast != NULL ){
   671     if( !cast->is_ConstraintCast() ) return false;
   672     worklist.push(cast);
   673   }
   675   // Begin recursive walk of phi nodes.
   676   while( worklist.size() ){
   677     // Take a node off the worklist
   678     Node *n = worklist.pop();
   679     if( !closure.member(n) ){
   680       // Add it to the closure.
   681       closure.push(n);
   682       // Make a sanity check to ensure we don't waste too much time here.
   683       if( closure.size() > 20) return false;
   684       // This node is OK if:
   685       //  - it is a cast of an identical value
   686       //  - or it is a phi node (then we add its inputs to the worklist)
   687       // Otherwise, the node is not OK, and we presume the cast is not invariant
   688       if( n->is_ConstraintCast() ){
   689         worklist.push(n->in(1));
   690       } else if( n->is_Phi() ) {
   691         for( uint i = 1; i < n->req(); i++ ) {
   692           worklist.push(n->in(i));
   693         }
   694       } else {
   695         return false;
   696       }
   697     }
   698   }
   700   // Quit when the worklist is empty, and we've found no offending nodes.
   701   return true;
   702 }
   704 //------------------------------Ideal_DU_postCCP-------------------------------
   705 // Find any cast-away of null-ness and keep its control.  Null cast-aways are
   706 // going away in this pass and we need to make this memory op depend on the
   707 // gating null check.
   708 Node *MemNode::Ideal_DU_postCCP( PhaseCCP *ccp ) {
   709   return Ideal_common_DU_postCCP(ccp, this, in(MemNode::Address));
   710 }
   712 // I tried to leave the CastPP's in.  This makes the graph more accurate in
   713 // some sense; we get to keep around the knowledge that an oop is not-null
   714 // after some test.  Alas, the CastPP's interfere with GVN (some values are
   715 // the regular oop, some are the CastPP of the oop, all merge at Phi's which
   716 // cannot collapse, etc).  This cost us 10% on SpecJVM, even when I removed
   717 // some of the more trivial cases in the optimizer.  Removing more useless
   718 // Phi's started allowing Loads to illegally float above null checks.  I gave
   719 // up on this approach.  CNC 10/20/2000
   720 // This static method may be called not from MemNode (EncodePNode calls it).
   721 // Only the control edge of the node 'n' might be updated.
   722 Node *MemNode::Ideal_common_DU_postCCP( PhaseCCP *ccp, Node* n, Node* adr ) {
   723   Node *skipped_cast = NULL;
   724   // Need a null check?  Regular static accesses do not because they are
   725   // from constant addresses.  Array ops are gated by the range check (which
   726   // always includes a NULL check).  Just check field ops.
   727   if( n->in(MemNode::Control) == NULL ) {
   728     // Scan upwards for the highest location we can place this memory op.
   729     while( true ) {
   730       switch( adr->Opcode() ) {
   732       case Op_AddP:             // No change to NULL-ness, so peek thru AddP's
   733         adr = adr->in(AddPNode::Base);
   734         continue;
   736       case Op_DecodeN:         // No change to NULL-ness, so peek thru
   737       case Op_DecodeNKlass:
   738         adr = adr->in(1);
   739         continue;
   741       case Op_EncodeP:
   742       case Op_EncodePKlass:
   743         // EncodeP node's control edge could be set by this method
   744         // when EncodeP node depends on CastPP node.
   745         //
   746         // Use its control edge for memory op because EncodeP may go away
   747         // later when it is folded with following or preceding DecodeN node.
   748         if (adr->in(0) == NULL) {
   749           // Keep looking for cast nodes.
   750           adr = adr->in(1);
   751           continue;
   752         }
   753         ccp->hash_delete(n);
   754         n->set_req(MemNode::Control, adr->in(0));
   755         ccp->hash_insert(n);
   756         return n;
   758       case Op_CastPP:
   759         // If the CastPP is useless, just peek on through it.
   760         if( ccp->type(adr) == ccp->type(adr->in(1)) ) {
   761           // Remember the cast that we've peeked though. If we peek
   762           // through more than one, then we end up remembering the highest
   763           // one, that is, if in a loop, the one closest to the top.
   764           skipped_cast = adr;
   765           adr = adr->in(1);
   766           continue;
   767         }
   768         // CastPP is going away in this pass!  We need this memory op to be
   769         // control-dependent on the test that is guarding the CastPP.
   770         ccp->hash_delete(n);
   771         n->set_req(MemNode::Control, adr->in(0));
   772         ccp->hash_insert(n);
   773         return n;
   775       case Op_Phi:
   776         // Attempt to float above a Phi to some dominating point.
   777         if (adr->in(0) != NULL && adr->in(0)->is_CountedLoop()) {
   778           // If we've already peeked through a Cast (which could have set the
   779           // control), we can't float above a Phi, because the skipped Cast
   780           // may not be loop invariant.
   781           if (adr_phi_is_loop_invariant(adr, skipped_cast)) {
   782             adr = adr->in(1);
   783             continue;
   784           }
   785         }
   787         // Intentional fallthrough!
   789         // No obvious dominating point.  The mem op is pinned below the Phi
   790         // by the Phi itself.  If the Phi goes away (no true value is merged)
   791         // then the mem op can float, but not indefinitely.  It must be pinned
   792         // behind the controls leading to the Phi.
   793       case Op_CheckCastPP:
   794         // These usually stick around to change address type, however a
   795         // useless one can be elided and we still need to pick up a control edge
   796         if (adr->in(0) == NULL) {
   797           // This CheckCastPP node has NO control and is likely useless. But we
   798           // need check further up the ancestor chain for a control input to keep
   799           // the node in place. 4959717.
   800           skipped_cast = adr;
   801           adr = adr->in(1);
   802           continue;
   803         }
   804         ccp->hash_delete(n);
   805         n->set_req(MemNode::Control, adr->in(0));
   806         ccp->hash_insert(n);
   807         return n;
   809         // List of "safe" opcodes; those that implicitly block the memory
   810         // op below any null check.
   811       case Op_CastX2P:          // no null checks on native pointers
   812       case Op_Parm:             // 'this' pointer is not null
   813       case Op_LoadP:            // Loading from within a klass
   814       case Op_LoadN:            // Loading from within a klass
   815       case Op_LoadKlass:        // Loading from within a klass
   816       case Op_LoadNKlass:       // Loading from within a klass
   817       case Op_ConP:             // Loading from a klass
   818       case Op_ConN:             // Loading from a klass
   819       case Op_ConNKlass:        // Loading from a klass
   820       case Op_CreateEx:         // Sucking up the guts of an exception oop
   821       case Op_Con:              // Reading from TLS
   822       case Op_CMoveP:           // CMoveP is pinned
   823       case Op_CMoveN:           // CMoveN is pinned
   824         break;                  // No progress
   826       case Op_Proj:             // Direct call to an allocation routine
   827       case Op_SCMemProj:        // Memory state from store conditional ops
   828 #ifdef ASSERT
   829         {
   830           assert(adr->as_Proj()->_con == TypeFunc::Parms, "must be return value");
   831           const Node* call = adr->in(0);
   832           if (call->is_CallJava()) {
   833             const CallJavaNode* call_java = call->as_CallJava();
   834             const TypeTuple *r = call_java->tf()->range();
   835             assert(r->cnt() > TypeFunc::Parms, "must return value");
   836             const Type* ret_type = r->field_at(TypeFunc::Parms);
   837             assert(ret_type && ret_type->isa_ptr(), "must return pointer");
   838             // We further presume that this is one of
   839             // new_instance_Java, new_array_Java, or
   840             // the like, but do not assert for this.
   841           } else if (call->is_Allocate()) {
   842             // similar case to new_instance_Java, etc.
   843           } else if (!call->is_CallLeaf()) {
   844             // Projections from fetch_oop (OSR) are allowed as well.
   845             ShouldNotReachHere();
   846           }
   847         }
   848 #endif
   849         break;
   850       default:
   851         ShouldNotReachHere();
   852       }
   853       break;
   854     }
   855   }
   857   return  NULL;               // No progress
   858 }
   861 //=============================================================================
   862 // Should LoadNode::Ideal() attempt to remove control edges?
   863 bool LoadNode::can_remove_control() const {
   864   return true;
   865 }
   866 uint LoadNode::size_of() const { return sizeof(*this); }
   867 uint LoadNode::cmp( const Node &n ) const
   868 { return !Type::cmp( _type, ((LoadNode&)n)._type ); }
   869 const Type *LoadNode::bottom_type() const { return _type; }
   870 uint LoadNode::ideal_reg() const {
   871   return _type->ideal_reg();
   872 }
   874 #ifndef PRODUCT
   875 void LoadNode::dump_spec(outputStream *st) const {
   876   MemNode::dump_spec(st);
   877   if( !Verbose && !WizardMode ) {
   878     // standard dump does this in Verbose and WizardMode
   879     st->print(" #"); _type->dump_on(st);
   880   }
   881   if (!_depends_only_on_test) {
   882     st->print(" (does not depend only on test)");
   883   }
   884 }
   885 #endif
   887 #ifdef ASSERT
   888 //----------------------------is_immutable_value-------------------------------
   889 // Helper function to allow a raw load without control edge for some cases
   890 bool LoadNode::is_immutable_value(Node* adr) {
   891   return (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() &&
   892           adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
   893           (adr->in(AddPNode::Offset)->find_intptr_t_con(-1) ==
   894            in_bytes(JavaThread::osthread_offset())));
   895 }
   896 #endif
   898 //----------------------------LoadNode::make-----------------------------------
   899 // Polymorphic factory method:
   900 Node *LoadNode::make(PhaseGVN& gvn, Node *ctl, Node *mem, Node *adr, const TypePtr* adr_type, const Type *rt, BasicType bt, MemOrd mo, ControlDependency control_dependency) {
   901   Compile* C = gvn.C;
   903   // sanity check the alias category against the created node type
   904   assert(!(adr_type->isa_oopptr() &&
   905            adr_type->offset() == oopDesc::klass_offset_in_bytes()),
   906          "use LoadKlassNode instead");
   907   assert(!(adr_type->isa_aryptr() &&
   908            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
   909          "use LoadRangeNode instead");
   910   // Check control edge of raw loads
   911   assert( ctl != NULL || C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
   912           // oop will be recorded in oop map if load crosses safepoint
   913           rt->isa_oopptr() || is_immutable_value(adr),
   914           "raw memory operations should have control edge");
   915   switch (bt) {
   916   case T_BOOLEAN: return new (C) LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
   917   case T_BYTE:    return new (C) LoadBNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
   918   case T_INT:     return new (C) LoadINode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
   919   case T_CHAR:    return new (C) LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
   920   case T_SHORT:   return new (C) LoadSNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency);
   921   case T_LONG:    return new (C) LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency);
   922   case T_FLOAT:   return new (C) LoadFNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency);
   923   case T_DOUBLE:  return new (C) LoadDNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency);
   924   case T_ADDRESS: return new (C) LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(),  mo, control_dependency);
   925   case T_OBJECT:
   926 #ifdef _LP64
   927     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
   928       Node* load  = gvn.transform(new (C) LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency));
   929       return new (C) DecodeNNode(load, load->bottom_type()->make_ptr());
   930     } else
   931 #endif
   932     {
   933       assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop");
   934       return new (C) LoadPNode(ctl, mem, adr, adr_type, rt->is_oopptr(), mo, control_dependency);
   935     }
   936   }
   937   ShouldNotReachHere();
   938   return (LoadNode*)NULL;
   939 }
   941 LoadLNode* LoadLNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo, ControlDependency control_dependency) {
   942   bool require_atomic = true;
   943   return new (C) LoadLNode(ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic);
   944 }
   946 LoadDNode* LoadDNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo, ControlDependency control_dependency) {
   947   bool require_atomic = true;
   948   return new (C) LoadDNode(ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic);
   949 }
   953 //------------------------------hash-------------------------------------------
   954 uint LoadNode::hash() const {
   955   // unroll addition of interesting fields
   956   return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
   957 }
   959 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) {
   960   if ((atp != NULL) && (atp->index() >= Compile::AliasIdxRaw)) {
   961     bool non_volatile = (atp->field() != NULL) && !atp->field()->is_volatile();
   962     bool is_stable_ary = FoldStableValues &&
   963                          (tp != NULL) && (tp->isa_aryptr() != NULL) &&
   964                          tp->isa_aryptr()->is_stable();
   966     return (eliminate_boxing && non_volatile) || is_stable_ary;
   967   }
   969   return false;
   970 }
   972 //---------------------------can_see_stored_value------------------------------
   973 // This routine exists to make sure this set of tests is done the same
   974 // everywhere.  We need to make a coordinated change: first LoadNode::Ideal
   975 // will change the graph shape in a way which makes memory alive twice at the
   976 // same time (uses the Oracle model of aliasing), then some
   977 // LoadXNode::Identity will fold things back to the equivalence-class model
   978 // of aliasing.
   979 Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
   980   Node* ld_adr = in(MemNode::Address);
   981   intptr_t ld_off = 0;
   982   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
   983   const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
   984   Compile::AliasType* atp = (tp != NULL) ? phase->C->alias_type(tp) : NULL;
   985   // This is more general than load from boxing objects.
   986   if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) {
   987     uint alias_idx = atp->index();
   988     bool final = !atp->is_rewritable();
   989     Node* result = NULL;
   990     Node* current = st;
   991     // Skip through chains of MemBarNodes checking the MergeMems for
   992     // new states for the slice of this load.  Stop once any other
   993     // kind of node is encountered.  Loads from final memory can skip
   994     // through any kind of MemBar but normal loads shouldn't skip
   995     // through MemBarAcquire since the could allow them to move out of
   996     // a synchronized region.
   997     while (current->is_Proj()) {
   998       int opc = current->in(0)->Opcode();
   999       if ((final && (opc == Op_MemBarAcquire ||
  1000                      opc == Op_MemBarAcquireLock ||
  1001                      opc == Op_LoadFence)) ||
  1002           opc == Op_MemBarRelease ||
  1003           opc == Op_StoreFence ||
  1004           opc == Op_MemBarReleaseLock ||
  1005           opc == Op_MemBarCPUOrder) {
  1006         Node* mem = current->in(0)->in(TypeFunc::Memory);
  1007         if (mem->is_MergeMem()) {
  1008           MergeMemNode* merge = mem->as_MergeMem();
  1009           Node* new_st = merge->memory_at(alias_idx);
  1010           if (new_st == merge->base_memory()) {
  1011             // Keep searching
  1012             current = new_st;
  1013             continue;
  1015           // Save the new memory state for the slice and fall through
  1016           // to exit.
  1017           result = new_st;
  1020       break;
  1022     if (result != NULL) {
  1023       st = result;
  1027   // Loop around twice in the case Load -> Initialize -> Store.
  1028   // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
  1029   for (int trip = 0; trip <= 1; trip++) {
  1031     if (st->is_Store()) {
  1032       Node* st_adr = st->in(MemNode::Address);
  1033       if (!phase->eqv(st_adr, ld_adr)) {
  1034         // Try harder before giving up...  Match raw and non-raw pointers.
  1035         intptr_t st_off = 0;
  1036         AllocateNode* alloc = AllocateNode::Ideal_allocation(st_adr, phase, st_off);
  1037         if (alloc == NULL)       return NULL;
  1038         if (alloc != ld_alloc)   return NULL;
  1039         if (ld_off != st_off)    return NULL;
  1040         // At this point we have proven something like this setup:
  1041         //  A = Allocate(...)
  1042         //  L = LoadQ(,  AddP(CastPP(, A.Parm),, #Off))
  1043         //  S = StoreQ(, AddP(,        A.Parm  , #Off), V)
  1044         // (Actually, we haven't yet proven the Q's are the same.)
  1045         // In other words, we are loading from a casted version of
  1046         // the same pointer-and-offset that we stored to.
  1047         // Thus, we are able to replace L by V.
  1049       // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
  1050       if (store_Opcode() != st->Opcode())
  1051         return NULL;
  1052       return st->in(MemNode::ValueIn);
  1055     // A load from a freshly-created object always returns zero.
  1056     // (This can happen after LoadNode::Ideal resets the load's memory input
  1057     // to find_captured_store, which returned InitializeNode::zero_memory.)
  1058     if (st->is_Proj() && st->in(0)->is_Allocate() &&
  1059         (st->in(0) == ld_alloc) &&
  1060         (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) {
  1061       // return a zero value for the load's basic type
  1062       // (This is one of the few places where a generic PhaseTransform
  1063       // can create new nodes.  Think of it as lazily manifesting
  1064       // virtually pre-existing constants.)
  1065       return phase->zerocon(memory_type());
  1068     // A load from an initialization barrier can match a captured store.
  1069     if (st->is_Proj() && st->in(0)->is_Initialize()) {
  1070       InitializeNode* init = st->in(0)->as_Initialize();
  1071       AllocateNode* alloc = init->allocation();
  1072       if ((alloc != NULL) && (alloc == ld_alloc)) {
  1073         // examine a captured store value
  1074         st = init->find_captured_store(ld_off, memory_size(), phase);
  1075         if (st != NULL)
  1076           continue;             // take one more trip around
  1080     // Load boxed value from result of valueOf() call is input parameter.
  1081     if (this->is_Load() && ld_adr->is_AddP() &&
  1082         (tp != NULL) && tp->is_ptr_to_boxed_value()) {
  1083       intptr_t ignore = 0;
  1084       Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore);
  1085       if (base != NULL && base->is_Proj() &&
  1086           base->as_Proj()->_con == TypeFunc::Parms &&
  1087           base->in(0)->is_CallStaticJava() &&
  1088           base->in(0)->as_CallStaticJava()->is_boxing_method()) {
  1089         return base->in(0)->in(TypeFunc::Parms);
  1093     break;
  1096   return NULL;
  1099 //----------------------is_instance_field_load_with_local_phi------------------
  1100 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
  1101   if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl &&
  1102       in(Address)->is_AddP() ) {
  1103     const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr();
  1104     // Only instances and boxed values.
  1105     if( t_oop != NULL &&
  1106         (t_oop->is_ptr_to_boxed_value() ||
  1107          t_oop->is_known_instance_field()) &&
  1108         t_oop->offset() != Type::OffsetBot &&
  1109         t_oop->offset() != Type::OffsetTop) {
  1110       return true;
  1113   return false;
  1116 //------------------------------Identity---------------------------------------
  1117 // Loads are identity if previous store is to same address
  1118 Node *LoadNode::Identity( PhaseTransform *phase ) {
  1119   // If the previous store-maker is the right kind of Store, and the store is
  1120   // to the same address, then we are equal to the value stored.
  1121   Node* mem = in(Memory);
  1122   Node* value = can_see_stored_value(mem, phase);
  1123   if( value ) {
  1124     // byte, short & char stores truncate naturally.
  1125     // A load has to load the truncated value which requires
  1126     // some sort of masking operation and that requires an
  1127     // Ideal call instead of an Identity call.
  1128     if (memory_size() < BytesPerInt) {
  1129       // If the input to the store does not fit with the load's result type,
  1130       // it must be truncated via an Ideal call.
  1131       if (!phase->type(value)->higher_equal(phase->type(this)))
  1132         return this;
  1134     // (This works even when value is a Con, but LoadNode::Value
  1135     // usually runs first, producing the singleton type of the Con.)
  1136     return value;
  1139   // Search for an existing data phi which was generated before for the same
  1140   // instance's field to avoid infinite generation of phis in a loop.
  1141   Node *region = mem->in(0);
  1142   if (is_instance_field_load_with_local_phi(region)) {
  1143     const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr();
  1144     int this_index  = phase->C->get_alias_index(addr_t);
  1145     int this_offset = addr_t->offset();
  1146     int this_iid    = addr_t->instance_id();
  1147     if (!addr_t->is_known_instance() &&
  1148          addr_t->is_ptr_to_boxed_value()) {
  1149       // Use _idx of address base (could be Phi node) for boxed values.
  1150       intptr_t   ignore = 0;
  1151       Node*      base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
  1152       this_iid = base->_idx;
  1154     const Type* this_type = bottom_type();
  1155     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
  1156       Node* phi = region->fast_out(i);
  1157       if (phi->is_Phi() && phi != mem &&
  1158           phi->as_Phi()->is_same_inst_field(this_type, this_iid, this_index, this_offset)) {
  1159         return phi;
  1164   return this;
  1167 // We're loading from an object which has autobox behaviour.
  1168 // If this object is result of a valueOf call we'll have a phi
  1169 // merging a newly allocated object and a load from the cache.
  1170 // We want to replace this load with the original incoming
  1171 // argument to the valueOf call.
  1172 Node* LoadNode::eliminate_autobox(PhaseGVN* phase) {
  1173   assert(phase->C->eliminate_boxing(), "sanity");
  1174   intptr_t ignore = 0;
  1175   Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
  1176   if ((base == NULL) || base->is_Phi()) {
  1177     // Push the loads from the phi that comes from valueOf up
  1178     // through it to allow elimination of the loads and the recovery
  1179     // of the original value. It is done in split_through_phi().
  1180     return NULL;
  1181   } else if (base->is_Load() ||
  1182              base->is_DecodeN() && base->in(1)->is_Load()) {
  1183     // Eliminate the load of boxed value for integer types from the cache
  1184     // array by deriving the value from the index into the array.
  1185     // Capture the offset of the load and then reverse the computation.
  1187     // Get LoadN node which loads a boxing object from 'cache' array.
  1188     if (base->is_DecodeN()) {
  1189       base = base->in(1);
  1191     if (!base->in(Address)->is_AddP()) {
  1192       return NULL; // Complex address
  1194     AddPNode* address = base->in(Address)->as_AddP();
  1195     Node* cache_base = address->in(AddPNode::Base);
  1196     if ((cache_base != NULL) && cache_base->is_DecodeN()) {
  1197       // Get ConP node which is static 'cache' field.
  1198       cache_base = cache_base->in(1);
  1200     if ((cache_base != NULL) && cache_base->is_Con()) {
  1201       const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr();
  1202       if ((base_type != NULL) && base_type->is_autobox_cache()) {
  1203         Node* elements[4];
  1204         int shift = exact_log2(type2aelembytes(T_OBJECT));
  1205         int count = address->unpack_offsets(elements, ARRAY_SIZE(elements));
  1206         if ((count >  0) && elements[0]->is_Con() &&
  1207             ((count == 1) ||
  1208              (count == 2) && elements[1]->Opcode() == Op_LShiftX &&
  1209                              elements[1]->in(2) == phase->intcon(shift))) {
  1210           ciObjArray* array = base_type->const_oop()->as_obj_array();
  1211           // Fetch the box object cache[0] at the base of the array and get its value
  1212           ciInstance* box = array->obj_at(0)->as_instance();
  1213           ciInstanceKlass* ik = box->klass()->as_instance_klass();
  1214           assert(ik->is_box_klass(), "sanity");
  1215           assert(ik->nof_nonstatic_fields() == 1, "change following code");
  1216           if (ik->nof_nonstatic_fields() == 1) {
  1217             // This should be true nonstatic_field_at requires calling
  1218             // nof_nonstatic_fields so check it anyway
  1219             ciConstant c = box->field_value(ik->nonstatic_field_at(0));
  1220             BasicType bt = c.basic_type();
  1221             // Only integer types have boxing cache.
  1222             assert(bt == T_BOOLEAN || bt == T_CHAR  ||
  1223                    bt == T_BYTE    || bt == T_SHORT ||
  1224                    bt == T_INT     || bt == T_LONG, err_msg_res("wrong type = %s", type2name(bt)));
  1225             jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int();
  1226             if (cache_low != (int)cache_low) {
  1227               return NULL; // should not happen since cache is array indexed by value
  1229             jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift);
  1230             if (offset != (int)offset) {
  1231               return NULL; // should not happen since cache is array indexed by value
  1233            // Add up all the offsets making of the address of the load
  1234             Node* result = elements[0];
  1235             for (int i = 1; i < count; i++) {
  1236               result = phase->transform(new (phase->C) AddXNode(result, elements[i]));
  1238             // Remove the constant offset from the address and then
  1239             result = phase->transform(new (phase->C) AddXNode(result, phase->MakeConX(-(int)offset)));
  1240             // remove the scaling of the offset to recover the original index.
  1241             if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) {
  1242               // Peel the shift off directly but wrap it in a dummy node
  1243               // since Ideal can't return existing nodes
  1244               result = new (phase->C) RShiftXNode(result->in(1), phase->intcon(0));
  1245             } else if (result->is_Add() && result->in(2)->is_Con() &&
  1246                        result->in(1)->Opcode() == Op_LShiftX &&
  1247                        result->in(1)->in(2) == phase->intcon(shift)) {
  1248               // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z)
  1249               // but for boxing cache access we know that X<<Z will not overflow
  1250               // (there is range check) so we do this optimizatrion by hand here.
  1251               Node* add_con = new (phase->C) RShiftXNode(result->in(2), phase->intcon(shift));
  1252               result = new (phase->C) AddXNode(result->in(1)->in(1), phase->transform(add_con));
  1253             } else {
  1254               result = new (phase->C) RShiftXNode(result, phase->intcon(shift));
  1256 #ifdef _LP64
  1257             if (bt != T_LONG) {
  1258               result = new (phase->C) ConvL2INode(phase->transform(result));
  1260 #else
  1261             if (bt == T_LONG) {
  1262               result = new (phase->C) ConvI2LNode(phase->transform(result));
  1264 #endif
  1265             // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
  1266             // Need to preserve unboxing load type if it is unsigned.
  1267             switch(this->Opcode()) {
  1268               case Op_LoadUB:
  1269                 result = new (phase->C) AndINode(phase->transform(result), phase->intcon(0xFF));
  1270                 break;
  1271               case Op_LoadUS:
  1272                 result = new (phase->C) AndINode(phase->transform(result), phase->intcon(0xFFFF));
  1273                 break;
  1275             return result;
  1281   return NULL;
  1284 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) {
  1285   Node* region = phi->in(0);
  1286   if (region == NULL) {
  1287     return false; // Wait stable graph
  1289   uint cnt = phi->req();
  1290   for (uint i = 1; i < cnt; i++) {
  1291     Node* rc = region->in(i);
  1292     if (rc == NULL || phase->type(rc) == Type::TOP)
  1293       return false; // Wait stable graph
  1294     Node* in = phi->in(i);
  1295     if (in == NULL || phase->type(in) == Type::TOP)
  1296       return false; // Wait stable graph
  1298   return true;
  1300 //------------------------------split_through_phi------------------------------
  1301 // Split instance or boxed field load through Phi.
  1302 Node *LoadNode::split_through_phi(PhaseGVN *phase) {
  1303   Node* mem     = in(Memory);
  1304   Node* address = in(Address);
  1305   const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr();
  1307   assert((t_oop != NULL) &&
  1308          (t_oop->is_known_instance_field() ||
  1309           t_oop->is_ptr_to_boxed_value()), "invalide conditions");
  1311   Compile* C = phase->C;
  1312   intptr_t ignore = 0;
  1313   Node*    base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
  1314   bool base_is_phi = (base != NULL) && base->is_Phi();
  1315   bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() &&
  1316                            (base != NULL) && (base == address->in(AddPNode::Base)) &&
  1317                            phase->type(base)->higher_equal(TypePtr::NOTNULL);
  1319   if (!((mem->is_Phi() || base_is_phi) &&
  1320         (load_boxed_values || t_oop->is_known_instance_field()))) {
  1321     return NULL; // memory is not Phi
  1324   if (mem->is_Phi()) {
  1325     if (!stable_phi(mem->as_Phi(), phase)) {
  1326       return NULL; // Wait stable graph
  1328     uint cnt = mem->req();
  1329     // Check for loop invariant memory.
  1330     if (cnt == 3) {
  1331       for (uint i = 1; i < cnt; i++) {
  1332         Node* in = mem->in(i);
  1333         Node*  m = optimize_memory_chain(in, t_oop, this, phase);
  1334         if (m == mem) {
  1335           set_req(Memory, mem->in(cnt - i));
  1336           return this; // made change
  1341   if (base_is_phi) {
  1342     if (!stable_phi(base->as_Phi(), phase)) {
  1343       return NULL; // Wait stable graph
  1345     uint cnt = base->req();
  1346     // Check for loop invariant memory.
  1347     if (cnt == 3) {
  1348       for (uint i = 1; i < cnt; i++) {
  1349         if (base->in(i) == base) {
  1350           return NULL; // Wait stable graph
  1356   bool load_boxed_phi = load_boxed_values && base_is_phi && (base->in(0) == mem->in(0));
  1358   // Split through Phi (see original code in loopopts.cpp).
  1359   assert(C->have_alias_type(t_oop), "instance should have alias type");
  1361   // Do nothing here if Identity will find a value
  1362   // (to avoid infinite chain of value phis generation).
  1363   if (!phase->eqv(this, this->Identity(phase)))
  1364     return NULL;
  1366   // Select Region to split through.
  1367   Node* region;
  1368   if (!base_is_phi) {
  1369     assert(mem->is_Phi(), "sanity");
  1370     region = mem->in(0);
  1371     // Skip if the region dominates some control edge of the address.
  1372     if (!MemNode::all_controls_dominate(address, region))
  1373       return NULL;
  1374   } else if (!mem->is_Phi()) {
  1375     assert(base_is_phi, "sanity");
  1376     region = base->in(0);
  1377     // Skip if the region dominates some control edge of the memory.
  1378     if (!MemNode::all_controls_dominate(mem, region))
  1379       return NULL;
  1380   } else if (base->in(0) != mem->in(0)) {
  1381     assert(base_is_phi && mem->is_Phi(), "sanity");
  1382     if (MemNode::all_controls_dominate(mem, base->in(0))) {
  1383       region = base->in(0);
  1384     } else if (MemNode::all_controls_dominate(address, mem->in(0))) {
  1385       region = mem->in(0);
  1386     } else {
  1387       return NULL; // complex graph
  1389   } else {
  1390     assert(base->in(0) == mem->in(0), "sanity");
  1391     region = mem->in(0);
  1394   const Type* this_type = this->bottom_type();
  1395   int this_index  = C->get_alias_index(t_oop);
  1396   int this_offset = t_oop->offset();
  1397   int this_iid    = t_oop->instance_id();
  1398   if (!t_oop->is_known_instance() && load_boxed_values) {
  1399     // Use _idx of address base for boxed values.
  1400     this_iid = base->_idx;
  1402   PhaseIterGVN* igvn = phase->is_IterGVN();
  1403   Node* phi = new (C) PhiNode(region, this_type, NULL, this_iid, this_index, this_offset);
  1404   for (uint i = 1; i < region->req(); i++) {
  1405     Node* x;
  1406     Node* the_clone = NULL;
  1407     if (region->in(i) == C->top()) {
  1408       x = C->top();      // Dead path?  Use a dead data op
  1409     } else {
  1410       x = this->clone();        // Else clone up the data op
  1411       the_clone = x;            // Remember for possible deletion.
  1412       // Alter data node to use pre-phi inputs
  1413       if (this->in(0) == region) {
  1414         x->set_req(0, region->in(i));
  1415       } else {
  1416         x->set_req(0, NULL);
  1418       if (mem->is_Phi() && (mem->in(0) == region)) {
  1419         x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone.
  1421       if (address->is_Phi() && address->in(0) == region) {
  1422         x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone
  1424       if (base_is_phi && (base->in(0) == region)) {
  1425         Node* base_x = base->in(i); // Clone address for loads from boxed objects.
  1426         Node* adr_x = phase->transform(new (C) AddPNode(base_x,base_x,address->in(AddPNode::Offset)));
  1427         x->set_req(Address, adr_x);
  1430     // Check for a 'win' on some paths
  1431     const Type *t = x->Value(igvn);
  1433     bool singleton = t->singleton();
  1435     // See comments in PhaseIdealLoop::split_thru_phi().
  1436     if (singleton && t == Type::TOP) {
  1437       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
  1440     if (singleton) {
  1441       x = igvn->makecon(t);
  1442     } else {
  1443       // We now call Identity to try to simplify the cloned node.
  1444       // Note that some Identity methods call phase->type(this).
  1445       // Make sure that the type array is big enough for
  1446       // our new node, even though we may throw the node away.
  1447       // (This tweaking with igvn only works because x is a new node.)
  1448       igvn->set_type(x, t);
  1449       // If x is a TypeNode, capture any more-precise type permanently into Node
  1450       // otherwise it will be not updated during igvn->transform since
  1451       // igvn->type(x) is set to x->Value() already.
  1452       x->raise_bottom_type(t);
  1453       Node *y = x->Identity(igvn);
  1454       if (y != x) {
  1455         x = y;
  1456       } else {
  1457         y = igvn->hash_find_insert(x);
  1458         if (y) {
  1459           x = y;
  1460         } else {
  1461           // Else x is a new node we are keeping
  1462           // We do not need register_new_node_with_optimizer
  1463           // because set_type has already been called.
  1464           igvn->_worklist.push(x);
  1468     if (x != the_clone && the_clone != NULL) {
  1469       igvn->remove_dead_node(the_clone);
  1471     phi->set_req(i, x);
  1473   // Record Phi
  1474   igvn->register_new_node_with_optimizer(phi);
  1475   return phi;
  1478 //------------------------------Ideal------------------------------------------
  1479 // If the load is from Field memory and the pointer is non-null, it might be possible to
  1480 // zero out the control input.
  1481 // If the offset is constant and the base is an object allocation,
  1482 // try to hook me up to the exact initializing store.
  1483 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  1484   Node* p = MemNode::Ideal_common(phase, can_reshape);
  1485   if (p)  return (p == NodeSentinel) ? NULL : p;
  1487   Node* ctrl    = in(MemNode::Control);
  1488   Node* address = in(MemNode::Address);
  1490   // Skip up past a SafePoint control.  Cannot do this for Stores because
  1491   // pointer stores & cardmarks must stay on the same side of a SafePoint.
  1492   if( ctrl != NULL && ctrl->Opcode() == Op_SafePoint &&
  1493       phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw ) {
  1494     ctrl = ctrl->in(0);
  1495     set_req(MemNode::Control,ctrl);
  1498   intptr_t ignore = 0;
  1499   Node*    base   = AddPNode::Ideal_base_and_offset(address, phase, ignore);
  1500   if (base != NULL
  1501       && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) {
  1502     // Check for useless control edge in some common special cases
  1503     if (in(MemNode::Control) != NULL
  1504         && can_remove_control()
  1505         && phase->type(base)->higher_equal(TypePtr::NOTNULL)
  1506         && all_controls_dominate(base, phase->C->start())) {
  1507       // A method-invariant, non-null address (constant or 'this' argument).
  1508       set_req(MemNode::Control, NULL);
  1512   Node* mem = in(MemNode::Memory);
  1513   const TypePtr *addr_t = phase->type(address)->isa_ptr();
  1515   if (can_reshape && (addr_t != NULL)) {
  1516     // try to optimize our memory input
  1517     Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase);
  1518     if (opt_mem != mem) {
  1519       set_req(MemNode::Memory, opt_mem);
  1520       if (phase->type( opt_mem ) == Type::TOP) return NULL;
  1521       return this;
  1523     const TypeOopPtr *t_oop = addr_t->isa_oopptr();
  1524     if ((t_oop != NULL) &&
  1525         (t_oop->is_known_instance_field() ||
  1526          t_oop->is_ptr_to_boxed_value())) {
  1527       PhaseIterGVN *igvn = phase->is_IterGVN();
  1528       if (igvn != NULL && igvn->_worklist.member(opt_mem)) {
  1529         // Delay this transformation until memory Phi is processed.
  1530         phase->is_IterGVN()->_worklist.push(this);
  1531         return NULL;
  1533       // Split instance field load through Phi.
  1534       Node* result = split_through_phi(phase);
  1535       if (result != NULL) return result;
  1537       if (t_oop->is_ptr_to_boxed_value()) {
  1538         Node* result = eliminate_autobox(phase);
  1539         if (result != NULL) return result;
  1544   // Check for prior store with a different base or offset; make Load
  1545   // independent.  Skip through any number of them.  Bail out if the stores
  1546   // are in an endless dead cycle and report no progress.  This is a key
  1547   // transform for Reflection.  However, if after skipping through the Stores
  1548   // we can't then fold up against a prior store do NOT do the transform as
  1549   // this amounts to using the 'Oracle' model of aliasing.  It leaves the same
  1550   // array memory alive twice: once for the hoisted Load and again after the
  1551   // bypassed Store.  This situation only works if EVERYBODY who does
  1552   // anti-dependence work knows how to bypass.  I.e. we need all
  1553   // anti-dependence checks to ask the same Oracle.  Right now, that Oracle is
  1554   // the alias index stuff.  So instead, peek through Stores and IFF we can
  1555   // fold up, do so.
  1556   Node* prev_mem = find_previous_store(phase);
  1557   // Steps (a), (b):  Walk past independent stores to find an exact match.
  1558   if (prev_mem != NULL && prev_mem != in(MemNode::Memory)) {
  1559     // (c) See if we can fold up on the spot, but don't fold up here.
  1560     // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or
  1561     // just return a prior value, which is done by Identity calls.
  1562     if (can_see_stored_value(prev_mem, phase)) {
  1563       // Make ready for step (d):
  1564       set_req(MemNode::Memory, prev_mem);
  1565       return this;
  1569   return NULL;                  // No further progress
  1572 // Helper to recognize certain Klass fields which are invariant across
  1573 // some group of array types (e.g., int[] or all T[] where T < Object).
  1574 const Type*
  1575 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
  1576                                  ciKlass* klass) const {
  1577   if (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) {
  1578     // The field is Klass::_modifier_flags.  Return its (constant) value.
  1579     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
  1580     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
  1581     return TypeInt::make(klass->modifier_flags());
  1583   if (tkls->offset() == in_bytes(Klass::access_flags_offset())) {
  1584     // The field is Klass::_access_flags.  Return its (constant) value.
  1585     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
  1586     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
  1587     return TypeInt::make(klass->access_flags());
  1589   if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
  1590     // The field is Klass::_layout_helper.  Return its constant value if known.
  1591     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
  1592     return TypeInt::make(klass->layout_helper());
  1595   // No match.
  1596   return NULL;
  1599 // Try to constant-fold a stable array element.
  1600 static const Type* fold_stable_ary_elem(const TypeAryPtr* ary, int off, BasicType loadbt) {
  1601   assert(ary->const_oop(), "array should be constant");
  1602   assert(ary->is_stable(), "array should be stable");
  1604   // Decode the results of GraphKit::array_element_address.
  1605   ciArray* aobj = ary->const_oop()->as_array();
  1606   ciConstant con = aobj->element_value_by_offset(off);
  1608   if (con.basic_type() != T_ILLEGAL && !con.is_null_or_zero()) {
  1609     const Type* con_type = Type::make_from_constant(con);
  1610     if (con_type != NULL) {
  1611       if (con_type->isa_aryptr()) {
  1612         // Join with the array element type, in case it is also stable.
  1613         int dim = ary->stable_dimension();
  1614         con_type = con_type->is_aryptr()->cast_to_stable(true, dim-1);
  1616       if (loadbt == T_NARROWOOP && con_type->isa_oopptr()) {
  1617         con_type = con_type->make_narrowoop();
  1619 #ifndef PRODUCT
  1620       if (TraceIterativeGVN) {
  1621         tty->print("FoldStableValues: array element [off=%d]: con_type=", off);
  1622         con_type->dump(); tty->cr();
  1624 #endif //PRODUCT
  1625       return con_type;
  1628   return NULL;
  1631 //------------------------------Value-----------------------------------------
  1632 const Type *LoadNode::Value( PhaseTransform *phase ) const {
  1633   // Either input is TOP ==> the result is TOP
  1634   Node* mem = in(MemNode::Memory);
  1635   const Type *t1 = phase->type(mem);
  1636   if (t1 == Type::TOP)  return Type::TOP;
  1637   Node* adr = in(MemNode::Address);
  1638   const TypePtr* tp = phase->type(adr)->isa_ptr();
  1639   if (tp == NULL || tp->empty())  return Type::TOP;
  1640   int off = tp->offset();
  1641   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
  1642   Compile* C = phase->C;
  1644   // Try to guess loaded type from pointer type
  1645   if (tp->isa_aryptr()) {
  1646     const TypeAryPtr* ary = tp->is_aryptr();
  1647     const Type* t = ary->elem();
  1649     // Determine whether the reference is beyond the header or not, by comparing
  1650     // the offset against the offset of the start of the array's data.
  1651     // Different array types begin at slightly different offsets (12 vs. 16).
  1652     // We choose T_BYTE as an example base type that is least restrictive
  1653     // as to alignment, which will therefore produce the smallest
  1654     // possible base offset.
  1655     const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
  1656     const bool off_beyond_header = ((uint)off >= (uint)min_base_off);
  1658     // Try to constant-fold a stable array element.
  1659     if (FoldStableValues && ary->is_stable() && ary->const_oop() != NULL) {
  1660       // Make sure the reference is not into the header and the offset is constant
  1661       if (off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
  1662         const Type* con_type = fold_stable_ary_elem(ary, off, memory_type());
  1663         if (con_type != NULL) {
  1664           return con_type;
  1669     // Don't do this for integer types. There is only potential profit if
  1670     // the element type t is lower than _type; that is, for int types, if _type is
  1671     // more restrictive than t.  This only happens here if one is short and the other
  1672     // char (both 16 bits), and in those cases we've made an intentional decision
  1673     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
  1674     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
  1675     //
  1676     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
  1677     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
  1678     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
  1679     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
  1680     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
  1681     // In fact, that could have been the original type of p1, and p1 could have
  1682     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
  1683     // expression (LShiftL quux 3) independently optimized to the constant 8.
  1684     if ((t->isa_int() == NULL) && (t->isa_long() == NULL)
  1685         && (_type->isa_vect() == NULL)
  1686         && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
  1687       // t might actually be lower than _type, if _type is a unique
  1688       // concrete subclass of abstract class t.
  1689       if (off_beyond_header) {  // is the offset beyond the header?
  1690         const Type* jt = t->join_speculative(_type);
  1691         // In any case, do not allow the join, per se, to empty out the type.
  1692         if (jt->empty() && !t->empty()) {
  1693           // This can happen if a interface-typed array narrows to a class type.
  1694           jt = _type;
  1696 #ifdef ASSERT
  1697         if (phase->C->eliminate_boxing() && adr->is_AddP()) {
  1698           // The pointers in the autobox arrays are always non-null
  1699           Node* base = adr->in(AddPNode::Base);
  1700           if ((base != NULL) && base->is_DecodeN()) {
  1701             // Get LoadN node which loads IntegerCache.cache field
  1702             base = base->in(1);
  1704           if ((base != NULL) && base->is_Con()) {
  1705             const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
  1706             if ((base_type != NULL) && base_type->is_autobox_cache()) {
  1707               // It could be narrow oop
  1708               assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
  1712 #endif
  1713         return jt;
  1716   } else if (tp->base() == Type::InstPtr) {
  1717     ciEnv* env = C->env();
  1718     const TypeInstPtr* tinst = tp->is_instptr();
  1719     ciKlass* klass = tinst->klass();
  1720     assert( off != Type::OffsetBot ||
  1721             // arrays can be cast to Objects
  1722             tp->is_oopptr()->klass()->is_java_lang_Object() ||
  1723             // unsafe field access may not have a constant offset
  1724             C->has_unsafe_access(),
  1725             "Field accesses must be precise" );
  1726     // For oop loads, we expect the _type to be precise
  1727     if (klass == env->String_klass() &&
  1728         adr->is_AddP() && off != Type::OffsetBot) {
  1729       // For constant Strings treat the final fields as compile time constants.
  1730       Node* base = adr->in(AddPNode::Base);
  1731       const TypeOopPtr* t = phase->type(base)->isa_oopptr();
  1732       if (t != NULL && t->singleton()) {
  1733         ciField* field = env->String_klass()->get_field_by_offset(off, false);
  1734         if (field != NULL && field->is_final()) {
  1735           ciObject* string = t->const_oop();
  1736           ciConstant constant = string->as_instance()->field_value(field);
  1737           if (constant.basic_type() == T_INT) {
  1738             return TypeInt::make(constant.as_int());
  1739           } else if (constant.basic_type() == T_ARRAY) {
  1740             if (adr->bottom_type()->is_ptr_to_narrowoop()) {
  1741               return TypeNarrowOop::make_from_constant(constant.as_object(), true);
  1742             } else {
  1743               return TypeOopPtr::make_from_constant(constant.as_object(), true);
  1749     // Optimizations for constant objects
  1750     ciObject* const_oop = tinst->const_oop();
  1751     if (const_oop != NULL) {
  1752       // For constant Boxed value treat the target field as a compile time constant.
  1753       if (tinst->is_ptr_to_boxed_value()) {
  1754         return tinst->get_const_boxed_value();
  1755       } else
  1756       // For constant CallSites treat the target field as a compile time constant.
  1757       if (const_oop->is_call_site()) {
  1758         ciCallSite* call_site = const_oop->as_call_site();
  1759         ciField* field = call_site->klass()->as_instance_klass()->get_field_by_offset(off, /*is_static=*/ false);
  1760         if (field != NULL && field->is_call_site_target()) {
  1761           ciMethodHandle* target = call_site->get_target();
  1762           if (target != NULL) {  // just in case
  1763             ciConstant constant(T_OBJECT, target);
  1764             const Type* t;
  1765             if (adr->bottom_type()->is_ptr_to_narrowoop()) {
  1766               t = TypeNarrowOop::make_from_constant(constant.as_object(), true);
  1767             } else {
  1768               t = TypeOopPtr::make_from_constant(constant.as_object(), true);
  1770             // Add a dependence for invalidation of the optimization.
  1771             if (!call_site->is_constant_call_site()) {
  1772               C->dependencies()->assert_call_site_target_value(call_site, target);
  1774             return t;
  1779   } else if (tp->base() == Type::KlassPtr) {
  1780     assert( off != Type::OffsetBot ||
  1781             // arrays can be cast to Objects
  1782             tp->is_klassptr()->klass()->is_java_lang_Object() ||
  1783             // also allow array-loading from the primary supertype
  1784             // array during subtype checks
  1785             Opcode() == Op_LoadKlass,
  1786             "Field accesses must be precise" );
  1787     // For klass/static loads, we expect the _type to be precise
  1790   const TypeKlassPtr *tkls = tp->isa_klassptr();
  1791   if (tkls != NULL && !StressReflectiveCode) {
  1792     ciKlass* klass = tkls->klass();
  1793     if (klass->is_loaded() && tkls->klass_is_exact()) {
  1794       // We are loading a field from a Klass metaobject whose identity
  1795       // is known at compile time (the type is "exact" or "precise").
  1796       // Check for fields we know are maintained as constants by the VM.
  1797       if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
  1798         // The field is Klass::_super_check_offset.  Return its (constant) value.
  1799         // (Folds up type checking code.)
  1800         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
  1801         return TypeInt::make(klass->super_check_offset());
  1803       // Compute index into primary_supers array
  1804       juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
  1805       // Check for overflowing; use unsigned compare to handle the negative case.
  1806       if( depth < ciKlass::primary_super_limit() ) {
  1807         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
  1808         // (Folds up type checking code.)
  1809         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
  1810         ciKlass *ss = klass->super_of_depth(depth);
  1811         return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
  1813       const Type* aift = load_array_final_field(tkls, klass);
  1814       if (aift != NULL)  return aift;
  1815       if (tkls->offset() == in_bytes(ArrayKlass::component_mirror_offset())
  1816           && klass->is_array_klass()) {
  1817         // The field is ArrayKlass::_component_mirror.  Return its (constant) value.
  1818         // (Folds up aClassConstant.getComponentType, common in Arrays.copyOf.)
  1819         assert(Opcode() == Op_LoadP, "must load an oop from _component_mirror");
  1820         return TypeInstPtr::make(klass->as_array_klass()->component_mirror());
  1822       if (tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
  1823         // The field is Klass::_java_mirror.  Return its (constant) value.
  1824         // (Folds up the 2nd indirection in anObjConstant.getClass().)
  1825         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
  1826         return TypeInstPtr::make(klass->java_mirror());
  1830     // We can still check if we are loading from the primary_supers array at a
  1831     // shallow enough depth.  Even though the klass is not exact, entries less
  1832     // than or equal to its super depth are correct.
  1833     if (klass->is_loaded() ) {
  1834       ciType *inner = klass;
  1835       while( inner->is_obj_array_klass() )
  1836         inner = inner->as_obj_array_klass()->base_element_type();
  1837       if( inner->is_instance_klass() &&
  1838           !inner->as_instance_klass()->flags().is_interface() ) {
  1839         // Compute index into primary_supers array
  1840         juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
  1841         // Check for overflowing; use unsigned compare to handle the negative case.
  1842         if( depth < ciKlass::primary_super_limit() &&
  1843             depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
  1844           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
  1845           // (Folds up type checking code.)
  1846           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
  1847           ciKlass *ss = klass->super_of_depth(depth);
  1848           return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
  1853     // If the type is enough to determine that the thing is not an array,
  1854     // we can give the layout_helper a positive interval type.
  1855     // This will help short-circuit some reflective code.
  1856     if (tkls->offset() == in_bytes(Klass::layout_helper_offset())
  1857         && !klass->is_array_klass() // not directly typed as an array
  1858         && !klass->is_interface()  // specifically not Serializable & Cloneable
  1859         && !klass->is_java_lang_Object()   // not the supertype of all T[]
  1860         ) {
  1861       // Note:  When interfaces are reliable, we can narrow the interface
  1862       // test to (klass != Serializable && klass != Cloneable).
  1863       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
  1864       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
  1865       // The key property of this type is that it folds up tests
  1866       // for array-ness, since it proves that the layout_helper is positive.
  1867       // Thus, a generic value like the basic object layout helper works fine.
  1868       return TypeInt::make(min_size, max_jint, Type::WidenMin);
  1872   // If we are loading from a freshly-allocated object, produce a zero,
  1873   // if the load is provably beyond the header of the object.
  1874   // (Also allow a variable load from a fresh array to produce zero.)
  1875   const TypeOopPtr *tinst = tp->isa_oopptr();
  1876   bool is_instance = (tinst != NULL) && tinst->is_known_instance_field();
  1877   bool is_boxed_value = (tinst != NULL) && tinst->is_ptr_to_boxed_value();
  1878   if (ReduceFieldZeroing || is_instance || is_boxed_value) {
  1879     Node* value = can_see_stored_value(mem,phase);
  1880     if (value != NULL && value->is_Con()) {
  1881       assert(value->bottom_type()->higher_equal(_type),"sanity");
  1882       return value->bottom_type();
  1886   if (is_instance) {
  1887     // If we have an instance type and our memory input is the
  1888     // programs's initial memory state, there is no matching store,
  1889     // so just return a zero of the appropriate type
  1890     Node *mem = in(MemNode::Memory);
  1891     if (mem->is_Parm() && mem->in(0)->is_Start()) {
  1892       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
  1893       return Type::get_zero_type(_type->basic_type());
  1896   return _type;
  1899 //------------------------------match_edge-------------------------------------
  1900 // Do we Match on this edge index or not?  Match only the address.
  1901 uint LoadNode::match_edge(uint idx) const {
  1902   return idx == MemNode::Address;
  1905 //--------------------------LoadBNode::Ideal--------------------------------------
  1906 //
  1907 //  If the previous store is to the same address as this load,
  1908 //  and the value stored was larger than a byte, replace this load
  1909 //  with the value stored truncated to a byte.  If no truncation is
  1910 //  needed, the replacement is done in LoadNode::Identity().
  1911 //
  1912 Node *LoadBNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  1913   Node* mem = in(MemNode::Memory);
  1914   Node* value = can_see_stored_value(mem,phase);
  1915   if( value && !phase->type(value)->higher_equal( _type ) ) {
  1916     Node *result = phase->transform( new (phase->C) LShiftINode(value, phase->intcon(24)) );
  1917     return new (phase->C) RShiftINode(result, phase->intcon(24));
  1919   // Identity call will handle the case where truncation is not needed.
  1920   return LoadNode::Ideal(phase, can_reshape);
  1923 const Type* LoadBNode::Value(PhaseTransform *phase) const {
  1924   Node* mem = in(MemNode::Memory);
  1925   Node* value = can_see_stored_value(mem,phase);
  1926   if (value != NULL && value->is_Con() &&
  1927       !value->bottom_type()->higher_equal(_type)) {
  1928     // If the input to the store does not fit with the load's result type,
  1929     // it must be truncated. We can't delay until Ideal call since
  1930     // a singleton Value is needed for split_thru_phi optimization.
  1931     int con = value->get_int();
  1932     return TypeInt::make((con << 24) >> 24);
  1934   return LoadNode::Value(phase);
  1937 //--------------------------LoadUBNode::Ideal-------------------------------------
  1938 //
  1939 //  If the previous store is to the same address as this load,
  1940 //  and the value stored was larger than a byte, replace this load
  1941 //  with the value stored truncated to a byte.  If no truncation is
  1942 //  needed, the replacement is done in LoadNode::Identity().
  1943 //
  1944 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
  1945   Node* mem = in(MemNode::Memory);
  1946   Node* value = can_see_stored_value(mem, phase);
  1947   if (value && !phase->type(value)->higher_equal(_type))
  1948     return new (phase->C) AndINode(value, phase->intcon(0xFF));
  1949   // Identity call will handle the case where truncation is not needed.
  1950   return LoadNode::Ideal(phase, can_reshape);
  1953 const Type* LoadUBNode::Value(PhaseTransform *phase) const {
  1954   Node* mem = in(MemNode::Memory);
  1955   Node* value = can_see_stored_value(mem,phase);
  1956   if (value != NULL && value->is_Con() &&
  1957       !value->bottom_type()->higher_equal(_type)) {
  1958     // If the input to the store does not fit with the load's result type,
  1959     // it must be truncated. We can't delay until Ideal call since
  1960     // a singleton Value is needed for split_thru_phi optimization.
  1961     int con = value->get_int();
  1962     return TypeInt::make(con & 0xFF);
  1964   return LoadNode::Value(phase);
  1967 //--------------------------LoadUSNode::Ideal-------------------------------------
  1968 //
  1969 //  If the previous store is to the same address as this load,
  1970 //  and the value stored was larger than a char, replace this load
  1971 //  with the value stored truncated to a char.  If no truncation is
  1972 //  needed, the replacement is done in LoadNode::Identity().
  1973 //
  1974 Node *LoadUSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  1975   Node* mem = in(MemNode::Memory);
  1976   Node* value = can_see_stored_value(mem,phase);
  1977   if( value && !phase->type(value)->higher_equal( _type ) )
  1978     return new (phase->C) AndINode(value,phase->intcon(0xFFFF));
  1979   // Identity call will handle the case where truncation is not needed.
  1980   return LoadNode::Ideal(phase, can_reshape);
  1983 const Type* LoadUSNode::Value(PhaseTransform *phase) const {
  1984   Node* mem = in(MemNode::Memory);
  1985   Node* value = can_see_stored_value(mem,phase);
  1986   if (value != NULL && value->is_Con() &&
  1987       !value->bottom_type()->higher_equal(_type)) {
  1988     // If the input to the store does not fit with the load's result type,
  1989     // it must be truncated. We can't delay until Ideal call since
  1990     // a singleton Value is needed for split_thru_phi optimization.
  1991     int con = value->get_int();
  1992     return TypeInt::make(con & 0xFFFF);
  1994   return LoadNode::Value(phase);
  1997 //--------------------------LoadSNode::Ideal--------------------------------------
  1998 //
  1999 //  If the previous store is to the same address as this load,
  2000 //  and the value stored was larger than a short, replace this load
  2001 //  with the value stored truncated to a short.  If no truncation is
  2002 //  needed, the replacement is done in LoadNode::Identity().
  2003 //
  2004 Node *LoadSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  2005   Node* mem = in(MemNode::Memory);
  2006   Node* value = can_see_stored_value(mem,phase);
  2007   if( value && !phase->type(value)->higher_equal( _type ) ) {
  2008     Node *result = phase->transform( new (phase->C) LShiftINode(value, phase->intcon(16)) );
  2009     return new (phase->C) RShiftINode(result, phase->intcon(16));
  2011   // Identity call will handle the case where truncation is not needed.
  2012   return LoadNode::Ideal(phase, can_reshape);
  2015 const Type* LoadSNode::Value(PhaseTransform *phase) const {
  2016   Node* mem = in(MemNode::Memory);
  2017   Node* value = can_see_stored_value(mem,phase);
  2018   if (value != NULL && value->is_Con() &&
  2019       !value->bottom_type()->higher_equal(_type)) {
  2020     // If the input to the store does not fit with the load's result type,
  2021     // it must be truncated. We can't delay until Ideal call since
  2022     // a singleton Value is needed for split_thru_phi optimization.
  2023     int con = value->get_int();
  2024     return TypeInt::make((con << 16) >> 16);
  2026   return LoadNode::Value(phase);
  2029 //=============================================================================
  2030 //----------------------------LoadKlassNode::make------------------------------
  2031 // Polymorphic factory method:
  2032 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node *mem, Node *adr, const TypePtr* at, const TypeKlassPtr *tk) {
  2033   Compile* C = gvn.C;
  2034   // sanity check the alias category against the created node type
  2035   const TypePtr *adr_type = adr->bottom_type()->isa_ptr();
  2036   assert(adr_type != NULL, "expecting TypeKlassPtr");
  2037 #ifdef _LP64
  2038   if (adr_type->is_ptr_to_narrowklass()) {
  2039     assert(UseCompressedClassPointers, "no compressed klasses");
  2040     Node* load_klass = gvn.transform(new (C) LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
  2041     return new (C) DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
  2043 #endif
  2044   assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
  2045   return new (C) LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered);
  2048 //------------------------------Value------------------------------------------
  2049 const Type *LoadKlassNode::Value( PhaseTransform *phase ) const {
  2050   return klass_value_common(phase);
  2053 // In most cases, LoadKlassNode does not have the control input set. If the control
  2054 // input is set, it must not be removed (by LoadNode::Ideal()).
  2055 bool LoadKlassNode::can_remove_control() const {
  2056   return false;
  2059 const Type *LoadNode::klass_value_common( PhaseTransform *phase ) const {
  2060   // Either input is TOP ==> the result is TOP
  2061   const Type *t1 = phase->type( in(MemNode::Memory) );
  2062   if (t1 == Type::TOP)  return Type::TOP;
  2063   Node *adr = in(MemNode::Address);
  2064   const Type *t2 = phase->type( adr );
  2065   if (t2 == Type::TOP)  return Type::TOP;
  2066   const TypePtr *tp = t2->is_ptr();
  2067   if (TypePtr::above_centerline(tp->ptr()) ||
  2068       tp->ptr() == TypePtr::Null)  return Type::TOP;
  2070   // Return a more precise klass, if possible
  2071   const TypeInstPtr *tinst = tp->isa_instptr();
  2072   if (tinst != NULL) {
  2073     ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
  2074     int offset = tinst->offset();
  2075     if (ik == phase->C->env()->Class_klass()
  2076         && (offset == java_lang_Class::klass_offset_in_bytes() ||
  2077             offset == java_lang_Class::array_klass_offset_in_bytes())) {
  2078       // We are loading a special hidden field from a Class mirror object,
  2079       // the field which points to the VM's Klass metaobject.
  2080       ciType* t = tinst->java_mirror_type();
  2081       // java_mirror_type returns non-null for compile-time Class constants.
  2082       if (t != NULL) {
  2083         // constant oop => constant klass
  2084         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
  2085           if (t->is_void()) {
  2086             // We cannot create a void array.  Since void is a primitive type return null
  2087             // klass.  Users of this result need to do a null check on the returned klass.
  2088             return TypePtr::NULL_PTR;
  2090           return TypeKlassPtr::make(ciArrayKlass::make(t));
  2092         if (!t->is_klass()) {
  2093           // a primitive Class (e.g., int.class) has NULL for a klass field
  2094           return TypePtr::NULL_PTR;
  2096         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
  2097         return TypeKlassPtr::make(t->as_klass());
  2099       // non-constant mirror, so we can't tell what's going on
  2101     if( !ik->is_loaded() )
  2102       return _type;             // Bail out if not loaded
  2103     if (offset == oopDesc::klass_offset_in_bytes()) {
  2104       if (tinst->klass_is_exact()) {
  2105         return TypeKlassPtr::make(ik);
  2107       // See if we can become precise: no subklasses and no interface
  2108       // (Note:  We need to support verified interfaces.)
  2109       if (!ik->is_interface() && !ik->has_subklass()) {
  2110         //assert(!UseExactTypes, "this code should be useless with exact types");
  2111         // Add a dependence; if any subclass added we need to recompile
  2112         if (!ik->is_final()) {
  2113           // %%% should use stronger assert_unique_concrete_subtype instead
  2114           phase->C->dependencies()->assert_leaf_type(ik);
  2116         // Return precise klass
  2117         return TypeKlassPtr::make(ik);
  2120       // Return root of possible klass
  2121       return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
  2125   // Check for loading klass from an array
  2126   const TypeAryPtr *tary = tp->isa_aryptr();
  2127   if( tary != NULL ) {
  2128     ciKlass *tary_klass = tary->klass();
  2129     if (tary_klass != NULL   // can be NULL when at BOTTOM or TOP
  2130         && tary->offset() == oopDesc::klass_offset_in_bytes()) {
  2131       if (tary->klass_is_exact()) {
  2132         return TypeKlassPtr::make(tary_klass);
  2134       ciArrayKlass *ak = tary->klass()->as_array_klass();
  2135       // If the klass is an object array, we defer the question to the
  2136       // array component klass.
  2137       if( ak->is_obj_array_klass() ) {
  2138         assert( ak->is_loaded(), "" );
  2139         ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
  2140         if( base_k->is_loaded() && base_k->is_instance_klass() ) {
  2141           ciInstanceKlass* ik = base_k->as_instance_klass();
  2142           // See if we can become precise: no subklasses and no interface
  2143           if (!ik->is_interface() && !ik->has_subklass()) {
  2144             //assert(!UseExactTypes, "this code should be useless with exact types");
  2145             // Add a dependence; if any subclass added we need to recompile
  2146             if (!ik->is_final()) {
  2147               phase->C->dependencies()->assert_leaf_type(ik);
  2149             // Return precise array klass
  2150             return TypeKlassPtr::make(ak);
  2153         return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
  2154       } else {                  // Found a type-array?
  2155         //assert(!UseExactTypes, "this code should be useless with exact types");
  2156         assert( ak->is_type_array_klass(), "" );
  2157         return TypeKlassPtr::make(ak); // These are always precise
  2162   // Check for loading klass from an array klass
  2163   const TypeKlassPtr *tkls = tp->isa_klassptr();
  2164   if (tkls != NULL && !StressReflectiveCode) {
  2165     ciKlass* klass = tkls->klass();
  2166     if( !klass->is_loaded() )
  2167       return _type;             // Bail out if not loaded
  2168     if( klass->is_obj_array_klass() &&
  2169         tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
  2170       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
  2171       // // Always returning precise element type is incorrect,
  2172       // // e.g., element type could be object and array may contain strings
  2173       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
  2175       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
  2176       // according to the element type's subclassing.
  2177       return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
  2179     if( klass->is_instance_klass() && tkls->klass_is_exact() &&
  2180         tkls->offset() == in_bytes(Klass::super_offset())) {
  2181       ciKlass* sup = klass->as_instance_klass()->super();
  2182       // The field is Klass::_super.  Return its (constant) value.
  2183       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
  2184       return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
  2188   // Bailout case
  2189   return LoadNode::Value(phase);
  2192 //------------------------------Identity---------------------------------------
  2193 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
  2194 // Also feed through the klass in Allocate(...klass...)._klass.
  2195 Node* LoadKlassNode::Identity( PhaseTransform *phase ) {
  2196   return klass_identity_common(phase);
  2199 Node* LoadNode::klass_identity_common(PhaseTransform *phase ) {
  2200   Node* x = LoadNode::Identity(phase);
  2201   if (x != this)  return x;
  2203   // Take apart the address into an oop and and offset.
  2204   // Return 'this' if we cannot.
  2205   Node*    adr    = in(MemNode::Address);
  2206   intptr_t offset = 0;
  2207   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
  2208   if (base == NULL)     return this;
  2209   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
  2210   if (toop == NULL)     return this;
  2212   // We can fetch the klass directly through an AllocateNode.
  2213   // This works even if the klass is not constant (clone or newArray).
  2214   if (offset == oopDesc::klass_offset_in_bytes()) {
  2215     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
  2216     if (allocated_klass != NULL) {
  2217       return allocated_klass;
  2221   // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
  2222   // Simplify ak.component_mirror.array_klass to plain ak, ak an ArrayKlass.
  2223   // See inline_native_Class_query for occurrences of these patterns.
  2224   // Java Example:  x.getClass().isAssignableFrom(y)
  2225   // Java Example:  Array.newInstance(x.getClass().getComponentType(), n)
  2226   //
  2227   // This improves reflective code, often making the Class
  2228   // mirror go completely dead.  (Current exception:  Class
  2229   // mirrors may appear in debug info, but we could clean them out by
  2230   // introducing a new debug info operator for Klass*.java_mirror).
  2231   if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
  2232       && (offset == java_lang_Class::klass_offset_in_bytes() ||
  2233           offset == java_lang_Class::array_klass_offset_in_bytes())) {
  2234     // We are loading a special hidden field from a Class mirror,
  2235     // the field which points to its Klass or ArrayKlass metaobject.
  2236     if (base->is_Load()) {
  2237       Node* adr2 = base->in(MemNode::Address);
  2238       const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
  2239       if (tkls != NULL && !tkls->empty()
  2240           && (tkls->klass()->is_instance_klass() ||
  2241               tkls->klass()->is_array_klass())
  2242           && adr2->is_AddP()
  2243           ) {
  2244         int mirror_field = in_bytes(Klass::java_mirror_offset());
  2245         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
  2246           mirror_field = in_bytes(ArrayKlass::component_mirror_offset());
  2248         if (tkls->offset() == mirror_field) {
  2249           return adr2->in(AddPNode::Base);
  2255   return this;
  2259 //------------------------------Value------------------------------------------
  2260 const Type *LoadNKlassNode::Value( PhaseTransform *phase ) const {
  2261   const Type *t = klass_value_common(phase);
  2262   if (t == Type::TOP)
  2263     return t;
  2265   return t->make_narrowklass();
  2268 //------------------------------Identity---------------------------------------
  2269 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
  2270 // Also feed through the klass in Allocate(...klass...)._klass.
  2271 Node* LoadNKlassNode::Identity( PhaseTransform *phase ) {
  2272   Node *x = klass_identity_common(phase);
  2274   const Type *t = phase->type( x );
  2275   if( t == Type::TOP ) return x;
  2276   if( t->isa_narrowklass()) return x;
  2277   assert (!t->isa_narrowoop(), "no narrow oop here");
  2279   return phase->transform(new (phase->C) EncodePKlassNode(x, t->make_narrowklass()));
  2282 //------------------------------Value-----------------------------------------
  2283 const Type *LoadRangeNode::Value( PhaseTransform *phase ) const {
  2284   // Either input is TOP ==> the result is TOP
  2285   const Type *t1 = phase->type( in(MemNode::Memory) );
  2286   if( t1 == Type::TOP ) return Type::TOP;
  2287   Node *adr = in(MemNode::Address);
  2288   const Type *t2 = phase->type( adr );
  2289   if( t2 == Type::TOP ) return Type::TOP;
  2290   const TypePtr *tp = t2->is_ptr();
  2291   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
  2292   const TypeAryPtr *tap = tp->isa_aryptr();
  2293   if( !tap ) return _type;
  2294   return tap->size();
  2297 //-------------------------------Ideal---------------------------------------
  2298 // Feed through the length in AllocateArray(...length...)._length.
  2299 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  2300   Node* p = MemNode::Ideal_common(phase, can_reshape);
  2301   if (p)  return (p == NodeSentinel) ? NULL : p;
  2303   // Take apart the address into an oop and and offset.
  2304   // Return 'this' if we cannot.
  2305   Node*    adr    = in(MemNode::Address);
  2306   intptr_t offset = 0;
  2307   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase,  offset);
  2308   if (base == NULL)     return NULL;
  2309   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
  2310   if (tary == NULL)     return NULL;
  2312   // We can fetch the length directly through an AllocateArrayNode.
  2313   // This works even if the length is not constant (clone or newArray).
  2314   if (offset == arrayOopDesc::length_offset_in_bytes()) {
  2315     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
  2316     if (alloc != NULL) {
  2317       Node* allocated_length = alloc->Ideal_length();
  2318       Node* len = alloc->make_ideal_length(tary, phase);
  2319       if (allocated_length != len) {
  2320         // New CastII improves on this.
  2321         return len;
  2326   return NULL;
  2329 //------------------------------Identity---------------------------------------
  2330 // Feed through the length in AllocateArray(...length...)._length.
  2331 Node* LoadRangeNode::Identity( PhaseTransform *phase ) {
  2332   Node* x = LoadINode::Identity(phase);
  2333   if (x != this)  return x;
  2335   // Take apart the address into an oop and and offset.
  2336   // Return 'this' if we cannot.
  2337   Node*    adr    = in(MemNode::Address);
  2338   intptr_t offset = 0;
  2339   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
  2340   if (base == NULL)     return this;
  2341   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
  2342   if (tary == NULL)     return this;
  2344   // We can fetch the length directly through an AllocateArrayNode.
  2345   // This works even if the length is not constant (clone or newArray).
  2346   if (offset == arrayOopDesc::length_offset_in_bytes()) {
  2347     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
  2348     if (alloc != NULL) {
  2349       Node* allocated_length = alloc->Ideal_length();
  2350       // Do not allow make_ideal_length to allocate a CastII node.
  2351       Node* len = alloc->make_ideal_length(tary, phase, false);
  2352       if (allocated_length == len) {
  2353         // Return allocated_length only if it would not be improved by a CastII.
  2354         return allocated_length;
  2359   return this;
  2363 //=============================================================================
  2364 //---------------------------StoreNode::make-----------------------------------
  2365 // Polymorphic factory method:
  2366 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo) {
  2367   assert((mo == unordered || mo == release), "unexpected");
  2368   Compile* C = gvn.C;
  2369   assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
  2370          ctl != NULL, "raw memory operations should have control edge");
  2372   switch (bt) {
  2373   case T_BOOLEAN: val = gvn.transform(new (C) AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case
  2374   case T_BYTE:    return new (C) StoreBNode(ctl, mem, adr, adr_type, val, mo);
  2375   case T_INT:     return new (C) StoreINode(ctl, mem, adr, adr_type, val, mo);
  2376   case T_CHAR:
  2377   case T_SHORT:   return new (C) StoreCNode(ctl, mem, adr, adr_type, val, mo);
  2378   case T_LONG:    return new (C) StoreLNode(ctl, mem, adr, adr_type, val, mo);
  2379   case T_FLOAT:   return new (C) StoreFNode(ctl, mem, adr, adr_type, val, mo);
  2380   case T_DOUBLE:  return new (C) StoreDNode(ctl, mem, adr, adr_type, val, mo);
  2381   case T_METADATA:
  2382   case T_ADDRESS:
  2383   case T_OBJECT:
  2384 #ifdef _LP64
  2385     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
  2386       val = gvn.transform(new (C) EncodePNode(val, val->bottom_type()->make_narrowoop()));
  2387       return new (C) StoreNNode(ctl, mem, adr, adr_type, val, mo);
  2388     } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
  2389                (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
  2390                 adr->bottom_type()->isa_rawptr())) {
  2391       val = gvn.transform(new (C) EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
  2392       return new (C) StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
  2394 #endif
  2396       return new (C) StorePNode(ctl, mem, adr, adr_type, val, mo);
  2399   ShouldNotReachHere();
  2400   return (StoreNode*)NULL;
  2403 StoreLNode* StoreLNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
  2404   bool require_atomic = true;
  2405   return new (C) StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
  2408 StoreDNode* StoreDNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
  2409   bool require_atomic = true;
  2410   return new (C) StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
  2414 //--------------------------bottom_type----------------------------------------
  2415 const Type *StoreNode::bottom_type() const {
  2416   return Type::MEMORY;
  2419 //------------------------------hash-------------------------------------------
  2420 uint StoreNode::hash() const {
  2421   // unroll addition of interesting fields
  2422   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
  2424   // Since they are not commoned, do not hash them:
  2425   return NO_HASH;
  2428 //------------------------------Ideal------------------------------------------
  2429 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
  2430 // When a store immediately follows a relevant allocation/initialization,
  2431 // try to capture it into the initialization, or hoist it above.
  2432 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  2433   Node* p = MemNode::Ideal_common(phase, can_reshape);
  2434   if (p)  return (p == NodeSentinel) ? NULL : p;
  2436   Node* mem     = in(MemNode::Memory);
  2437   Node* address = in(MemNode::Address);
  2439   // Back-to-back stores to same address?  Fold em up.  Generally
  2440   // unsafe if I have intervening uses...  Also disallowed for StoreCM
  2441   // since they must follow each StoreP operation.  Redundant StoreCMs
  2442   // are eliminated just before matching in final_graph_reshape.
  2443   if (mem->is_Store() && mem->in(MemNode::Address)->eqv_uncast(address) &&
  2444       mem->Opcode() != Op_StoreCM) {
  2445     // Looking at a dead closed cycle of memory?
  2446     assert(mem != mem->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
  2448     assert(Opcode() == mem->Opcode() ||
  2449            phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw,
  2450            "no mismatched stores, except on raw memory");
  2452     if (mem->outcnt() == 1 &&           // check for intervening uses
  2453         mem->as_Store()->memory_size() <= this->memory_size()) {
  2454       // If anybody other than 'this' uses 'mem', we cannot fold 'mem' away.
  2455       // For example, 'mem' might be the final state at a conditional return.
  2456       // Or, 'mem' might be used by some node which is live at the same time
  2457       // 'this' is live, which might be unschedulable.  So, require exactly
  2458       // ONE user, the 'this' store, until such time as we clone 'mem' for
  2459       // each of 'mem's uses (thus making the exactly-1-user-rule hold true).
  2460       if (can_reshape) {  // (%%% is this an anachronism?)
  2461         set_req_X(MemNode::Memory, mem->in(MemNode::Memory),
  2462                   phase->is_IterGVN());
  2463       } else {
  2464         // It's OK to do this in the parser, since DU info is always accurate,
  2465         // and the parser always refers to nodes via SafePointNode maps.
  2466         set_req(MemNode::Memory, mem->in(MemNode::Memory));
  2468       return this;
  2472   // Capture an unaliased, unconditional, simple store into an initializer.
  2473   // Or, if it is independent of the allocation, hoist it above the allocation.
  2474   if (ReduceFieldZeroing && /*can_reshape &&*/
  2475       mem->is_Proj() && mem->in(0)->is_Initialize()) {
  2476     InitializeNode* init = mem->in(0)->as_Initialize();
  2477     intptr_t offset = init->can_capture_store(this, phase, can_reshape);
  2478     if (offset > 0) {
  2479       Node* moved = init->capture_store(this, offset, phase, can_reshape);
  2480       // If the InitializeNode captured me, it made a raw copy of me,
  2481       // and I need to disappear.
  2482       if (moved != NULL) {
  2483         // %%% hack to ensure that Ideal returns a new node:
  2484         mem = MergeMemNode::make(phase->C, mem);
  2485         return mem;             // fold me away
  2490   return NULL;                  // No further progress
  2493 //------------------------------Value-----------------------------------------
  2494 const Type *StoreNode::Value( PhaseTransform *phase ) const {
  2495   // Either input is TOP ==> the result is TOP
  2496   const Type *t1 = phase->type( in(MemNode::Memory) );
  2497   if( t1 == Type::TOP ) return Type::TOP;
  2498   const Type *t2 = phase->type( in(MemNode::Address) );
  2499   if( t2 == Type::TOP ) return Type::TOP;
  2500   const Type *t3 = phase->type( in(MemNode::ValueIn) );
  2501   if( t3 == Type::TOP ) return Type::TOP;
  2502   return Type::MEMORY;
  2505 //------------------------------Identity---------------------------------------
  2506 // Remove redundant stores:
  2507 //   Store(m, p, Load(m, p)) changes to m.
  2508 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
  2509 Node *StoreNode::Identity( PhaseTransform *phase ) {
  2510   Node* mem = in(MemNode::Memory);
  2511   Node* adr = in(MemNode::Address);
  2512   Node* val = in(MemNode::ValueIn);
  2514   // Load then Store?  Then the Store is useless
  2515   if (val->is_Load() &&
  2516       val->in(MemNode::Address)->eqv_uncast(adr) &&
  2517       val->in(MemNode::Memory )->eqv_uncast(mem) &&
  2518       val->as_Load()->store_Opcode() == Opcode()) {
  2519     return mem;
  2522   // Two stores in a row of the same value?
  2523   if (mem->is_Store() &&
  2524       mem->in(MemNode::Address)->eqv_uncast(adr) &&
  2525       mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
  2526       mem->Opcode() == Opcode()) {
  2527     return mem;
  2530   // Store of zero anywhere into a freshly-allocated object?
  2531   // Then the store is useless.
  2532   // (It must already have been captured by the InitializeNode.)
  2533   if (ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
  2534     // a newly allocated object is already all-zeroes everywhere
  2535     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
  2536       return mem;
  2539     // the store may also apply to zero-bits in an earlier object
  2540     Node* prev_mem = find_previous_store(phase);
  2541     // Steps (a), (b):  Walk past independent stores to find an exact match.
  2542     if (prev_mem != NULL) {
  2543       Node* prev_val = can_see_stored_value(prev_mem, phase);
  2544       if (prev_val != NULL && phase->eqv(prev_val, val)) {
  2545         // prev_val and val might differ by a cast; it would be good
  2546         // to keep the more informative of the two.
  2547         return mem;
  2552   return this;
  2555 //------------------------------match_edge-------------------------------------
  2556 // Do we Match on this edge index or not?  Match only memory & value
  2557 uint StoreNode::match_edge(uint idx) const {
  2558   return idx == MemNode::Address || idx == MemNode::ValueIn;
  2561 //------------------------------cmp--------------------------------------------
  2562 // Do not common stores up together.  They generally have to be split
  2563 // back up anyways, so do not bother.
  2564 uint StoreNode::cmp( const Node &n ) const {
  2565   return (&n == this);          // Always fail except on self
  2568 //------------------------------Ideal_masked_input-----------------------------
  2569 // Check for a useless mask before a partial-word store
  2570 // (StoreB ... (AndI valIn conIa) )
  2571 // If (conIa & mask == mask) this simplifies to
  2572 // (StoreB ... (valIn) )
  2573 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
  2574   Node *val = in(MemNode::ValueIn);
  2575   if( val->Opcode() == Op_AndI ) {
  2576     const TypeInt *t = phase->type( val->in(2) )->isa_int();
  2577     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
  2578       set_req(MemNode::ValueIn, val->in(1));
  2579       return this;
  2582   return NULL;
  2586 //------------------------------Ideal_sign_extended_input----------------------
  2587 // Check for useless sign-extension before a partial-word store
  2588 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
  2589 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
  2590 // (StoreB ... (valIn) )
  2591 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
  2592   Node *val = in(MemNode::ValueIn);
  2593   if( val->Opcode() == Op_RShiftI ) {
  2594     const TypeInt *t = phase->type( val->in(2) )->isa_int();
  2595     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
  2596       Node *shl = val->in(1);
  2597       if( shl->Opcode() == Op_LShiftI ) {
  2598         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
  2599         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
  2600           set_req(MemNode::ValueIn, shl->in(1));
  2601           return this;
  2606   return NULL;
  2609 //------------------------------value_never_loaded-----------------------------------
  2610 // Determine whether there are any possible loads of the value stored.
  2611 // For simplicity, we actually check if there are any loads from the
  2612 // address stored to, not just for loads of the value stored by this node.
  2613 //
  2614 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
  2615   Node *adr = in(Address);
  2616   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
  2617   if (adr_oop == NULL)
  2618     return false;
  2619   if (!adr_oop->is_known_instance_field())
  2620     return false; // if not a distinct instance, there may be aliases of the address
  2621   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
  2622     Node *use = adr->fast_out(i);
  2623     int opc = use->Opcode();
  2624     if (use->is_Load() || use->is_LoadStore()) {
  2625       return false;
  2628   return true;
  2631 //=============================================================================
  2632 //------------------------------Ideal------------------------------------------
  2633 // If the store is from an AND mask that leaves the low bits untouched, then
  2634 // we can skip the AND operation.  If the store is from a sign-extension
  2635 // (a left shift, then right shift) we can skip both.
  2636 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2637   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
  2638   if( progress != NULL ) return progress;
  2640   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
  2641   if( progress != NULL ) return progress;
  2643   // Finally check the default case
  2644   return StoreNode::Ideal(phase, can_reshape);
  2647 //=============================================================================
  2648 //------------------------------Ideal------------------------------------------
  2649 // If the store is from an AND mask that leaves the low bits untouched, then
  2650 // we can skip the AND operation
  2651 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2652   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
  2653   if( progress != NULL ) return progress;
  2655   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
  2656   if( progress != NULL ) return progress;
  2658   // Finally check the default case
  2659   return StoreNode::Ideal(phase, can_reshape);
  2662 //=============================================================================
  2663 //------------------------------Identity---------------------------------------
  2664 Node *StoreCMNode::Identity( PhaseTransform *phase ) {
  2665   // No need to card mark when storing a null ptr
  2666   Node* my_store = in(MemNode::OopStore);
  2667   if (my_store->is_Store()) {
  2668     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
  2669     if( t1 == TypePtr::NULL_PTR ) {
  2670       return in(MemNode::Memory);
  2673   return this;
  2676 //=============================================================================
  2677 //------------------------------Ideal---------------------------------------
  2678 Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2679   Node* progress = StoreNode::Ideal(phase, can_reshape);
  2680   if (progress != NULL) return progress;
  2682   Node* my_store = in(MemNode::OopStore);
  2683   if (my_store->is_MergeMem()) {
  2684     Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
  2685     set_req(MemNode::OopStore, mem);
  2686     return this;
  2689   return NULL;
  2692 //------------------------------Value-----------------------------------------
  2693 const Type *StoreCMNode::Value( PhaseTransform *phase ) const {
  2694   // Either input is TOP ==> the result is TOP
  2695   const Type *t = phase->type( in(MemNode::Memory) );
  2696   if( t == Type::TOP ) return Type::TOP;
  2697   t = phase->type( in(MemNode::Address) );
  2698   if( t == Type::TOP ) return Type::TOP;
  2699   t = phase->type( in(MemNode::ValueIn) );
  2700   if( t == Type::TOP ) return Type::TOP;
  2701   // If extra input is TOP ==> the result is TOP
  2702   t = phase->type( in(MemNode::OopStore) );
  2703   if( t == Type::TOP ) return Type::TOP;
  2705   return StoreNode::Value( phase );
  2709 //=============================================================================
  2710 //----------------------------------SCMemProjNode------------------------------
  2711 const Type * SCMemProjNode::Value( PhaseTransform *phase ) const
  2713   return bottom_type();
  2716 //=============================================================================
  2717 //----------------------------------LoadStoreNode------------------------------
  2718 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
  2719   : Node(required),
  2720     _type(rt),
  2721     _adr_type(at)
  2723   init_req(MemNode::Control, c  );
  2724   init_req(MemNode::Memory , mem);
  2725   init_req(MemNode::Address, adr);
  2726   init_req(MemNode::ValueIn, val);
  2727   init_class_id(Class_LoadStore);
  2730 uint LoadStoreNode::ideal_reg() const {
  2731   return _type->ideal_reg();
  2734 bool LoadStoreNode::result_not_used() const {
  2735   for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
  2736     Node *x = fast_out(i);
  2737     if (x->Opcode() == Op_SCMemProj) continue;
  2738     return false;
  2740   return true;
  2743 uint LoadStoreNode::size_of() const { return sizeof(*this); }
  2745 //=============================================================================
  2746 //----------------------------------LoadStoreConditionalNode--------------------
  2747 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, NULL, TypeInt::BOOL, 5) {
  2748   init_req(ExpectedIn, ex );
  2751 //=============================================================================
  2752 //-------------------------------adr_type--------------------------------------
  2753 // Do we Match on this edge index or not?  Do not match memory
  2754 const TypePtr* ClearArrayNode::adr_type() const {
  2755   Node *adr = in(3);
  2756   return MemNode::calculate_adr_type(adr->bottom_type());
  2759 //------------------------------match_edge-------------------------------------
  2760 // Do we Match on this edge index or not?  Do not match memory
  2761 uint ClearArrayNode::match_edge(uint idx) const {
  2762   return idx > 1;
  2765 //------------------------------Identity---------------------------------------
  2766 // Clearing a zero length array does nothing
  2767 Node *ClearArrayNode::Identity( PhaseTransform *phase ) {
  2768   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
  2771 //------------------------------Idealize---------------------------------------
  2772 // Clearing a short array is faster with stores
  2773 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2774   const int unit = BytesPerLong;
  2775   const TypeX* t = phase->type(in(2))->isa_intptr_t();
  2776   if (!t)  return NULL;
  2777   if (!t->is_con())  return NULL;
  2778   intptr_t raw_count = t->get_con();
  2779   intptr_t size = raw_count;
  2780   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
  2781   // Clearing nothing uses the Identity call.
  2782   // Negative clears are possible on dead ClearArrays
  2783   // (see jck test stmt114.stmt11402.val).
  2784   if (size <= 0 || size % unit != 0)  return NULL;
  2785   intptr_t count = size / unit;
  2786   // Length too long; use fast hardware clear
  2787   if (size > Matcher::init_array_short_size)  return NULL;
  2788   Node *mem = in(1);
  2789   if( phase->type(mem)==Type::TOP ) return NULL;
  2790   Node *adr = in(3);
  2791   const Type* at = phase->type(adr);
  2792   if( at==Type::TOP ) return NULL;
  2793   const TypePtr* atp = at->isa_ptr();
  2794   // adjust atp to be the correct array element address type
  2795   if (atp == NULL)  atp = TypePtr::BOTTOM;
  2796   else              atp = atp->add_offset(Type::OffsetBot);
  2797   // Get base for derived pointer purposes
  2798   if( adr->Opcode() != Op_AddP ) Unimplemented();
  2799   Node *base = adr->in(1);
  2801   Node *zero = phase->makecon(TypeLong::ZERO);
  2802   Node *off  = phase->MakeConX(BytesPerLong);
  2803   mem = new (phase->C) StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
  2804   count--;
  2805   while( count-- ) {
  2806     mem = phase->transform(mem);
  2807     adr = phase->transform(new (phase->C) AddPNode(base,adr,off));
  2808     mem = new (phase->C) StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
  2810   return mem;
  2813 //----------------------------step_through----------------------------------
  2814 // Return allocation input memory edge if it is different instance
  2815 // or itself if it is the one we are looking for.
  2816 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseTransform* phase) {
  2817   Node* n = *np;
  2818   assert(n->is_ClearArray(), "sanity");
  2819   intptr_t offset;
  2820   AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
  2821   // This method is called only before Allocate nodes are expanded during
  2822   // macro nodes expansion. Before that ClearArray nodes are only generated
  2823   // in LibraryCallKit::generate_arraycopy() which follows allocations.
  2824   assert(alloc != NULL, "should have allocation");
  2825   if (alloc->_idx == instance_id) {
  2826     // Can not bypass initialization of the instance we are looking for.
  2827     return false;
  2829   // Otherwise skip it.
  2830   InitializeNode* init = alloc->initialization();
  2831   if (init != NULL)
  2832     *np = init->in(TypeFunc::Memory);
  2833   else
  2834     *np = alloc->in(TypeFunc::Memory);
  2835   return true;
  2838 //----------------------------clear_memory-------------------------------------
  2839 // Generate code to initialize object storage to zero.
  2840 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
  2841                                    intptr_t start_offset,
  2842                                    Node* end_offset,
  2843                                    PhaseGVN* phase) {
  2844   Compile* C = phase->C;
  2845   intptr_t offset = start_offset;
  2847   int unit = BytesPerLong;
  2848   if ((offset % unit) != 0) {
  2849     Node* adr = new (C) AddPNode(dest, dest, phase->MakeConX(offset));
  2850     adr = phase->transform(adr);
  2851     const TypePtr* atp = TypeRawPtr::BOTTOM;
  2852     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
  2853     mem = phase->transform(mem);
  2854     offset += BytesPerInt;
  2856   assert((offset % unit) == 0, "");
  2858   // Initialize the remaining stuff, if any, with a ClearArray.
  2859   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
  2862 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
  2863                                    Node* start_offset,
  2864                                    Node* end_offset,
  2865                                    PhaseGVN* phase) {
  2866   if (start_offset == end_offset) {
  2867     // nothing to do
  2868     return mem;
  2871   Compile* C = phase->C;
  2872   int unit = BytesPerLong;
  2873   Node* zbase = start_offset;
  2874   Node* zend  = end_offset;
  2876   // Scale to the unit required by the CPU:
  2877   if (!Matcher::init_array_count_is_in_bytes) {
  2878     Node* shift = phase->intcon(exact_log2(unit));
  2879     zbase = phase->transform( new(C) URShiftXNode(zbase, shift) );
  2880     zend  = phase->transform( new(C) URShiftXNode(zend,  shift) );
  2883   // Bulk clear double-words
  2884   Node* zsize = phase->transform( new(C) SubXNode(zend, zbase) );
  2885   Node* adr = phase->transform( new(C) AddPNode(dest, dest, start_offset) );
  2886   mem = new (C) ClearArrayNode(ctl, mem, zsize, adr);
  2887   return phase->transform(mem);
  2890 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
  2891                                    intptr_t start_offset,
  2892                                    intptr_t end_offset,
  2893                                    PhaseGVN* phase) {
  2894   if (start_offset == end_offset) {
  2895     // nothing to do
  2896     return mem;
  2899   Compile* C = phase->C;
  2900   assert((end_offset % BytesPerInt) == 0, "odd end offset");
  2901   intptr_t done_offset = end_offset;
  2902   if ((done_offset % BytesPerLong) != 0) {
  2903     done_offset -= BytesPerInt;
  2905   if (done_offset > start_offset) {
  2906     mem = clear_memory(ctl, mem, dest,
  2907                        start_offset, phase->MakeConX(done_offset), phase);
  2909   if (done_offset < end_offset) { // emit the final 32-bit store
  2910     Node* adr = new (C) AddPNode(dest, dest, phase->MakeConX(done_offset));
  2911     adr = phase->transform(adr);
  2912     const TypePtr* atp = TypeRawPtr::BOTTOM;
  2913     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
  2914     mem = phase->transform(mem);
  2915     done_offset += BytesPerInt;
  2917   assert(done_offset == end_offset, "");
  2918   return mem;
  2921 //=============================================================================
  2922 // Do not match memory edge.
  2923 uint StrIntrinsicNode::match_edge(uint idx) const {
  2924   return idx == 2 || idx == 3;
  2927 //------------------------------Ideal------------------------------------------
  2928 // Return a node which is more "ideal" than the current node.  Strip out
  2929 // control copies
  2930 Node *StrIntrinsicNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  2931   if (remove_dead_region(phase, can_reshape)) return this;
  2932   // Don't bother trying to transform a dead node
  2933   if (in(0) && in(0)->is_top())  return NULL;
  2935   if (can_reshape) {
  2936     Node* mem = phase->transform(in(MemNode::Memory));
  2937     // If transformed to a MergeMem, get the desired slice
  2938     uint alias_idx = phase->C->get_alias_index(adr_type());
  2939     mem = mem->is_MergeMem() ? mem->as_MergeMem()->memory_at(alias_idx) : mem;
  2940     if (mem != in(MemNode::Memory)) {
  2941       set_req(MemNode::Memory, mem);
  2942       return this;
  2945   return NULL;
  2948 //------------------------------Value------------------------------------------
  2949 const Type *StrIntrinsicNode::Value( PhaseTransform *phase ) const {
  2950   if (in(0) && phase->type(in(0)) == Type::TOP) return Type::TOP;
  2951   return bottom_type();
  2954 //=============================================================================
  2955 //------------------------------match_edge-------------------------------------
  2956 // Do not match memory edge
  2957 uint EncodeISOArrayNode::match_edge(uint idx) const {
  2958   return idx == 2 || idx == 3; // EncodeISOArray src (Binary dst len)
  2961 //------------------------------Ideal------------------------------------------
  2962 // Return a node which is more "ideal" than the current node.  Strip out
  2963 // control copies
  2964 Node *EncodeISOArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  2965   return remove_dead_region(phase, can_reshape) ? this : NULL;
  2968 //------------------------------Value------------------------------------------
  2969 const Type *EncodeISOArrayNode::Value(PhaseTransform *phase) const {
  2970   if (in(0) && phase->type(in(0)) == Type::TOP) return Type::TOP;
  2971   return bottom_type();
  2974 //=============================================================================
  2975 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
  2976   : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
  2977     _adr_type(C->get_adr_type(alias_idx))
  2979   init_class_id(Class_MemBar);
  2980   Node* top = C->top();
  2981   init_req(TypeFunc::I_O,top);
  2982   init_req(TypeFunc::FramePtr,top);
  2983   init_req(TypeFunc::ReturnAdr,top);
  2984   if (precedent != NULL)
  2985     init_req(TypeFunc::Parms, precedent);
  2988 //------------------------------cmp--------------------------------------------
  2989 uint MemBarNode::hash() const { return NO_HASH; }
  2990 uint MemBarNode::cmp( const Node &n ) const {
  2991   return (&n == this);          // Always fail except on self
  2994 //------------------------------make-------------------------------------------
  2995 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
  2996   switch (opcode) {
  2997   case Op_MemBarAcquire:     return new(C) MemBarAcquireNode(C, atp, pn);
  2998   case Op_LoadFence:         return new(C) LoadFenceNode(C, atp, pn);
  2999   case Op_MemBarRelease:     return new(C) MemBarReleaseNode(C, atp, pn);
  3000   case Op_StoreFence:        return new(C) StoreFenceNode(C, atp, pn);
  3001   case Op_MemBarAcquireLock: return new(C) MemBarAcquireLockNode(C, atp, pn);
  3002   case Op_MemBarReleaseLock: return new(C) MemBarReleaseLockNode(C, atp, pn);
  3003   case Op_MemBarVolatile:    return new(C) MemBarVolatileNode(C, atp, pn);
  3004   case Op_MemBarCPUOrder:    return new(C) MemBarCPUOrderNode(C, atp, pn);
  3005   case Op_Initialize:        return new(C) InitializeNode(C, atp, pn);
  3006   case Op_MemBarStoreStore:  return new(C) MemBarStoreStoreNode(C, atp, pn);
  3007   default: ShouldNotReachHere(); return NULL;
  3011 //------------------------------Ideal------------------------------------------
  3012 // Return a node which is more "ideal" than the current node.  Strip out
  3013 // control copies
  3014 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  3015   if (remove_dead_region(phase, can_reshape)) return this;
  3016   // Don't bother trying to transform a dead node
  3017   if (in(0) && in(0)->is_top()) {
  3018     return NULL;
  3021   // Eliminate volatile MemBars for scalar replaced objects.
  3022   if (can_reshape && req() == (Precedent+1)) {
  3023     bool eliminate = false;
  3024     int opc = Opcode();
  3025     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
  3026       // Volatile field loads and stores.
  3027       Node* my_mem = in(MemBarNode::Precedent);
  3028       // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
  3029       if ((my_mem != NULL) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
  3030         // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
  3031         // replace this Precedent (decodeN) with the Load instead.
  3032         if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1))  {
  3033           Node* load_node = my_mem->in(1);
  3034           set_req(MemBarNode::Precedent, load_node);
  3035           phase->is_IterGVN()->_worklist.push(my_mem);
  3036           my_mem = load_node;
  3037         } else {
  3038           assert(my_mem->unique_out() == this, "sanity");
  3039           del_req(Precedent);
  3040           phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
  3041           my_mem = NULL;
  3044       if (my_mem != NULL && my_mem->is_Mem()) {
  3045         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
  3046         // Check for scalar replaced object reference.
  3047         if( t_oop != NULL && t_oop->is_known_instance_field() &&
  3048             t_oop->offset() != Type::OffsetBot &&
  3049             t_oop->offset() != Type::OffsetTop) {
  3050           eliminate = true;
  3053     } else if (opc == Op_MemBarRelease) {
  3054       // Final field stores.
  3055       Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent), phase);
  3056       if ((alloc != NULL) && alloc->is_Allocate() &&
  3057           alloc->as_Allocate()->_is_non_escaping) {
  3058         // The allocated object does not escape.
  3059         eliminate = true;
  3062     if (eliminate) {
  3063       // Replace MemBar projections by its inputs.
  3064       PhaseIterGVN* igvn = phase->is_IterGVN();
  3065       igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
  3066       igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
  3067       // Must return either the original node (now dead) or a new node
  3068       // (Do not return a top here, since that would break the uniqueness of top.)
  3069       return new (phase->C) ConINode(TypeInt::ZERO);
  3072   return NULL;
  3075 //------------------------------Value------------------------------------------
  3076 const Type *MemBarNode::Value( PhaseTransform *phase ) const {
  3077   if( !in(0) ) return Type::TOP;
  3078   if( phase->type(in(0)) == Type::TOP )
  3079     return Type::TOP;
  3080   return TypeTuple::MEMBAR;
  3083 //------------------------------match------------------------------------------
  3084 // Construct projections for memory.
  3085 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
  3086   switch (proj->_con) {
  3087   case TypeFunc::Control:
  3088   case TypeFunc::Memory:
  3089     return new (m->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
  3091   ShouldNotReachHere();
  3092   return NULL;
  3095 //===========================InitializeNode====================================
  3096 // SUMMARY:
  3097 // This node acts as a memory barrier on raw memory, after some raw stores.
  3098 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
  3099 // The Initialize can 'capture' suitably constrained stores as raw inits.
  3100 // It can coalesce related raw stores into larger units (called 'tiles').
  3101 // It can avoid zeroing new storage for memory units which have raw inits.
  3102 // At macro-expansion, it is marked 'complete', and does not optimize further.
  3103 //
  3104 // EXAMPLE:
  3105 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
  3106 //   ctl = incoming control; mem* = incoming memory
  3107 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
  3108 // First allocate uninitialized memory and fill in the header:
  3109 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
  3110 //   ctl := alloc.Control; mem* := alloc.Memory*
  3111 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
  3112 // Then initialize to zero the non-header parts of the raw memory block:
  3113 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
  3114 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
  3115 // After the initialize node executes, the object is ready for service:
  3116 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
  3117 // Suppose its body is immediately initialized as {1,2}:
  3118 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
  3119 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
  3120 //   mem.SLICE(#short[*]) := store2
  3121 //
  3122 // DETAILS:
  3123 // An InitializeNode collects and isolates object initialization after
  3124 // an AllocateNode and before the next possible safepoint.  As a
  3125 // memory barrier (MemBarNode), it keeps critical stores from drifting
  3126 // down past any safepoint or any publication of the allocation.
  3127 // Before this barrier, a newly-allocated object may have uninitialized bits.
  3128 // After this barrier, it may be treated as a real oop, and GC is allowed.
  3129 //
  3130 // The semantics of the InitializeNode include an implicit zeroing of
  3131 // the new object from object header to the end of the object.
  3132 // (The object header and end are determined by the AllocateNode.)
  3133 //
  3134 // Certain stores may be added as direct inputs to the InitializeNode.
  3135 // These stores must update raw memory, and they must be to addresses
  3136 // derived from the raw address produced by AllocateNode, and with
  3137 // a constant offset.  They must be ordered by increasing offset.
  3138 // The first one is at in(RawStores), the last at in(req()-1).
  3139 // Unlike most memory operations, they are not linked in a chain,
  3140 // but are displayed in parallel as users of the rawmem output of
  3141 // the allocation.
  3142 //
  3143 // (See comments in InitializeNode::capture_store, which continue
  3144 // the example given above.)
  3145 //
  3146 // When the associated Allocate is macro-expanded, the InitializeNode
  3147 // may be rewritten to optimize collected stores.  A ClearArrayNode
  3148 // may also be created at that point to represent any required zeroing.
  3149 // The InitializeNode is then marked 'complete', prohibiting further
  3150 // capturing of nearby memory operations.
  3151 //
  3152 // During macro-expansion, all captured initializations which store
  3153 // constant values of 32 bits or smaller are coalesced (if advantageous)
  3154 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
  3155 // initialized in fewer memory operations.  Memory words which are
  3156 // covered by neither tiles nor non-constant stores are pre-zeroed
  3157 // by explicit stores of zero.  (The code shape happens to do all
  3158 // zeroing first, then all other stores, with both sequences occurring
  3159 // in order of ascending offsets.)
  3160 //
  3161 // Alternatively, code may be inserted between an AllocateNode and its
  3162 // InitializeNode, to perform arbitrary initialization of the new object.
  3163 // E.g., the object copying intrinsics insert complex data transfers here.
  3164 // The initialization must then be marked as 'complete' disable the
  3165 // built-in zeroing semantics and the collection of initializing stores.
  3166 //
  3167 // While an InitializeNode is incomplete, reads from the memory state
  3168 // produced by it are optimizable if they match the control edge and
  3169 // new oop address associated with the allocation/initialization.
  3170 // They return a stored value (if the offset matches) or else zero.
  3171 // A write to the memory state, if it matches control and address,
  3172 // and if it is to a constant offset, may be 'captured' by the
  3173 // InitializeNode.  It is cloned as a raw memory operation and rewired
  3174 // inside the initialization, to the raw oop produced by the allocation.
  3175 // Operations on addresses which are provably distinct (e.g., to
  3176 // other AllocateNodes) are allowed to bypass the initialization.
  3177 //
  3178 // The effect of all this is to consolidate object initialization
  3179 // (both arrays and non-arrays, both piecewise and bulk) into a
  3180 // single location, where it can be optimized as a unit.
  3181 //
  3182 // Only stores with an offset less than TrackedInitializationLimit words
  3183 // will be considered for capture by an InitializeNode.  This puts a
  3184 // reasonable limit on the complexity of optimized initializations.
  3186 //---------------------------InitializeNode------------------------------------
  3187 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
  3188   : _is_complete(Incomplete), _does_not_escape(false),
  3189     MemBarNode(C, adr_type, rawoop)
  3191   init_class_id(Class_Initialize);
  3193   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
  3194   assert(in(RawAddress) == rawoop, "proper init");
  3195   // Note:  allocation() can be NULL, for secondary initialization barriers
  3198 // Since this node is not matched, it will be processed by the
  3199 // register allocator.  Declare that there are no constraints
  3200 // on the allocation of the RawAddress edge.
  3201 const RegMask &InitializeNode::in_RegMask(uint idx) const {
  3202   // This edge should be set to top, by the set_complete.  But be conservative.
  3203   if (idx == InitializeNode::RawAddress)
  3204     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
  3205   return RegMask::Empty;
  3208 Node* InitializeNode::memory(uint alias_idx) {
  3209   Node* mem = in(Memory);
  3210   if (mem->is_MergeMem()) {
  3211     return mem->as_MergeMem()->memory_at(alias_idx);
  3212   } else {
  3213     // incoming raw memory is not split
  3214     return mem;
  3218 bool InitializeNode::is_non_zero() {
  3219   if (is_complete())  return false;
  3220   remove_extra_zeroes();
  3221   return (req() > RawStores);
  3224 void InitializeNode::set_complete(PhaseGVN* phase) {
  3225   assert(!is_complete(), "caller responsibility");
  3226   _is_complete = Complete;
  3228   // After this node is complete, it contains a bunch of
  3229   // raw-memory initializations.  There is no need for
  3230   // it to have anything to do with non-raw memory effects.
  3231   // Therefore, tell all non-raw users to re-optimize themselves,
  3232   // after skipping the memory effects of this initialization.
  3233   PhaseIterGVN* igvn = phase->is_IterGVN();
  3234   if (igvn)  igvn->add_users_to_worklist(this);
  3237 // convenience function
  3238 // return false if the init contains any stores already
  3239 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
  3240   InitializeNode* init = initialization();
  3241   if (init == NULL || init->is_complete())  return false;
  3242   init->remove_extra_zeroes();
  3243   // for now, if this allocation has already collected any inits, bail:
  3244   if (init->is_non_zero())  return false;
  3245   init->set_complete(phase);
  3246   return true;
  3249 void InitializeNode::remove_extra_zeroes() {
  3250   if (req() == RawStores)  return;
  3251   Node* zmem = zero_memory();
  3252   uint fill = RawStores;
  3253   for (uint i = fill; i < req(); i++) {
  3254     Node* n = in(i);
  3255     if (n->is_top() || n == zmem)  continue;  // skip
  3256     if (fill < i)  set_req(fill, n);          // compact
  3257     ++fill;
  3259   // delete any empty spaces created:
  3260   while (fill < req()) {
  3261     del_req(fill);
  3265 // Helper for remembering which stores go with which offsets.
  3266 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
  3267   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
  3268   intptr_t offset = -1;
  3269   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
  3270                                                phase, offset);
  3271   if (base == NULL)     return -1;  // something is dead,
  3272   if (offset < 0)       return -1;  //        dead, dead
  3273   return offset;
  3276 // Helper for proving that an initialization expression is
  3277 // "simple enough" to be folded into an object initialization.
  3278 // Attempts to prove that a store's initial value 'n' can be captured
  3279 // within the initialization without creating a vicious cycle, such as:
  3280 //     { Foo p = new Foo(); p.next = p; }
  3281 // True for constants and parameters and small combinations thereof.
  3282 bool InitializeNode::detect_init_independence(Node* n, int& count) {
  3283   if (n == NULL)      return true;   // (can this really happen?)
  3284   if (n->is_Proj())   n = n->in(0);
  3285   if (n == this)      return false;  // found a cycle
  3286   if (n->is_Con())    return true;
  3287   if (n->is_Start())  return true;   // params, etc., are OK
  3288   if (n->is_Root())   return true;   // even better
  3290   Node* ctl = n->in(0);
  3291   if (ctl != NULL && !ctl->is_top()) {
  3292     if (ctl->is_Proj())  ctl = ctl->in(0);
  3293     if (ctl == this)  return false;
  3295     // If we already know that the enclosing memory op is pinned right after
  3296     // the init, then any control flow that the store has picked up
  3297     // must have preceded the init, or else be equal to the init.
  3298     // Even after loop optimizations (which might change control edges)
  3299     // a store is never pinned *before* the availability of its inputs.
  3300     if (!MemNode::all_controls_dominate(n, this))
  3301       return false;                  // failed to prove a good control
  3304   // Check data edges for possible dependencies on 'this'.
  3305   if ((count += 1) > 20)  return false;  // complexity limit
  3306   for (uint i = 1; i < n->req(); i++) {
  3307     Node* m = n->in(i);
  3308     if (m == NULL || m == n || m->is_top())  continue;
  3309     uint first_i = n->find_edge(m);
  3310     if (i != first_i)  continue;  // process duplicate edge just once
  3311     if (!detect_init_independence(m, count)) {
  3312       return false;
  3316   return true;
  3319 // Here are all the checks a Store must pass before it can be moved into
  3320 // an initialization.  Returns zero if a check fails.
  3321 // On success, returns the (constant) offset to which the store applies,
  3322 // within the initialized memory.
  3323 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase, bool can_reshape) {
  3324   const int FAIL = 0;
  3325   if (st->req() != MemNode::ValueIn + 1)
  3326     return FAIL;                // an inscrutable StoreNode (card mark?)
  3327   Node* ctl = st->in(MemNode::Control);
  3328   if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
  3329     return FAIL;                // must be unconditional after the initialization
  3330   Node* mem = st->in(MemNode::Memory);
  3331   if (!(mem->is_Proj() && mem->in(0) == this))
  3332     return FAIL;                // must not be preceded by other stores
  3333   Node* adr = st->in(MemNode::Address);
  3334   intptr_t offset;
  3335   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
  3336   if (alloc == NULL)
  3337     return FAIL;                // inscrutable address
  3338   if (alloc != allocation())
  3339     return FAIL;                // wrong allocation!  (store needs to float up)
  3340   Node* val = st->in(MemNode::ValueIn);
  3341   int complexity_count = 0;
  3342   if (!detect_init_independence(val, complexity_count))
  3343     return FAIL;                // stored value must be 'simple enough'
  3345   // The Store can be captured only if nothing after the allocation
  3346   // and before the Store is using the memory location that the store
  3347   // overwrites.
  3348   bool failed = false;
  3349   // If is_complete_with_arraycopy() is true the shape of the graph is
  3350   // well defined and is safe so no need for extra checks.
  3351   if (!is_complete_with_arraycopy()) {
  3352     // We are going to look at each use of the memory state following
  3353     // the allocation to make sure nothing reads the memory that the
  3354     // Store writes.
  3355     const TypePtr* t_adr = phase->type(adr)->isa_ptr();
  3356     int alias_idx = phase->C->get_alias_index(t_adr);
  3357     ResourceMark rm;
  3358     Unique_Node_List mems;
  3359     mems.push(mem);
  3360     Node* unique_merge = NULL;
  3361     for (uint next = 0; next < mems.size(); ++next) {
  3362       Node *m  = mems.at(next);
  3363       for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
  3364         Node *n = m->fast_out(j);
  3365         if (n->outcnt() == 0) {
  3366           continue;
  3368         if (n == st) {
  3369           continue;
  3370         } else if (n->in(0) != NULL && n->in(0) != ctl) {
  3371           // If the control of this use is different from the control
  3372           // of the Store which is right after the InitializeNode then
  3373           // this node cannot be between the InitializeNode and the
  3374           // Store.
  3375           continue;
  3376         } else if (n->is_MergeMem()) {
  3377           if (n->as_MergeMem()->memory_at(alias_idx) == m) {
  3378             // We can hit a MergeMemNode (that will likely go away
  3379             // later) that is a direct use of the memory state
  3380             // following the InitializeNode on the same slice as the
  3381             // store node that we'd like to capture. We need to check
  3382             // the uses of the MergeMemNode.
  3383             mems.push(n);
  3385         } else if (n->is_Mem()) {
  3386           Node* other_adr = n->in(MemNode::Address);
  3387           if (other_adr == adr) {
  3388             failed = true;
  3389             break;
  3390           } else {
  3391             const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
  3392             if (other_t_adr != NULL) {
  3393               int other_alias_idx = phase->C->get_alias_index(other_t_adr);
  3394               if (other_alias_idx == alias_idx) {
  3395                 // A load from the same memory slice as the store right
  3396                 // after the InitializeNode. We check the control of the
  3397                 // object/array that is loaded from. If it's the same as
  3398                 // the store control then we cannot capture the store.
  3399                 assert(!n->is_Store(), "2 stores to same slice on same control?");
  3400                 Node* base = other_adr;
  3401                 assert(base->is_AddP(), err_msg_res("should be addp but is %s", base->Name()));
  3402                 base = base->in(AddPNode::Base);
  3403                 if (base != NULL) {
  3404                   base = base->uncast();
  3405                   if (base->is_Proj() && base->in(0) == alloc) {
  3406                     failed = true;
  3407                     break;
  3413         } else {
  3414           failed = true;
  3415           break;
  3420   if (failed) {
  3421     if (!can_reshape) {
  3422       // We decided we couldn't capture the store during parsing. We
  3423       // should try again during the next IGVN once the graph is
  3424       // cleaner.
  3425       phase->C->record_for_igvn(st);
  3427     return FAIL;
  3430   return offset;                // success
  3433 // Find the captured store in(i) which corresponds to the range
  3434 // [start..start+size) in the initialized object.
  3435 // If there is one, return its index i.  If there isn't, return the
  3436 // negative of the index where it should be inserted.
  3437 // Return 0 if the queried range overlaps an initialization boundary
  3438 // or if dead code is encountered.
  3439 // If size_in_bytes is zero, do not bother with overlap checks.
  3440 int InitializeNode::captured_store_insertion_point(intptr_t start,
  3441                                                    int size_in_bytes,
  3442                                                    PhaseTransform* phase) {
  3443   const int FAIL = 0, MAX_STORE = BytesPerLong;
  3445   if (is_complete())
  3446     return FAIL;                // arraycopy got here first; punt
  3448   assert(allocation() != NULL, "must be present");
  3450   // no negatives, no header fields:
  3451   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
  3453   // after a certain size, we bail out on tracking all the stores:
  3454   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
  3455   if (start >= ti_limit)  return FAIL;
  3457   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
  3458     if (i >= limit)  return -(int)i; // not found; here is where to put it
  3460     Node*    st     = in(i);
  3461     intptr_t st_off = get_store_offset(st, phase);
  3462     if (st_off < 0) {
  3463       if (st != zero_memory()) {
  3464         return FAIL;            // bail out if there is dead garbage
  3466     } else if (st_off > start) {
  3467       // ...we are done, since stores are ordered
  3468       if (st_off < start + size_in_bytes) {
  3469         return FAIL;            // the next store overlaps
  3471       return -(int)i;           // not found; here is where to put it
  3472     } else if (st_off < start) {
  3473       if (size_in_bytes != 0 &&
  3474           start < st_off + MAX_STORE &&
  3475           start < st_off + st->as_Store()->memory_size()) {
  3476         return FAIL;            // the previous store overlaps
  3478     } else {
  3479       if (size_in_bytes != 0 &&
  3480           st->as_Store()->memory_size() != size_in_bytes) {
  3481         return FAIL;            // mismatched store size
  3483       return i;
  3486     ++i;
  3490 // Look for a captured store which initializes at the offset 'start'
  3491 // with the given size.  If there is no such store, and no other
  3492 // initialization interferes, then return zero_memory (the memory
  3493 // projection of the AllocateNode).
  3494 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
  3495                                           PhaseTransform* phase) {
  3496   assert(stores_are_sane(phase), "");
  3497   int i = captured_store_insertion_point(start, size_in_bytes, phase);
  3498   if (i == 0) {
  3499     return NULL;                // something is dead
  3500   } else if (i < 0) {
  3501     return zero_memory();       // just primordial zero bits here
  3502   } else {
  3503     Node* st = in(i);           // here is the store at this position
  3504     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
  3505     return st;
  3509 // Create, as a raw pointer, an address within my new object at 'offset'.
  3510 Node* InitializeNode::make_raw_address(intptr_t offset,
  3511                                        PhaseTransform* phase) {
  3512   Node* addr = in(RawAddress);
  3513   if (offset != 0) {
  3514     Compile* C = phase->C;
  3515     addr = phase->transform( new (C) AddPNode(C->top(), addr,
  3516                                                  phase->MakeConX(offset)) );
  3518   return addr;
  3521 // Clone the given store, converting it into a raw store
  3522 // initializing a field or element of my new object.
  3523 // Caller is responsible for retiring the original store,
  3524 // with subsume_node or the like.
  3525 //
  3526 // From the example above InitializeNode::InitializeNode,
  3527 // here are the old stores to be captured:
  3528 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
  3529 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
  3530 //
  3531 // Here is the changed code; note the extra edges on init:
  3532 //   alloc = (Allocate ...)
  3533 //   rawoop = alloc.RawAddress
  3534 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
  3535 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
  3536 //   init = (Initialize alloc.Control alloc.Memory rawoop
  3537 //                      rawstore1 rawstore2)
  3538 //
  3539 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
  3540                                     PhaseTransform* phase, bool can_reshape) {
  3541   assert(stores_are_sane(phase), "");
  3543   if (start < 0)  return NULL;
  3544   assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
  3546   Compile* C = phase->C;
  3547   int size_in_bytes = st->memory_size();
  3548   int i = captured_store_insertion_point(start, size_in_bytes, phase);
  3549   if (i == 0)  return NULL;     // bail out
  3550   Node* prev_mem = NULL;        // raw memory for the captured store
  3551   if (i > 0) {
  3552     prev_mem = in(i);           // there is a pre-existing store under this one
  3553     set_req(i, C->top());       // temporarily disconnect it
  3554     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
  3555   } else {
  3556     i = -i;                     // no pre-existing store
  3557     prev_mem = zero_memory();   // a slice of the newly allocated object
  3558     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
  3559       set_req(--i, C->top());   // reuse this edge; it has been folded away
  3560     else
  3561       ins_req(i, C->top());     // build a new edge
  3563   Node* new_st = st->clone();
  3564   new_st->set_req(MemNode::Control, in(Control));
  3565   new_st->set_req(MemNode::Memory,  prev_mem);
  3566   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
  3567   new_st = phase->transform(new_st);
  3569   // At this point, new_st might have swallowed a pre-existing store
  3570   // at the same offset, or perhaps new_st might have disappeared,
  3571   // if it redundantly stored the same value (or zero to fresh memory).
  3573   // In any case, wire it in:
  3574   set_req(i, new_st);
  3576   // The caller may now kill the old guy.
  3577   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
  3578   assert(check_st == new_st || check_st == NULL, "must be findable");
  3579   assert(!is_complete(), "");
  3580   return new_st;
  3583 static bool store_constant(jlong* tiles, int num_tiles,
  3584                            intptr_t st_off, int st_size,
  3585                            jlong con) {
  3586   if ((st_off & (st_size-1)) != 0)
  3587     return false;               // strange store offset (assume size==2**N)
  3588   address addr = (address)tiles + st_off;
  3589   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
  3590   switch (st_size) {
  3591   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
  3592   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
  3593   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
  3594   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
  3595   default: return false;        // strange store size (detect size!=2**N here)
  3597   return true;                  // return success to caller
  3600 // Coalesce subword constants into int constants and possibly
  3601 // into long constants.  The goal, if the CPU permits,
  3602 // is to initialize the object with a small number of 64-bit tiles.
  3603 // Also, convert floating-point constants to bit patterns.
  3604 // Non-constants are not relevant to this pass.
  3605 //
  3606 // In terms of the running example on InitializeNode::InitializeNode
  3607 // and InitializeNode::capture_store, here is the transformation
  3608 // of rawstore1 and rawstore2 into rawstore12:
  3609 //   alloc = (Allocate ...)
  3610 //   rawoop = alloc.RawAddress
  3611 //   tile12 = 0x00010002
  3612 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
  3613 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
  3614 //
  3615 void
  3616 InitializeNode::coalesce_subword_stores(intptr_t header_size,
  3617                                         Node* size_in_bytes,
  3618                                         PhaseGVN* phase) {
  3619   Compile* C = phase->C;
  3621   assert(stores_are_sane(phase), "");
  3622   // Note:  After this pass, they are not completely sane,
  3623   // since there may be some overlaps.
  3625   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
  3627   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
  3628   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
  3629   size_limit = MIN2(size_limit, ti_limit);
  3630   size_limit = align_size_up(size_limit, BytesPerLong);
  3631   int num_tiles = size_limit / BytesPerLong;
  3633   // allocate space for the tile map:
  3634   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
  3635   jlong  tiles_buf[small_len];
  3636   Node*  nodes_buf[small_len];
  3637   jlong  inits_buf[small_len];
  3638   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
  3639                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
  3640   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
  3641                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
  3642   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
  3643                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
  3644   // tiles: exact bitwise model of all primitive constants
  3645   // nodes: last constant-storing node subsumed into the tiles model
  3646   // inits: which bytes (in each tile) are touched by any initializations
  3648   //// Pass A: Fill in the tile model with any relevant stores.
  3650   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
  3651   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
  3652   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
  3653   Node* zmem = zero_memory(); // initially zero memory state
  3654   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
  3655     Node* st = in(i);
  3656     intptr_t st_off = get_store_offset(st, phase);
  3658     // Figure out the store's offset and constant value:
  3659     if (st_off < header_size)             continue; //skip (ignore header)
  3660     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
  3661     int st_size = st->as_Store()->memory_size();
  3662     if (st_off + st_size > size_limit)    break;
  3664     // Record which bytes are touched, whether by constant or not.
  3665     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
  3666       continue;                 // skip (strange store size)
  3668     const Type* val = phase->type(st->in(MemNode::ValueIn));
  3669     if (!val->singleton())                continue; //skip (non-con store)
  3670     BasicType type = val->basic_type();
  3672     jlong con = 0;
  3673     switch (type) {
  3674     case T_INT:    con = val->is_int()->get_con();  break;
  3675     case T_LONG:   con = val->is_long()->get_con(); break;
  3676     case T_FLOAT:  con = jint_cast(val->getf());    break;
  3677     case T_DOUBLE: con = jlong_cast(val->getd());   break;
  3678     default:                              continue; //skip (odd store type)
  3681     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
  3682         st->Opcode() == Op_StoreL) {
  3683       continue;                 // This StoreL is already optimal.
  3686     // Store down the constant.
  3687     store_constant(tiles, num_tiles, st_off, st_size, con);
  3689     intptr_t j = st_off >> LogBytesPerLong;
  3691     if (type == T_INT && st_size == BytesPerInt
  3692         && (st_off & BytesPerInt) == BytesPerInt) {
  3693       jlong lcon = tiles[j];
  3694       if (!Matcher::isSimpleConstant64(lcon) &&
  3695           st->Opcode() == Op_StoreI) {
  3696         // This StoreI is already optimal by itself.
  3697         jint* intcon = (jint*) &tiles[j];
  3698         intcon[1] = 0;  // undo the store_constant()
  3700         // If the previous store is also optimal by itself, back up and
  3701         // undo the action of the previous loop iteration... if we can.
  3702         // But if we can't, just let the previous half take care of itself.
  3703         st = nodes[j];
  3704         st_off -= BytesPerInt;
  3705         con = intcon[0];
  3706         if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
  3707           assert(st_off >= header_size, "still ignoring header");
  3708           assert(get_store_offset(st, phase) == st_off, "must be");
  3709           assert(in(i-1) == zmem, "must be");
  3710           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
  3711           assert(con == tcon->is_int()->get_con(), "must be");
  3712           // Undo the effects of the previous loop trip, which swallowed st:
  3713           intcon[0] = 0;        // undo store_constant()
  3714           set_req(i-1, st);     // undo set_req(i, zmem)
  3715           nodes[j] = NULL;      // undo nodes[j] = st
  3716           --old_subword;        // undo ++old_subword
  3718         continue;               // This StoreI is already optimal.
  3722     // This store is not needed.
  3723     set_req(i, zmem);
  3724     nodes[j] = st;              // record for the moment
  3725     if (st_size < BytesPerLong) // something has changed
  3726           ++old_subword;        // includes int/float, but who's counting...
  3727     else  ++old_long;
  3730   if ((old_subword + old_long) == 0)
  3731     return;                     // nothing more to do
  3733   //// Pass B: Convert any non-zero tiles into optimal constant stores.
  3734   // Be sure to insert them before overlapping non-constant stores.
  3735   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
  3736   for (int j = 0; j < num_tiles; j++) {
  3737     jlong con  = tiles[j];
  3738     jlong init = inits[j];
  3739     if (con == 0)  continue;
  3740     jint con0,  con1;           // split the constant, address-wise
  3741     jint init0, init1;          // split the init map, address-wise
  3742     { union { jlong con; jint intcon[2]; } u;
  3743       u.con = con;
  3744       con0  = u.intcon[0];
  3745       con1  = u.intcon[1];
  3746       u.con = init;
  3747       init0 = u.intcon[0];
  3748       init1 = u.intcon[1];
  3751     Node* old = nodes[j];
  3752     assert(old != NULL, "need the prior store");
  3753     intptr_t offset = (j * BytesPerLong);
  3755     bool split = !Matcher::isSimpleConstant64(con);
  3757     if (offset < header_size) {
  3758       assert(offset + BytesPerInt >= header_size, "second int counts");
  3759       assert(*(jint*)&tiles[j] == 0, "junk in header");
  3760       split = true;             // only the second word counts
  3761       // Example:  int a[] = { 42 ... }
  3762     } else if (con0 == 0 && init0 == -1) {
  3763       split = true;             // first word is covered by full inits
  3764       // Example:  int a[] = { ... foo(), 42 ... }
  3765     } else if (con1 == 0 && init1 == -1) {
  3766       split = true;             // second word is covered by full inits
  3767       // Example:  int a[] = { ... 42, foo() ... }
  3770     // Here's a case where init0 is neither 0 nor -1:
  3771     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
  3772     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
  3773     // In this case the tile is not split; it is (jlong)42.
  3774     // The big tile is stored down, and then the foo() value is inserted.
  3775     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
  3777     Node* ctl = old->in(MemNode::Control);
  3778     Node* adr = make_raw_address(offset, phase);
  3779     const TypePtr* atp = TypeRawPtr::BOTTOM;
  3781     // One or two coalesced stores to plop down.
  3782     Node*    st[2];
  3783     intptr_t off[2];
  3784     int  nst = 0;
  3785     if (!split) {
  3786       ++new_long;
  3787       off[nst] = offset;
  3788       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
  3789                                   phase->longcon(con), T_LONG, MemNode::unordered);
  3790     } else {
  3791       // Omit either if it is a zero.
  3792       if (con0 != 0) {
  3793         ++new_int;
  3794         off[nst]  = offset;
  3795         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
  3796                                     phase->intcon(con0), T_INT, MemNode::unordered);
  3798       if (con1 != 0) {
  3799         ++new_int;
  3800         offset += BytesPerInt;
  3801         adr = make_raw_address(offset, phase);
  3802         off[nst]  = offset;
  3803         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
  3804                                     phase->intcon(con1), T_INT, MemNode::unordered);
  3808     // Insert second store first, then the first before the second.
  3809     // Insert each one just before any overlapping non-constant stores.
  3810     while (nst > 0) {
  3811       Node* st1 = st[--nst];
  3812       C->copy_node_notes_to(st1, old);
  3813       st1 = phase->transform(st1);
  3814       offset = off[nst];
  3815       assert(offset >= header_size, "do not smash header");
  3816       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
  3817       guarantee(ins_idx != 0, "must re-insert constant store");
  3818       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
  3819       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
  3820         set_req(--ins_idx, st1);
  3821       else
  3822         ins_req(ins_idx, st1);
  3826   if (PrintCompilation && WizardMode)
  3827     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
  3828                   old_subword, old_long, new_int, new_long);
  3829   if (C->log() != NULL)
  3830     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
  3831                    old_subword, old_long, new_int, new_long);
  3833   // Clean up any remaining occurrences of zmem:
  3834   remove_extra_zeroes();
  3837 // Explore forward from in(start) to find the first fully initialized
  3838 // word, and return its offset.  Skip groups of subword stores which
  3839 // together initialize full words.  If in(start) is itself part of a
  3840 // fully initialized word, return the offset of in(start).  If there
  3841 // are no following full-word stores, or if something is fishy, return
  3842 // a negative value.
  3843 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
  3844   int       int_map = 0;
  3845   intptr_t  int_map_off = 0;
  3846   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
  3848   for (uint i = start, limit = req(); i < limit; i++) {
  3849     Node* st = in(i);
  3851     intptr_t st_off = get_store_offset(st, phase);
  3852     if (st_off < 0)  break;  // return conservative answer
  3854     int st_size = st->as_Store()->memory_size();
  3855     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
  3856       return st_off;            // we found a complete word init
  3859     // update the map:
  3861     intptr_t this_int_off = align_size_down(st_off, BytesPerInt);
  3862     if (this_int_off != int_map_off) {
  3863       // reset the map:
  3864       int_map = 0;
  3865       int_map_off = this_int_off;
  3868     int subword_off = st_off - this_int_off;
  3869     int_map |= right_n_bits(st_size) << subword_off;
  3870     if ((int_map & FULL_MAP) == FULL_MAP) {
  3871       return this_int_off;      // we found a complete word init
  3874     // Did this store hit or cross the word boundary?
  3875     intptr_t next_int_off = align_size_down(st_off + st_size, BytesPerInt);
  3876     if (next_int_off == this_int_off + BytesPerInt) {
  3877       // We passed the current int, without fully initializing it.
  3878       int_map_off = next_int_off;
  3879       int_map >>= BytesPerInt;
  3880     } else if (next_int_off > this_int_off + BytesPerInt) {
  3881       // We passed the current and next int.
  3882       return this_int_off + BytesPerInt;
  3886   return -1;
  3890 // Called when the associated AllocateNode is expanded into CFG.
  3891 // At this point, we may perform additional optimizations.
  3892 // Linearize the stores by ascending offset, to make memory
  3893 // activity as coherent as possible.
  3894 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
  3895                                       intptr_t header_size,
  3896                                       Node* size_in_bytes,
  3897                                       PhaseGVN* phase) {
  3898   assert(!is_complete(), "not already complete");
  3899   assert(stores_are_sane(phase), "");
  3900   assert(allocation() != NULL, "must be present");
  3902   remove_extra_zeroes();
  3904   if (ReduceFieldZeroing || ReduceBulkZeroing)
  3905     // reduce instruction count for common initialization patterns
  3906     coalesce_subword_stores(header_size, size_in_bytes, phase);
  3908   Node* zmem = zero_memory();   // initially zero memory state
  3909   Node* inits = zmem;           // accumulating a linearized chain of inits
  3910   #ifdef ASSERT
  3911   intptr_t first_offset = allocation()->minimum_header_size();
  3912   intptr_t last_init_off = first_offset;  // previous init offset
  3913   intptr_t last_init_end = first_offset;  // previous init offset+size
  3914   intptr_t last_tile_end = first_offset;  // previous tile offset+size
  3915   #endif
  3916   intptr_t zeroes_done = header_size;
  3918   bool do_zeroing = true;       // we might give up if inits are very sparse
  3919   int  big_init_gaps = 0;       // how many large gaps have we seen?
  3921   if (ZeroTLAB)  do_zeroing = false;
  3922   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
  3924   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
  3925     Node* st = in(i);
  3926     intptr_t st_off = get_store_offset(st, phase);
  3927     if (st_off < 0)
  3928       break;                    // unknown junk in the inits
  3929     if (st->in(MemNode::Memory) != zmem)
  3930       break;                    // complicated store chains somehow in list
  3932     int st_size = st->as_Store()->memory_size();
  3933     intptr_t next_init_off = st_off + st_size;
  3935     if (do_zeroing && zeroes_done < next_init_off) {
  3936       // See if this store needs a zero before it or under it.
  3937       intptr_t zeroes_needed = st_off;
  3939       if (st_size < BytesPerInt) {
  3940         // Look for subword stores which only partially initialize words.
  3941         // If we find some, we must lay down some word-level zeroes first,
  3942         // underneath the subword stores.
  3943         //
  3944         // Examples:
  3945         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
  3946         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
  3947         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
  3948         //
  3949         // Note:  coalesce_subword_stores may have already done this,
  3950         // if it was prompted by constant non-zero subword initializers.
  3951         // But this case can still arise with non-constant stores.
  3953         intptr_t next_full_store = find_next_fullword_store(i, phase);
  3955         // In the examples above:
  3956         //   in(i)          p   q   r   s     x   y     z
  3957         //   st_off        12  13  14  15    12  13    14
  3958         //   st_size        1   1   1   1     1   1     1
  3959         //   next_full_s.  12  16  16  16    16  16    16
  3960         //   z's_done      12  16  16  16    12  16    12
  3961         //   z's_needed    12  16  16  16    16  16    16
  3962         //   zsize          0   0   0   0     4   0     4
  3963         if (next_full_store < 0) {
  3964           // Conservative tack:  Zero to end of current word.
  3965           zeroes_needed = align_size_up(zeroes_needed, BytesPerInt);
  3966         } else {
  3967           // Zero to beginning of next fully initialized word.
  3968           // Or, don't zero at all, if we are already in that word.
  3969           assert(next_full_store >= zeroes_needed, "must go forward");
  3970           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
  3971           zeroes_needed = next_full_store;
  3975       if (zeroes_needed > zeroes_done) {
  3976         intptr_t zsize = zeroes_needed - zeroes_done;
  3977         // Do some incremental zeroing on rawmem, in parallel with inits.
  3978         zeroes_done = align_size_down(zeroes_done, BytesPerInt);
  3979         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
  3980                                               zeroes_done, zeroes_needed,
  3981                                               phase);
  3982         zeroes_done = zeroes_needed;
  3983         if (zsize > Matcher::init_array_short_size && ++big_init_gaps > 2)
  3984           do_zeroing = false;   // leave the hole, next time
  3988     // Collect the store and move on:
  3989     st->set_req(MemNode::Memory, inits);
  3990     inits = st;                 // put it on the linearized chain
  3991     set_req(i, zmem);           // unhook from previous position
  3993     if (zeroes_done == st_off)
  3994       zeroes_done = next_init_off;
  3996     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
  3998     #ifdef ASSERT
  3999     // Various order invariants.  Weaker than stores_are_sane because
  4000     // a large constant tile can be filled in by smaller non-constant stores.
  4001     assert(st_off >= last_init_off, "inits do not reverse");
  4002     last_init_off = st_off;
  4003     const Type* val = NULL;
  4004     if (st_size >= BytesPerInt &&
  4005         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
  4006         (int)val->basic_type() < (int)T_OBJECT) {
  4007       assert(st_off >= last_tile_end, "tiles do not overlap");
  4008       assert(st_off >= last_init_end, "tiles do not overwrite inits");
  4009       last_tile_end = MAX2(last_tile_end, next_init_off);
  4010     } else {
  4011       intptr_t st_tile_end = align_size_up(next_init_off, BytesPerLong);
  4012       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
  4013       assert(st_off      >= last_init_end, "inits do not overlap");
  4014       last_init_end = next_init_off;  // it's a non-tile
  4016     #endif //ASSERT
  4019   remove_extra_zeroes();        // clear out all the zmems left over
  4020   add_req(inits);
  4022   if (!ZeroTLAB) {
  4023     // If anything remains to be zeroed, zero it all now.
  4024     zeroes_done = align_size_down(zeroes_done, BytesPerInt);
  4025     // if it is the last unused 4 bytes of an instance, forget about it
  4026     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
  4027     if (zeroes_done + BytesPerLong >= size_limit) {
  4028       assert(allocation() != NULL, "");
  4029       if (allocation()->Opcode() == Op_Allocate) {
  4030         Node* klass_node = allocation()->in(AllocateNode::KlassNode);
  4031         ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
  4032         if (zeroes_done == k->layout_helper())
  4033           zeroes_done = size_limit;
  4036     if (zeroes_done < size_limit) {
  4037       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
  4038                                             zeroes_done, size_in_bytes, phase);
  4042   set_complete(phase);
  4043   return rawmem;
  4047 #ifdef ASSERT
  4048 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
  4049   if (is_complete())
  4050     return true;                // stores could be anything at this point
  4051   assert(allocation() != NULL, "must be present");
  4052   intptr_t last_off = allocation()->minimum_header_size();
  4053   for (uint i = InitializeNode::RawStores; i < req(); i++) {
  4054     Node* st = in(i);
  4055     intptr_t st_off = get_store_offset(st, phase);
  4056     if (st_off < 0)  continue;  // ignore dead garbage
  4057     if (last_off > st_off) {
  4058       tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
  4059       this->dump(2);
  4060       assert(false, "ascending store offsets");
  4061       return false;
  4063     last_off = st_off + st->as_Store()->memory_size();
  4065   return true;
  4067 #endif //ASSERT
  4072 //============================MergeMemNode=====================================
  4073 //
  4074 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
  4075 // contributing store or call operations.  Each contributor provides the memory
  4076 // state for a particular "alias type" (see Compile::alias_type).  For example,
  4077 // if a MergeMem has an input X for alias category #6, then any memory reference
  4078 // to alias category #6 may use X as its memory state input, as an exact equivalent
  4079 // to using the MergeMem as a whole.
  4080 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
  4081 //
  4082 // (Here, the <N> notation gives the index of the relevant adr_type.)
  4083 //
  4084 // In one special case (and more cases in the future), alias categories overlap.
  4085 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
  4086 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
  4087 // it is exactly equivalent to that state W:
  4088 //   MergeMem(<Bot>: W) <==> W
  4089 //
  4090 // Usually, the merge has more than one input.  In that case, where inputs
  4091 // overlap (i.e., one is Bot), the narrower alias type determines the memory
  4092 // state for that type, and the wider alias type (Bot) fills in everywhere else:
  4093 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
  4094 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
  4095 //
  4096 // A merge can take a "wide" memory state as one of its narrow inputs.
  4097 // This simply means that the merge observes out only the relevant parts of
  4098 // the wide input.  That is, wide memory states arriving at narrow merge inputs
  4099 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
  4100 //
  4101 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
  4102 // and that memory slices "leak through":
  4103 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
  4104 //
  4105 // But, in such a cascade, repeated memory slices can "block the leak":
  4106 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
  4107 //
  4108 // In the last example, Y is not part of the combined memory state of the
  4109 // outermost MergeMem.  The system must, of course, prevent unschedulable
  4110 // memory states from arising, so you can be sure that the state Y is somehow
  4111 // a precursor to state Y'.
  4112 //
  4113 //
  4114 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
  4115 // of each MergeMemNode array are exactly the numerical alias indexes, including
  4116 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
  4117 // Compile::alias_type (and kin) produce and manage these indexes.
  4118 //
  4119 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
  4120 // (Note that this provides quick access to the top node inside MergeMem methods,
  4121 // without the need to reach out via TLS to Compile::current.)
  4122 //
  4123 // As a consequence of what was just described, a MergeMem that represents a full
  4124 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
  4125 // containing all alias categories.
  4126 //
  4127 // MergeMem nodes never (?) have control inputs, so in(0) is NULL.
  4128 //
  4129 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
  4130 // a memory state for the alias type <N>, or else the top node, meaning that
  4131 // there is no particular input for that alias type.  Note that the length of
  4132 // a MergeMem is variable, and may be extended at any time to accommodate new
  4133 // memory states at larger alias indexes.  When merges grow, they are of course
  4134 // filled with "top" in the unused in() positions.
  4135 //
  4136 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
  4137 // (Top was chosen because it works smoothly with passes like GCM.)
  4138 //
  4139 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
  4140 // the type of random VM bits like TLS references.)  Since it is always the
  4141 // first non-Bot memory slice, some low-level loops use it to initialize an
  4142 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
  4143 //
  4144 //
  4145 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
  4146 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
  4147 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
  4148 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
  4149 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
  4150 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
  4151 //
  4152 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
  4153 // really that different from the other memory inputs.  An abbreviation called
  4154 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
  4155 //
  4156 //
  4157 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
  4158 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
  4159 // that "emerges though" the base memory will be marked as excluding the alias types
  4160 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
  4161 //
  4162 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
  4163 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
  4164 //
  4165 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
  4166 // (It is currently unimplemented.)  As you can see, the resulting merge is
  4167 // actually a disjoint union of memory states, rather than an overlay.
  4168 //
  4170 //------------------------------MergeMemNode-----------------------------------
  4171 Node* MergeMemNode::make_empty_memory() {
  4172   Node* empty_memory = (Node*) Compile::current()->top();
  4173   assert(empty_memory->is_top(), "correct sentinel identity");
  4174   return empty_memory;
  4177 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
  4178   init_class_id(Class_MergeMem);
  4179   // all inputs are nullified in Node::Node(int)
  4180   // set_input(0, NULL);  // no control input
  4182   // Initialize the edges uniformly to top, for starters.
  4183   Node* empty_mem = make_empty_memory();
  4184   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
  4185     init_req(i,empty_mem);
  4187   assert(empty_memory() == empty_mem, "");
  4189   if( new_base != NULL && new_base->is_MergeMem() ) {
  4190     MergeMemNode* mdef = new_base->as_MergeMem();
  4191     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
  4192     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
  4193       mms.set_memory(mms.memory2());
  4195     assert(base_memory() == mdef->base_memory(), "");
  4196   } else {
  4197     set_base_memory(new_base);
  4201 // Make a new, untransformed MergeMem with the same base as 'mem'.
  4202 // If mem is itself a MergeMem, populate the result with the same edges.
  4203 MergeMemNode* MergeMemNode::make(Compile* C, Node* mem) {
  4204   return new(C) MergeMemNode(mem);
  4207 //------------------------------cmp--------------------------------------------
  4208 uint MergeMemNode::hash() const { return NO_HASH; }
  4209 uint MergeMemNode::cmp( const Node &n ) const {
  4210   return (&n == this);          // Always fail except on self
  4213 //------------------------------Identity---------------------------------------
  4214 Node* MergeMemNode::Identity(PhaseTransform *phase) {
  4215   // Identity if this merge point does not record any interesting memory
  4216   // disambiguations.
  4217   Node* base_mem = base_memory();
  4218   Node* empty_mem = empty_memory();
  4219   if (base_mem != empty_mem) {  // Memory path is not dead?
  4220     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  4221       Node* mem = in(i);
  4222       if (mem != empty_mem && mem != base_mem) {
  4223         return this;            // Many memory splits; no change
  4227   return base_mem;              // No memory splits; ID on the one true input
  4230 //------------------------------Ideal------------------------------------------
  4231 // This method is invoked recursively on chains of MergeMem nodes
  4232 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  4233   // Remove chain'd MergeMems
  4234   //
  4235   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
  4236   // relative to the "in(Bot)".  Since we are patching both at the same time,
  4237   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
  4238   // but rewrite each "in(i)" relative to the new "in(Bot)".
  4239   Node *progress = NULL;
  4242   Node* old_base = base_memory();
  4243   Node* empty_mem = empty_memory();
  4244   if (old_base == empty_mem)
  4245     return NULL; // Dead memory path.
  4247   MergeMemNode* old_mbase;
  4248   if (old_base != NULL && old_base->is_MergeMem())
  4249     old_mbase = old_base->as_MergeMem();
  4250   else
  4251     old_mbase = NULL;
  4252   Node* new_base = old_base;
  4254   // simplify stacked MergeMems in base memory
  4255   if (old_mbase)  new_base = old_mbase->base_memory();
  4257   // the base memory might contribute new slices beyond my req()
  4258   if (old_mbase)  grow_to_match(old_mbase);
  4260   // Look carefully at the base node if it is a phi.
  4261   PhiNode* phi_base;
  4262   if (new_base != NULL && new_base->is_Phi())
  4263     phi_base = new_base->as_Phi();
  4264   else
  4265     phi_base = NULL;
  4267   Node*    phi_reg = NULL;
  4268   uint     phi_len = (uint)-1;
  4269   if (phi_base != NULL && !phi_base->is_copy()) {
  4270     // do not examine phi if degraded to a copy
  4271     phi_reg = phi_base->region();
  4272     phi_len = phi_base->req();
  4273     // see if the phi is unfinished
  4274     for (uint i = 1; i < phi_len; i++) {
  4275       if (phi_base->in(i) == NULL) {
  4276         // incomplete phi; do not look at it yet!
  4277         phi_reg = NULL;
  4278         phi_len = (uint)-1;
  4279         break;
  4284   // Note:  We do not call verify_sparse on entry, because inputs
  4285   // can normalize to the base_memory via subsume_node or similar
  4286   // mechanisms.  This method repairs that damage.
  4288   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
  4290   // Look at each slice.
  4291   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  4292     Node* old_in = in(i);
  4293     // calculate the old memory value
  4294     Node* old_mem = old_in;
  4295     if (old_mem == empty_mem)  old_mem = old_base;
  4296     assert(old_mem == memory_at(i), "");
  4298     // maybe update (reslice) the old memory value
  4300     // simplify stacked MergeMems
  4301     Node* new_mem = old_mem;
  4302     MergeMemNode* old_mmem;
  4303     if (old_mem != NULL && old_mem->is_MergeMem())
  4304       old_mmem = old_mem->as_MergeMem();
  4305     else
  4306       old_mmem = NULL;
  4307     if (old_mmem == this) {
  4308       // This can happen if loops break up and safepoints disappear.
  4309       // A merge of BotPtr (default) with a RawPtr memory derived from a
  4310       // safepoint can be rewritten to a merge of the same BotPtr with
  4311       // the BotPtr phi coming into the loop.  If that phi disappears
  4312       // also, we can end up with a self-loop of the mergemem.
  4313       // In general, if loops degenerate and memory effects disappear,
  4314       // a mergemem can be left looking at itself.  This simply means
  4315       // that the mergemem's default should be used, since there is
  4316       // no longer any apparent effect on this slice.
  4317       // Note: If a memory slice is a MergeMem cycle, it is unreachable
  4318       //       from start.  Update the input to TOP.
  4319       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
  4321     else if (old_mmem != NULL) {
  4322       new_mem = old_mmem->memory_at(i);
  4324     // else preceding memory was not a MergeMem
  4326     // replace equivalent phis (unfortunately, they do not GVN together)
  4327     if (new_mem != NULL && new_mem != new_base &&
  4328         new_mem->req() == phi_len && new_mem->in(0) == phi_reg) {
  4329       if (new_mem->is_Phi()) {
  4330         PhiNode* phi_mem = new_mem->as_Phi();
  4331         for (uint i = 1; i < phi_len; i++) {
  4332           if (phi_base->in(i) != phi_mem->in(i)) {
  4333             phi_mem = NULL;
  4334             break;
  4337         if (phi_mem != NULL) {
  4338           // equivalent phi nodes; revert to the def
  4339           new_mem = new_base;
  4344     // maybe store down a new value
  4345     Node* new_in = new_mem;
  4346     if (new_in == new_base)  new_in = empty_mem;
  4348     if (new_in != old_in) {
  4349       // Warning:  Do not combine this "if" with the previous "if"
  4350       // A memory slice might have be be rewritten even if it is semantically
  4351       // unchanged, if the base_memory value has changed.
  4352       set_req(i, new_in);
  4353       progress = this;          // Report progress
  4357   if (new_base != old_base) {
  4358     set_req(Compile::AliasIdxBot, new_base);
  4359     // Don't use set_base_memory(new_base), because we need to update du.
  4360     assert(base_memory() == new_base, "");
  4361     progress = this;
  4364   if( base_memory() == this ) {
  4365     // a self cycle indicates this memory path is dead
  4366     set_req(Compile::AliasIdxBot, empty_mem);
  4369   // Resolve external cycles by calling Ideal on a MergeMem base_memory
  4370   // Recursion must occur after the self cycle check above
  4371   if( base_memory()->is_MergeMem() ) {
  4372     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
  4373     Node *m = phase->transform(new_mbase);  // Rollup any cycles
  4374     if( m != NULL && (m->is_top() ||
  4375         m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem) ) {
  4376       // propagate rollup of dead cycle to self
  4377       set_req(Compile::AliasIdxBot, empty_mem);
  4381   if( base_memory() == empty_mem ) {
  4382     progress = this;
  4383     // Cut inputs during Parse phase only.
  4384     // During Optimize phase a dead MergeMem node will be subsumed by Top.
  4385     if( !can_reshape ) {
  4386       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  4387         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
  4392   if( !progress && base_memory()->is_Phi() && can_reshape ) {
  4393     // Check if PhiNode::Ideal's "Split phis through memory merges"
  4394     // transform should be attempted. Look for this->phi->this cycle.
  4395     uint merge_width = req();
  4396     if (merge_width > Compile::AliasIdxRaw) {
  4397       PhiNode* phi = base_memory()->as_Phi();
  4398       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
  4399         if (phi->in(i) == this) {
  4400           phase->is_IterGVN()->_worklist.push(phi);
  4401           break;
  4407   assert(progress || verify_sparse(), "please, no dups of base");
  4408   return progress;
  4411 //-------------------------set_base_memory-------------------------------------
  4412 void MergeMemNode::set_base_memory(Node *new_base) {
  4413   Node* empty_mem = empty_memory();
  4414   set_req(Compile::AliasIdxBot, new_base);
  4415   assert(memory_at(req()) == new_base, "must set default memory");
  4416   // Clear out other occurrences of new_base:
  4417   if (new_base != empty_mem) {
  4418     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  4419       if (in(i) == new_base)  set_req(i, empty_mem);
  4424 //------------------------------out_RegMask------------------------------------
  4425 const RegMask &MergeMemNode::out_RegMask() const {
  4426   return RegMask::Empty;
  4429 //------------------------------dump_spec--------------------------------------
  4430 #ifndef PRODUCT
  4431 void MergeMemNode::dump_spec(outputStream *st) const {
  4432   st->print(" {");
  4433   Node* base_mem = base_memory();
  4434   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
  4435     Node* mem = memory_at(i);
  4436     if (mem == base_mem) { st->print(" -"); continue; }
  4437     st->print( " N%d:", mem->_idx );
  4438     Compile::current()->get_adr_type(i)->dump_on(st);
  4440   st->print(" }");
  4442 #endif // !PRODUCT
  4445 #ifdef ASSERT
  4446 static bool might_be_same(Node* a, Node* b) {
  4447   if (a == b)  return true;
  4448   if (!(a->is_Phi() || b->is_Phi()))  return false;
  4449   // phis shift around during optimization
  4450   return true;  // pretty stupid...
  4453 // verify a narrow slice (either incoming or outgoing)
  4454 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
  4455   if (!VerifyAliases)       return;  // don't bother to verify unless requested
  4456   if (is_error_reported())  return;  // muzzle asserts when debugging an error
  4457   if (Node::in_dump())      return;  // muzzle asserts when printing
  4458   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
  4459   assert(n != NULL, "");
  4460   // Elide intervening MergeMem's
  4461   while (n->is_MergeMem()) {
  4462     n = n->as_MergeMem()->memory_at(alias_idx);
  4464   Compile* C = Compile::current();
  4465   const TypePtr* n_adr_type = n->adr_type();
  4466   if (n == m->empty_memory()) {
  4467     // Implicit copy of base_memory()
  4468   } else if (n_adr_type != TypePtr::BOTTOM) {
  4469     assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
  4470     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
  4471   } else {
  4472     // A few places like make_runtime_call "know" that VM calls are narrow,
  4473     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
  4474     bool expected_wide_mem = false;
  4475     if (n == m->base_memory()) {
  4476       expected_wide_mem = true;
  4477     } else if (alias_idx == Compile::AliasIdxRaw ||
  4478                n == m->memory_at(Compile::AliasIdxRaw)) {
  4479       expected_wide_mem = true;
  4480     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
  4481       // memory can "leak through" calls on channels that
  4482       // are write-once.  Allow this also.
  4483       expected_wide_mem = true;
  4485     assert(expected_wide_mem, "expected narrow slice replacement");
  4488 #else // !ASSERT
  4489 #define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
  4490 #endif
  4493 //-----------------------------memory_at---------------------------------------
  4494 Node* MergeMemNode::memory_at(uint alias_idx) const {
  4495   assert(alias_idx >= Compile::AliasIdxRaw ||
  4496          alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
  4497          "must avoid base_memory and AliasIdxTop");
  4499   // Otherwise, it is a narrow slice.
  4500   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
  4501   Compile *C = Compile::current();
  4502   if (is_empty_memory(n)) {
  4503     // the array is sparse; empty slots are the "top" node
  4504     n = base_memory();
  4505     assert(Node::in_dump()
  4506            || n == NULL || n->bottom_type() == Type::TOP
  4507            || n->adr_type() == NULL // address is TOP
  4508            || n->adr_type() == TypePtr::BOTTOM
  4509            || n->adr_type() == TypeRawPtr::BOTTOM
  4510            || Compile::current()->AliasLevel() == 0,
  4511            "must be a wide memory");
  4512     // AliasLevel == 0 if we are organizing the memory states manually.
  4513     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
  4514   } else {
  4515     // make sure the stored slice is sane
  4516     #ifdef ASSERT
  4517     if (is_error_reported() || Node::in_dump()) {
  4518     } else if (might_be_same(n, base_memory())) {
  4519       // Give it a pass:  It is a mostly harmless repetition of the base.
  4520       // This can arise normally from node subsumption during optimization.
  4521     } else {
  4522       verify_memory_slice(this, alias_idx, n);
  4524     #endif
  4526   return n;
  4529 //---------------------------set_memory_at-------------------------------------
  4530 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
  4531   verify_memory_slice(this, alias_idx, n);
  4532   Node* empty_mem = empty_memory();
  4533   if (n == base_memory())  n = empty_mem;  // collapse default
  4534   uint need_req = alias_idx+1;
  4535   if (req() < need_req) {
  4536     if (n == empty_mem)  return;  // already the default, so do not grow me
  4537     // grow the sparse array
  4538     do {
  4539       add_req(empty_mem);
  4540     } while (req() < need_req);
  4542   set_req( alias_idx, n );
  4547 //--------------------------iteration_setup------------------------------------
  4548 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
  4549   if (other != NULL) {
  4550     grow_to_match(other);
  4551     // invariant:  the finite support of mm2 is within mm->req()
  4552     #ifdef ASSERT
  4553     for (uint i = req(); i < other->req(); i++) {
  4554       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
  4556     #endif
  4558   // Replace spurious copies of base_memory by top.
  4559   Node* base_mem = base_memory();
  4560   if (base_mem != NULL && !base_mem->is_top()) {
  4561     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
  4562       if (in(i) == base_mem)
  4563         set_req(i, empty_memory());
  4568 //---------------------------grow_to_match-------------------------------------
  4569 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
  4570   Node* empty_mem = empty_memory();
  4571   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
  4572   // look for the finite support of the other memory
  4573   for (uint i = other->req(); --i >= req(); ) {
  4574     if (other->in(i) != empty_mem) {
  4575       uint new_len = i+1;
  4576       while (req() < new_len)  add_req(empty_mem);
  4577       break;
  4582 //---------------------------verify_sparse-------------------------------------
  4583 #ifndef PRODUCT
  4584 bool MergeMemNode::verify_sparse() const {
  4585   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
  4586   Node* base_mem = base_memory();
  4587   // The following can happen in degenerate cases, since empty==top.
  4588   if (is_empty_memory(base_mem))  return true;
  4589   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  4590     assert(in(i) != NULL, "sane slice");
  4591     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
  4593   return true;
  4596 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
  4597   Node* n;
  4598   n = mm->in(idx);
  4599   if (mem == n)  return true;  // might be empty_memory()
  4600   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
  4601   if (mem == n)  return true;
  4602   while (n->is_Phi() && (n = n->as_Phi()->is_copy()) != NULL) {
  4603     if (mem == n)  return true;
  4604     if (n == NULL)  break;
  4606   return false;
  4608 #endif // !PRODUCT

mercurial