src/share/vm/opto/memnode.cpp

Thu, 24 May 2018 19:26:50 +0800

author
aoqi
date
Thu, 24 May 2018 19:26:50 +0800
changeset 8862
fd13a567f179
parent 8856
ac27a9c85bea
child 9041
95a08233f46c
permissions
-rw-r--r--

#7046 C2 supports long branch
Contributed-by: fujie

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

mercurial