src/share/vm/opto/memnode.cpp

Wed, 16 Jul 2008 16:04:39 -0700

author
kvn
date
Wed, 16 Jul 2008 16:04:39 -0700
changeset 682
02a35ad4adf8
parent 670
9c2ecc2ffb12
child 688
b0fe4deeb9fb
permissions
-rw-r--r--

6723160: Nightly failure: Error: meet not symmetric
Summary: Add missing _instance_id settings and other EA fixes.
Reviewed-by: rasbold

     1 /*
     2  * Copyright 1997-2008 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 // Portions of code courtesy of Clifford Click
    27 // Optimization - Graph Style
    29 #include "incls/_precompiled.incl"
    30 #include "incls/_memnode.cpp.incl"
    32 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
    34 //=============================================================================
    35 uint MemNode::size_of() const { return sizeof(*this); }
    37 const TypePtr *MemNode::adr_type() const {
    38   Node* adr = in(Address);
    39   const TypePtr* cross_check = NULL;
    40   DEBUG_ONLY(cross_check = _adr_type);
    41   return calculate_adr_type(adr->bottom_type(), cross_check);
    42 }
    44 #ifndef PRODUCT
    45 void MemNode::dump_spec(outputStream *st) const {
    46   if (in(Address) == NULL)  return; // node is dead
    47 #ifndef ASSERT
    48   // fake the missing field
    49   const TypePtr* _adr_type = NULL;
    50   if (in(Address) != NULL)
    51     _adr_type = in(Address)->bottom_type()->isa_ptr();
    52 #endif
    53   dump_adr_type(this, _adr_type, st);
    55   Compile* C = Compile::current();
    56   if( C->alias_type(_adr_type)->is_volatile() )
    57     st->print(" Volatile!");
    58 }
    60 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
    61   st->print(" @");
    62   if (adr_type == NULL) {
    63     st->print("NULL");
    64   } else {
    65     adr_type->dump_on(st);
    66     Compile* C = Compile::current();
    67     Compile::AliasType* atp = NULL;
    68     if (C->have_alias_type(adr_type))  atp = C->alias_type(adr_type);
    69     if (atp == NULL)
    70       st->print(", idx=?\?;");
    71     else if (atp->index() == Compile::AliasIdxBot)
    72       st->print(", idx=Bot;");
    73     else if (atp->index() == Compile::AliasIdxTop)
    74       st->print(", idx=Top;");
    75     else if (atp->index() == Compile::AliasIdxRaw)
    76       st->print(", idx=Raw;");
    77     else {
    78       ciField* field = atp->field();
    79       if (field) {
    80         st->print(", name=");
    81         field->print_name_on(st);
    82       }
    83       st->print(", idx=%d;", atp->index());
    84     }
    85   }
    86 }
    88 extern void print_alias_types();
    90 #endif
    92 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypePtr *t_adr, PhaseGVN *phase) {
    93   const TypeOopPtr *tinst = t_adr->isa_oopptr();
    94   if (tinst == NULL || !tinst->is_known_instance_field())
    95     return mchain;  // don't try to optimize non-instance types
    96   uint instance_id = tinst->instance_id();
    97   Node *prev = NULL;
    98   Node *result = mchain;
    99   while (prev != result) {
   100     prev = result;
   101     // skip over a call which does not affect this memory slice
   102     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
   103       Node *proj_in = result->in(0);
   104       if (proj_in->is_Call()) {
   105         CallNode *call = proj_in->as_Call();
   106         if (!call->may_modify(t_adr, phase)) {
   107           result = call->in(TypeFunc::Memory);
   108         }
   109       } else if (proj_in->is_Initialize()) {
   110         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
   111         // Stop if this is the initialization for the object instance which
   112         // which contains this memory slice, otherwise skip over it.
   113         if (alloc != NULL && alloc->_idx != instance_id) {
   114           result = proj_in->in(TypeFunc::Memory);
   115         }
   116       } else if (proj_in->is_MemBar()) {
   117         result = proj_in->in(TypeFunc::Memory);
   118       }
   119     } else if (result->is_MergeMem()) {
   120       result = step_through_mergemem(phase, result->as_MergeMem(), t_adr, NULL, tty);
   121     }
   122   }
   123   return result;
   124 }
   126 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, PhaseGVN *phase) {
   127   const TypeOopPtr *t_oop = t_adr->isa_oopptr();
   128   bool is_instance = (t_oop != NULL) && t_oop->is_known_instance_field();
   129   PhaseIterGVN *igvn = phase->is_IterGVN();
   130   Node *result = mchain;
   131   result = optimize_simple_memory_chain(result, t_adr, phase);
   132   if (is_instance && igvn != NULL  && result->is_Phi()) {
   133     PhiNode *mphi = result->as_Phi();
   134     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
   135     const TypePtr *t = mphi->adr_type();
   136     if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ||
   137         t->isa_oopptr() && !t->is_oopptr()->is_known_instance() &&
   138         t->is_oopptr()->cast_to_exactness(true)
   139          ->is_oopptr()->cast_to_ptr_type(t_oop->ptr())
   140          ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop) {
   141       // clone the Phi with our address type
   142       result = mphi->split_out_instance(t_adr, igvn);
   143     } else {
   144       assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
   145     }
   146   }
   147   return result;
   148 }
   150 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
   151   uint alias_idx = phase->C->get_alias_index(tp);
   152   Node *mem = mmem;
   153 #ifdef ASSERT
   154   {
   155     // Check that current type is consistent with the alias index used during graph construction
   156     assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
   157     bool consistent =  adr_check == NULL || adr_check->empty() ||
   158                        phase->C->must_alias(adr_check, alias_idx );
   159     // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
   160     if( !consistent && adr_check != NULL && !adr_check->empty() &&
   161                tp->isa_aryptr() &&        tp->offset() == Type::OffsetBot &&
   162         adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
   163         ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
   164           adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
   165           adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
   166       // don't assert if it is dead code.
   167       consistent = true;
   168     }
   169     if( !consistent ) {
   170       st->print("alias_idx==%d, adr_check==", alias_idx);
   171       if( adr_check == NULL ) {
   172         st->print("NULL");
   173       } else {
   174         adr_check->dump();
   175       }
   176       st->cr();
   177       print_alias_types();
   178       assert(consistent, "adr_check must match alias idx");
   179     }
   180   }
   181 #endif
   182   // TypeInstPtr::NOTNULL+any is an OOP with unknown offset - generally
   183   // means an array I have not precisely typed yet.  Do not do any
   184   // alias stuff with it any time soon.
   185   const TypeOopPtr *tinst = tp->isa_oopptr();
   186   if( tp->base() != Type::AnyPtr &&
   187       !(tinst &&
   188         tinst->klass()->is_java_lang_Object() &&
   189         tinst->offset() == Type::OffsetBot) ) {
   190     // compress paths and change unreachable cycles to TOP
   191     // If not, we can update the input infinitely along a MergeMem cycle
   192     // Equivalent code in PhiNode::Ideal
   193     Node* m  = phase->transform(mmem);
   194     // If tranformed to a MergeMem, get the desired slice
   195     // Otherwise the returned node represents memory for every slice
   196     mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
   197     // Update input if it is progress over what we have now
   198   }
   199   return mem;
   200 }
   202 //--------------------------Ideal_common---------------------------------------
   203 // Look for degenerate control and memory inputs.  Bypass MergeMem inputs.
   204 // Unhook non-raw memories from complete (macro-expanded) initializations.
   205 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
   206   // If our control input is a dead region, kill all below the region
   207   Node *ctl = in(MemNode::Control);
   208   if (ctl && remove_dead_region(phase, can_reshape))
   209     return this;
   211   // Ignore if memory is dead, or self-loop
   212   Node *mem = in(MemNode::Memory);
   213   if( phase->type( mem ) == Type::TOP ) return NodeSentinel; // caller will return NULL
   214   assert( mem != this, "dead loop in MemNode::Ideal" );
   216   Node *address = in(MemNode::Address);
   217   const Type *t_adr = phase->type( address );
   218   if( t_adr == Type::TOP )              return NodeSentinel; // caller will return NULL
   220   // Avoid independent memory operations
   221   Node* old_mem = mem;
   223   // The code which unhooks non-raw memories from complete (macro-expanded)
   224   // initializations was removed. After macro-expansion all stores catched
   225   // by Initialize node became raw stores and there is no information
   226   // which memory slices they modify. So it is unsafe to move any memory
   227   // operation above these stores. Also in most cases hooked non-raw memories
   228   // were already unhooked by using information from detect_ptr_independence()
   229   // and find_previous_store().
   231   if (mem->is_MergeMem()) {
   232     MergeMemNode* mmem = mem->as_MergeMem();
   233     const TypePtr *tp = t_adr->is_ptr();
   235     mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
   236   }
   238   if (mem != old_mem) {
   239     set_req(MemNode::Memory, mem);
   240     return this;
   241   }
   243   // let the subclass continue analyzing...
   244   return NULL;
   245 }
   247 // Helper function for proving some simple control dominations.
   248 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
   249 // Already assumes that 'dom' is available at 'sub', and that 'sub'
   250 // is not a constant (dominated by the method's StartNode).
   251 // Used by MemNode::find_previous_store to prove that the
   252 // control input of a memory operation predates (dominates)
   253 // an allocation it wants to look past.
   254 bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
   255   if (dom == NULL || dom->is_top() || sub == NULL || sub->is_top())
   256     return false; // Conservative answer for dead code
   258   // Check 'dom'. Skip Proj and CatchProj nodes.
   259   dom = dom->find_exact_control(dom);
   260   if (dom == NULL || dom->is_top())
   261     return false; // Conservative answer for dead code
   263   if (dom == sub) {
   264     // For the case when, for example, 'sub' is Initialize and the original
   265     // 'dom' is Proj node of the 'sub'.
   266     return false;
   267   }
   269   if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub)
   270     return true;
   272   // 'dom' dominates 'sub' if its control edge and control edges
   273   // of all its inputs dominate or equal to sub's control edge.
   275   // Currently 'sub' is either Allocate, Initialize or Start nodes.
   276   // Or Region for the check in LoadNode::Ideal();
   277   // 'sub' should have sub->in(0) != NULL.
   278   assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() ||
   279          sub->is_Region(), "expecting only these nodes");
   281   // Get control edge of 'sub'.
   282   Node* orig_sub = sub;
   283   sub = sub->find_exact_control(sub->in(0));
   284   if (sub == NULL || sub->is_top())
   285     return false; // Conservative answer for dead code
   287   assert(sub->is_CFG(), "expecting control");
   289   if (sub == dom)
   290     return true;
   292   if (sub->is_Start() || sub->is_Root())
   293     return false;
   295   {
   296     // Check all control edges of 'dom'.
   298     ResourceMark rm;
   299     Arena* arena = Thread::current()->resource_area();
   300     Node_List nlist(arena);
   301     Unique_Node_List dom_list(arena);
   303     dom_list.push(dom);
   304     bool only_dominating_controls = false;
   306     for (uint next = 0; next < dom_list.size(); next++) {
   307       Node* n = dom_list.at(next);
   308       if (n == orig_sub)
   309         return false; // One of dom's inputs dominated by sub.
   310       if (!n->is_CFG() && n->pinned()) {
   311         // Check only own control edge for pinned non-control nodes.
   312         n = n->find_exact_control(n->in(0));
   313         if (n == NULL || n->is_top())
   314           return false; // Conservative answer for dead code
   315         assert(n->is_CFG(), "expecting control");
   316         dom_list.push(n);
   317       } else if (n->is_Con() || n->is_Start() || n->is_Root()) {
   318         only_dominating_controls = true;
   319       } else if (n->is_CFG()) {
   320         if (n->dominates(sub, nlist))
   321           only_dominating_controls = true;
   322         else
   323           return false;
   324       } else {
   325         // First, own control edge.
   326         Node* m = n->find_exact_control(n->in(0));
   327         if (m != NULL) {
   328           if (m->is_top())
   329             return false; // Conservative answer for dead code
   330           dom_list.push(m);
   331         }
   332         // Now, the rest of edges.
   333         uint cnt = n->req();
   334         for (uint i = 1; i < cnt; i++) {
   335           m = n->find_exact_control(n->in(i));
   336           if (m == NULL || m->is_top())
   337             continue;
   338           dom_list.push(m);
   339         }
   340       }
   341     }
   342     return only_dominating_controls;
   343   }
   344 }
   346 //---------------------detect_ptr_independence---------------------------------
   347 // Used by MemNode::find_previous_store to prove that two base
   348 // pointers are never equal.
   349 // The pointers are accompanied by their associated allocations,
   350 // if any, which have been previously discovered by the caller.
   351 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
   352                                       Node* p2, AllocateNode* a2,
   353                                       PhaseTransform* phase) {
   354   // Attempt to prove that these two pointers cannot be aliased.
   355   // They may both manifestly be allocations, and they should differ.
   356   // Or, if they are not both allocations, they can be distinct constants.
   357   // Otherwise, one is an allocation and the other a pre-existing value.
   358   if (a1 == NULL && a2 == NULL) {           // neither an allocation
   359     return (p1 != p2) && p1->is_Con() && p2->is_Con();
   360   } else if (a1 != NULL && a2 != NULL) {    // both allocations
   361     return (a1 != a2);
   362   } else if (a1 != NULL) {                  // one allocation a1
   363     // (Note:  p2->is_Con implies p2->in(0)->is_Root, which dominates.)
   364     return all_controls_dominate(p2, a1);
   365   } else { //(a2 != NULL)                   // one allocation a2
   366     return all_controls_dominate(p1, a2);
   367   }
   368   return false;
   369 }
   372 // The logic for reordering loads and stores uses four steps:
   373 // (a) Walk carefully past stores and initializations which we
   374 //     can prove are independent of this load.
   375 // (b) Observe that the next memory state makes an exact match
   376 //     with self (load or store), and locate the relevant store.
   377 // (c) Ensure that, if we were to wire self directly to the store,
   378 //     the optimizer would fold it up somehow.
   379 // (d) Do the rewiring, and return, depending on some other part of
   380 //     the optimizer to fold up the load.
   381 // This routine handles steps (a) and (b).  Steps (c) and (d) are
   382 // specific to loads and stores, so they are handled by the callers.
   383 // (Currently, only LoadNode::Ideal has steps (c), (d).  More later.)
   384 //
   385 Node* MemNode::find_previous_store(PhaseTransform* phase) {
   386   Node*         ctrl   = in(MemNode::Control);
   387   Node*         adr    = in(MemNode::Address);
   388   intptr_t      offset = 0;
   389   Node*         base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
   390   AllocateNode* alloc  = AllocateNode::Ideal_allocation(base, phase);
   392   if (offset == Type::OffsetBot)
   393     return NULL;            // cannot unalias unless there are precise offsets
   395   const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
   397   intptr_t size_in_bytes = memory_size();
   399   Node* mem = in(MemNode::Memory);   // start searching here...
   401   int cnt = 50;             // Cycle limiter
   402   for (;;) {                // While we can dance past unrelated stores...
   403     if (--cnt < 0)  break;  // Caught in cycle or a complicated dance?
   405     if (mem->is_Store()) {
   406       Node* st_adr = mem->in(MemNode::Address);
   407       intptr_t st_offset = 0;
   408       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
   409       if (st_base == NULL)
   410         break;              // inscrutable pointer
   411       if (st_offset != offset && st_offset != Type::OffsetBot) {
   412         const int MAX_STORE = BytesPerLong;
   413         if (st_offset >= offset + size_in_bytes ||
   414             st_offset <= offset - MAX_STORE ||
   415             st_offset <= offset - mem->as_Store()->memory_size()) {
   416           // Success:  The offsets are provably independent.
   417           // (You may ask, why not just test st_offset != offset and be done?
   418           // The answer is that stores of different sizes can co-exist
   419           // in the same sequence of RawMem effects.  We sometimes initialize
   420           // a whole 'tile' of array elements with a single jint or jlong.)
   421           mem = mem->in(MemNode::Memory);
   422           continue;           // (a) advance through independent store memory
   423         }
   424       }
   425       if (st_base != base &&
   426           detect_ptr_independence(base, alloc,
   427                                   st_base,
   428                                   AllocateNode::Ideal_allocation(st_base, phase),
   429                                   phase)) {
   430         // Success:  The bases are provably independent.
   431         mem = mem->in(MemNode::Memory);
   432         continue;           // (a) advance through independent store memory
   433       }
   435       // (b) At this point, if the bases or offsets do not agree, we lose,
   436       // since we have not managed to prove 'this' and 'mem' independent.
   437       if (st_base == base && st_offset == offset) {
   438         return mem;         // let caller handle steps (c), (d)
   439       }
   441     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
   442       InitializeNode* st_init = mem->in(0)->as_Initialize();
   443       AllocateNode*  st_alloc = st_init->allocation();
   444       if (st_alloc == NULL)
   445         break;              // something degenerated
   446       bool known_identical = false;
   447       bool known_independent = false;
   448       if (alloc == st_alloc)
   449         known_identical = true;
   450       else if (alloc != NULL)
   451         known_independent = true;
   452       else if (all_controls_dominate(this, st_alloc))
   453         known_independent = true;
   455       if (known_independent) {
   456         // The bases are provably independent: Either they are
   457         // manifestly distinct allocations, or else the control
   458         // of this load dominates the store's allocation.
   459         int alias_idx = phase->C->get_alias_index(adr_type());
   460         if (alias_idx == Compile::AliasIdxRaw) {
   461           mem = st_alloc->in(TypeFunc::Memory);
   462         } else {
   463           mem = st_init->memory(alias_idx);
   464         }
   465         continue;           // (a) advance through independent store memory
   466       }
   468       // (b) at this point, if we are not looking at a store initializing
   469       // the same allocation we are loading from, we lose.
   470       if (known_identical) {
   471         // From caller, can_see_stored_value will consult find_captured_store.
   472         return mem;         // let caller handle steps (c), (d)
   473       }
   475     } else if (addr_t != NULL && addr_t->is_known_instance_field()) {
   476       // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
   477       if (mem->is_Proj() && mem->in(0)->is_Call()) {
   478         CallNode *call = mem->in(0)->as_Call();
   479         if (!call->may_modify(addr_t, phase)) {
   480           mem = call->in(TypeFunc::Memory);
   481           continue;         // (a) advance through independent call memory
   482         }
   483       } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
   484         mem = mem->in(0)->in(TypeFunc::Memory);
   485         continue;           // (a) advance through independent MemBar memory
   486       } else if (mem->is_MergeMem()) {
   487         int alias_idx = phase->C->get_alias_index(adr_type());
   488         mem = mem->as_MergeMem()->memory_at(alias_idx);
   489         continue;           // (a) advance through independent MergeMem memory
   490       }
   491     }
   493     // Unless there is an explicit 'continue', we must bail out here,
   494     // because 'mem' is an inscrutable memory state (e.g., a call).
   495     break;
   496   }
   498   return NULL;              // bail out
   499 }
   501 //----------------------calculate_adr_type-------------------------------------
   502 // Helper function.  Notices when the given type of address hits top or bottom.
   503 // Also, asserts a cross-check of the type against the expected address type.
   504 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
   505   if (t == Type::TOP)  return NULL; // does not touch memory any more?
   506   #ifdef PRODUCT
   507   cross_check = NULL;
   508   #else
   509   if (!VerifyAliases || is_error_reported() || Node::in_dump())  cross_check = NULL;
   510   #endif
   511   const TypePtr* tp = t->isa_ptr();
   512   if (tp == NULL) {
   513     assert(cross_check == NULL || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
   514     return TypePtr::BOTTOM;           // touches lots of memory
   515   } else {
   516     #ifdef ASSERT
   517     // %%%% [phh] We don't check the alias index if cross_check is
   518     //            TypeRawPtr::BOTTOM.  Needs to be investigated.
   519     if (cross_check != NULL &&
   520         cross_check != TypePtr::BOTTOM &&
   521         cross_check != TypeRawPtr::BOTTOM) {
   522       // Recheck the alias index, to see if it has changed (due to a bug).
   523       Compile* C = Compile::current();
   524       assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
   525              "must stay in the original alias category");
   526       // The type of the address must be contained in the adr_type,
   527       // disregarding "null"-ness.
   528       // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
   529       const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
   530       assert(cross_check->meet(tp_notnull) == cross_check,
   531              "real address must not escape from expected memory type");
   532     }
   533     #endif
   534     return tp;
   535   }
   536 }
   538 //------------------------adr_phi_is_loop_invariant----------------------------
   539 // A helper function for Ideal_DU_postCCP to check if a Phi in a counted
   540 // loop is loop invariant. Make a quick traversal of Phi and associated
   541 // CastPP nodes, looking to see if they are a closed group within the loop.
   542 bool MemNode::adr_phi_is_loop_invariant(Node* adr_phi, Node* cast) {
   543   // The idea is that the phi-nest must boil down to only CastPP nodes
   544   // with the same data. This implies that any path into the loop already
   545   // includes such a CastPP, and so the original cast, whatever its input,
   546   // must be covered by an equivalent cast, with an earlier control input.
   547   ResourceMark rm;
   549   // The loop entry input of the phi should be the unique dominating
   550   // node for every Phi/CastPP in the loop.
   551   Unique_Node_List closure;
   552   closure.push(adr_phi->in(LoopNode::EntryControl));
   554   // Add the phi node and the cast to the worklist.
   555   Unique_Node_List worklist;
   556   worklist.push(adr_phi);
   557   if( cast != NULL ){
   558     if( !cast->is_ConstraintCast() ) return false;
   559     worklist.push(cast);
   560   }
   562   // Begin recursive walk of phi nodes.
   563   while( worklist.size() ){
   564     // Take a node off the worklist
   565     Node *n = worklist.pop();
   566     if( !closure.member(n) ){
   567       // Add it to the closure.
   568       closure.push(n);
   569       // Make a sanity check to ensure we don't waste too much time here.
   570       if( closure.size() > 20) return false;
   571       // This node is OK if:
   572       //  - it is a cast of an identical value
   573       //  - or it is a phi node (then we add its inputs to the worklist)
   574       // Otherwise, the node is not OK, and we presume the cast is not invariant
   575       if( n->is_ConstraintCast() ){
   576         worklist.push(n->in(1));
   577       } else if( n->is_Phi() ) {
   578         for( uint i = 1; i < n->req(); i++ ) {
   579           worklist.push(n->in(i));
   580         }
   581       } else {
   582         return false;
   583       }
   584     }
   585   }
   587   // Quit when the worklist is empty, and we've found no offending nodes.
   588   return true;
   589 }
   591 //------------------------------Ideal_DU_postCCP-------------------------------
   592 // Find any cast-away of null-ness and keep its control.  Null cast-aways are
   593 // going away in this pass and we need to make this memory op depend on the
   594 // gating null check.
   595 Node *MemNode::Ideal_DU_postCCP( PhaseCCP *ccp ) {
   596   return Ideal_common_DU_postCCP(ccp, this, in(MemNode::Address));
   597 }
   599 // I tried to leave the CastPP's in.  This makes the graph more accurate in
   600 // some sense; we get to keep around the knowledge that an oop is not-null
   601 // after some test.  Alas, the CastPP's interfere with GVN (some values are
   602 // the regular oop, some are the CastPP of the oop, all merge at Phi's which
   603 // cannot collapse, etc).  This cost us 10% on SpecJVM, even when I removed
   604 // some of the more trivial cases in the optimizer.  Removing more useless
   605 // Phi's started allowing Loads to illegally float above null checks.  I gave
   606 // up on this approach.  CNC 10/20/2000
   607 // This static method may be called not from MemNode (EncodePNode calls it).
   608 // Only the control edge of the node 'n' might be updated.
   609 Node *MemNode::Ideal_common_DU_postCCP( PhaseCCP *ccp, Node* n, Node* adr ) {
   610   Node *skipped_cast = NULL;
   611   // Need a null check?  Regular static accesses do not because they are
   612   // from constant addresses.  Array ops are gated by the range check (which
   613   // always includes a NULL check).  Just check field ops.
   614   if( n->in(MemNode::Control) == NULL ) {
   615     // Scan upwards for the highest location we can place this memory op.
   616     while( true ) {
   617       switch( adr->Opcode() ) {
   619       case Op_AddP:             // No change to NULL-ness, so peek thru AddP's
   620         adr = adr->in(AddPNode::Base);
   621         continue;
   623       case Op_DecodeN:         // No change to NULL-ness, so peek thru
   624         adr = adr->in(1);
   625         continue;
   627       case Op_CastPP:
   628         // If the CastPP is useless, just peek on through it.
   629         if( ccp->type(adr) == ccp->type(adr->in(1)) ) {
   630           // Remember the cast that we've peeked though. If we peek
   631           // through more than one, then we end up remembering the highest
   632           // one, that is, if in a loop, the one closest to the top.
   633           skipped_cast = adr;
   634           adr = adr->in(1);
   635           continue;
   636         }
   637         // CastPP is going away in this pass!  We need this memory op to be
   638         // control-dependent on the test that is guarding the CastPP.
   639         ccp->hash_delete(n);
   640         n->set_req(MemNode::Control, adr->in(0));
   641         ccp->hash_insert(n);
   642         return n;
   644       case Op_Phi:
   645         // Attempt to float above a Phi to some dominating point.
   646         if (adr->in(0) != NULL && adr->in(0)->is_CountedLoop()) {
   647           // If we've already peeked through a Cast (which could have set the
   648           // control), we can't float above a Phi, because the skipped Cast
   649           // may not be loop invariant.
   650           if (adr_phi_is_loop_invariant(adr, skipped_cast)) {
   651             adr = adr->in(1);
   652             continue;
   653           }
   654         }
   656         // Intentional fallthrough!
   658         // No obvious dominating point.  The mem op is pinned below the Phi
   659         // by the Phi itself.  If the Phi goes away (no true value is merged)
   660         // then the mem op can float, but not indefinitely.  It must be pinned
   661         // behind the controls leading to the Phi.
   662       case Op_CheckCastPP:
   663         // These usually stick around to change address type, however a
   664         // useless one can be elided and we still need to pick up a control edge
   665         if (adr->in(0) == NULL) {
   666           // This CheckCastPP node has NO control and is likely useless. But we
   667           // need check further up the ancestor chain for a control input to keep
   668           // the node in place. 4959717.
   669           skipped_cast = adr;
   670           adr = adr->in(1);
   671           continue;
   672         }
   673         ccp->hash_delete(n);
   674         n->set_req(MemNode::Control, adr->in(0));
   675         ccp->hash_insert(n);
   676         return n;
   678         // List of "safe" opcodes; those that implicitly block the memory
   679         // op below any null check.
   680       case Op_CastX2P:          // no null checks on native pointers
   681       case Op_Parm:             // 'this' pointer is not null
   682       case Op_LoadP:            // Loading from within a klass
   683       case Op_LoadN:            // Loading from within a klass
   684       case Op_LoadKlass:        // Loading from within a klass
   685       case Op_LoadNKlass:       // Loading from within a klass
   686       case Op_ConP:             // Loading from a klass
   687       case Op_ConN:             // Loading from a klass
   688       case Op_CreateEx:         // Sucking up the guts of an exception oop
   689       case Op_Con:              // Reading from TLS
   690       case Op_CMoveP:           // CMoveP is pinned
   691       case Op_CMoveN:           // CMoveN is pinned
   692         break;                  // No progress
   694       case Op_Proj:             // Direct call to an allocation routine
   695       case Op_SCMemProj:        // Memory state from store conditional ops
   696 #ifdef ASSERT
   697         {
   698           assert(adr->as_Proj()->_con == TypeFunc::Parms, "must be return value");
   699           const Node* call = adr->in(0);
   700           if (call->is_CallJava()) {
   701             const CallJavaNode* call_java = call->as_CallJava();
   702             const TypeTuple *r = call_java->tf()->range();
   703             assert(r->cnt() > TypeFunc::Parms, "must return value");
   704             const Type* ret_type = r->field_at(TypeFunc::Parms);
   705             assert(ret_type && ret_type->isa_ptr(), "must return pointer");
   706             // We further presume that this is one of
   707             // new_instance_Java, new_array_Java, or
   708             // the like, but do not assert for this.
   709           } else if (call->is_Allocate()) {
   710             // similar case to new_instance_Java, etc.
   711           } else if (!call->is_CallLeaf()) {
   712             // Projections from fetch_oop (OSR) are allowed as well.
   713             ShouldNotReachHere();
   714           }
   715         }
   716 #endif
   717         break;
   718       default:
   719         ShouldNotReachHere();
   720       }
   721       break;
   722     }
   723   }
   725   return  NULL;               // No progress
   726 }
   729 //=============================================================================
   730 uint LoadNode::size_of() const { return sizeof(*this); }
   731 uint LoadNode::cmp( const Node &n ) const
   732 { return !Type::cmp( _type, ((LoadNode&)n)._type ); }
   733 const Type *LoadNode::bottom_type() const { return _type; }
   734 uint LoadNode::ideal_reg() const {
   735   return Matcher::base2reg[_type->base()];
   736 }
   738 #ifndef PRODUCT
   739 void LoadNode::dump_spec(outputStream *st) const {
   740   MemNode::dump_spec(st);
   741   if( !Verbose && !WizardMode ) {
   742     // standard dump does this in Verbose and WizardMode
   743     st->print(" #"); _type->dump_on(st);
   744   }
   745 }
   746 #endif
   749 //----------------------------LoadNode::make-----------------------------------
   750 // Polymorphic factory method:
   751 Node *LoadNode::make( PhaseGVN& gvn, Node *ctl, Node *mem, Node *adr, const TypePtr* adr_type, const Type *rt, BasicType bt ) {
   752   Compile* C = gvn.C;
   754   // sanity check the alias category against the created node type
   755   assert(!(adr_type->isa_oopptr() &&
   756            adr_type->offset() == oopDesc::klass_offset_in_bytes()),
   757          "use LoadKlassNode instead");
   758   assert(!(adr_type->isa_aryptr() &&
   759            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
   760          "use LoadRangeNode instead");
   761   switch (bt) {
   762   case T_BOOLEAN:
   763   case T_BYTE:    return new (C, 3) LoadBNode(ctl, mem, adr, adr_type, rt->is_int()    );
   764   case T_INT:     return new (C, 3) LoadINode(ctl, mem, adr, adr_type, rt->is_int()    );
   765   case T_CHAR:    return new (C, 3) LoadCNode(ctl, mem, adr, adr_type, rt->is_int()    );
   766   case T_SHORT:   return new (C, 3) LoadSNode(ctl, mem, adr, adr_type, rt->is_int()    );
   767   case T_LONG:    return new (C, 3) LoadLNode(ctl, mem, adr, adr_type, rt->is_long()   );
   768   case T_FLOAT:   return new (C, 3) LoadFNode(ctl, mem, adr, adr_type, rt              );
   769   case T_DOUBLE:  return new (C, 3) LoadDNode(ctl, mem, adr, adr_type, rt              );
   770   case T_ADDRESS: return new (C, 3) LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr()    );
   771   case T_OBJECT:
   772 #ifdef _LP64
   773     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
   774       Node* load  = gvn.transform(new (C, 3) LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop()));
   775       return new (C, 2) DecodeNNode(load, load->bottom_type()->make_ptr());
   776     } else
   777 #endif
   778     {
   779       assert(!adr->bottom_type()->is_ptr_to_narrowoop(), "should have got back a narrow oop");
   780       return new (C, 3) LoadPNode(ctl, mem, adr, adr_type, rt->is_oopptr());
   781     }
   782   }
   783   ShouldNotReachHere();
   784   return (LoadNode*)NULL;
   785 }
   787 LoadLNode* LoadLNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt) {
   788   bool require_atomic = true;
   789   return new (C, 3) LoadLNode(ctl, mem, adr, adr_type, rt->is_long(), require_atomic);
   790 }
   795 //------------------------------hash-------------------------------------------
   796 uint LoadNode::hash() const {
   797   // unroll addition of interesting fields
   798   return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
   799 }
   801 //---------------------------can_see_stored_value------------------------------
   802 // This routine exists to make sure this set of tests is done the same
   803 // everywhere.  We need to make a coordinated change: first LoadNode::Ideal
   804 // will change the graph shape in a way which makes memory alive twice at the
   805 // same time (uses the Oracle model of aliasing), then some
   806 // LoadXNode::Identity will fold things back to the equivalence-class model
   807 // of aliasing.
   808 Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
   809   Node* ld_adr = in(MemNode::Address);
   811   const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
   812   Compile::AliasType* atp = tp != NULL ? phase->C->alias_type(tp) : NULL;
   813   if (EliminateAutoBox && atp != NULL && atp->index() >= Compile::AliasIdxRaw &&
   814       atp->field() != NULL && !atp->field()->is_volatile()) {
   815     uint alias_idx = atp->index();
   816     bool final = atp->field()->is_final();
   817     Node* result = NULL;
   818     Node* current = st;
   819     // Skip through chains of MemBarNodes checking the MergeMems for
   820     // new states for the slice of this load.  Stop once any other
   821     // kind of node is encountered.  Loads from final memory can skip
   822     // through any kind of MemBar but normal loads shouldn't skip
   823     // through MemBarAcquire since the could allow them to move out of
   824     // a synchronized region.
   825     while (current->is_Proj()) {
   826       int opc = current->in(0)->Opcode();
   827       if ((final && opc == Op_MemBarAcquire) ||
   828           opc == Op_MemBarRelease || opc == Op_MemBarCPUOrder) {
   829         Node* mem = current->in(0)->in(TypeFunc::Memory);
   830         if (mem->is_MergeMem()) {
   831           MergeMemNode* merge = mem->as_MergeMem();
   832           Node* new_st = merge->memory_at(alias_idx);
   833           if (new_st == merge->base_memory()) {
   834             // Keep searching
   835             current = merge->base_memory();
   836             continue;
   837           }
   838           // Save the new memory state for the slice and fall through
   839           // to exit.
   840           result = new_st;
   841         }
   842       }
   843       break;
   844     }
   845     if (result != NULL) {
   846       st = result;
   847     }
   848   }
   851   // Loop around twice in the case Load -> Initialize -> Store.
   852   // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
   853   for (int trip = 0; trip <= 1; trip++) {
   855     if (st->is_Store()) {
   856       Node* st_adr = st->in(MemNode::Address);
   857       if (!phase->eqv(st_adr, ld_adr)) {
   858         // Try harder before giving up...  Match raw and non-raw pointers.
   859         intptr_t st_off = 0;
   860         AllocateNode* alloc = AllocateNode::Ideal_allocation(st_adr, phase, st_off);
   861         if (alloc == NULL)       return NULL;
   862         intptr_t ld_off = 0;
   863         AllocateNode* allo2 = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
   864         if (alloc != allo2)      return NULL;
   865         if (ld_off != st_off)    return NULL;
   866         // At this point we have proven something like this setup:
   867         //  A = Allocate(...)
   868         //  L = LoadQ(,  AddP(CastPP(, A.Parm),, #Off))
   869         //  S = StoreQ(, AddP(,        A.Parm  , #Off), V)
   870         // (Actually, we haven't yet proven the Q's are the same.)
   871         // In other words, we are loading from a casted version of
   872         // the same pointer-and-offset that we stored to.
   873         // Thus, we are able to replace L by V.
   874       }
   875       // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
   876       if (store_Opcode() != st->Opcode())
   877         return NULL;
   878       return st->in(MemNode::ValueIn);
   879     }
   881     intptr_t offset = 0;  // scratch
   883     // A load from a freshly-created object always returns zero.
   884     // (This can happen after LoadNode::Ideal resets the load's memory input
   885     // to find_captured_store, which returned InitializeNode::zero_memory.)
   886     if (st->is_Proj() && st->in(0)->is_Allocate() &&
   887         st->in(0) == AllocateNode::Ideal_allocation(ld_adr, phase, offset) &&
   888         offset >= st->in(0)->as_Allocate()->minimum_header_size()) {
   889       // return a zero value for the load's basic type
   890       // (This is one of the few places where a generic PhaseTransform
   891       // can create new nodes.  Think of it as lazily manifesting
   892       // virtually pre-existing constants.)
   893       return phase->zerocon(memory_type());
   894     }
   896     // A load from an initialization barrier can match a captured store.
   897     if (st->is_Proj() && st->in(0)->is_Initialize()) {
   898       InitializeNode* init = st->in(0)->as_Initialize();
   899       AllocateNode* alloc = init->allocation();
   900       if (alloc != NULL &&
   901           alloc == AllocateNode::Ideal_allocation(ld_adr, phase, offset)) {
   902         // examine a captured store value
   903         st = init->find_captured_store(offset, memory_size(), phase);
   904         if (st != NULL)
   905           continue;             // take one more trip around
   906       }
   907     }
   909     break;
   910   }
   912   return NULL;
   913 }
   915 //----------------------is_instance_field_load_with_local_phi------------------
   916 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
   917   if( in(MemNode::Memory)->is_Phi() && in(MemNode::Memory)->in(0) == ctrl &&
   918       in(MemNode::Address)->is_AddP() ) {
   919     const TypeOopPtr* t_oop = in(MemNode::Address)->bottom_type()->isa_oopptr();
   920     // Only instances.
   921     if( t_oop != NULL && t_oop->is_known_instance_field() &&
   922         t_oop->offset() != Type::OffsetBot &&
   923         t_oop->offset() != Type::OffsetTop) {
   924       return true;
   925     }
   926   }
   927   return false;
   928 }
   930 //------------------------------Identity---------------------------------------
   931 // Loads are identity if previous store is to same address
   932 Node *LoadNode::Identity( PhaseTransform *phase ) {
   933   // If the previous store-maker is the right kind of Store, and the store is
   934   // to the same address, then we are equal to the value stored.
   935   Node* mem = in(MemNode::Memory);
   936   Node* value = can_see_stored_value(mem, phase);
   937   if( value ) {
   938     // byte, short & char stores truncate naturally.
   939     // A load has to load the truncated value which requires
   940     // some sort of masking operation and that requires an
   941     // Ideal call instead of an Identity call.
   942     if (memory_size() < BytesPerInt) {
   943       // If the input to the store does not fit with the load's result type,
   944       // it must be truncated via an Ideal call.
   945       if (!phase->type(value)->higher_equal(phase->type(this)))
   946         return this;
   947     }
   948     // (This works even when value is a Con, but LoadNode::Value
   949     // usually runs first, producing the singleton type of the Con.)
   950     return value;
   951   }
   953   // Search for an existing data phi which was generated before for the same
   954   // instance's field to avoid infinite genertion of phis in a loop.
   955   Node *region = mem->in(0);
   956   if (is_instance_field_load_with_local_phi(region)) {
   957     const TypePtr *addr_t = in(MemNode::Address)->bottom_type()->isa_ptr();
   958     int this_index  = phase->C->get_alias_index(addr_t);
   959     int this_offset = addr_t->offset();
   960     int this_id    = addr_t->is_oopptr()->instance_id();
   961     const Type* this_type = bottom_type();
   962     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
   963       Node* phi = region->fast_out(i);
   964       if (phi->is_Phi() && phi != mem &&
   965           phi->as_Phi()->is_same_inst_field(this_type, this_id, this_index, this_offset)) {
   966         return phi;
   967       }
   968     }
   969   }
   971   return this;
   972 }
   975 // Returns true if the AliasType refers to the field that holds the
   976 // cached box array.  Currently only handles the IntegerCache case.
   977 static bool is_autobox_cache(Compile::AliasType* atp) {
   978   if (atp != NULL && atp->field() != NULL) {
   979     ciField* field = atp->field();
   980     ciSymbol* klass = field->holder()->name();
   981     if (field->name() == ciSymbol::cache_field_name() &&
   982         field->holder()->uses_default_loader() &&
   983         klass == ciSymbol::java_lang_Integer_IntegerCache()) {
   984       return true;
   985     }
   986   }
   987   return false;
   988 }
   990 // Fetch the base value in the autobox array
   991 static bool fetch_autobox_base(Compile::AliasType* atp, int& cache_offset) {
   992   if (atp != NULL && atp->field() != NULL) {
   993     ciField* field = atp->field();
   994     ciSymbol* klass = field->holder()->name();
   995     if (field->name() == ciSymbol::cache_field_name() &&
   996         field->holder()->uses_default_loader() &&
   997         klass == ciSymbol::java_lang_Integer_IntegerCache()) {
   998       assert(field->is_constant(), "what?");
   999       ciObjArray* array = field->constant_value().as_object()->as_obj_array();
  1000       // Fetch the box object at the base of the array and get its value
  1001       ciInstance* box = array->obj_at(0)->as_instance();
  1002       ciInstanceKlass* ik = box->klass()->as_instance_klass();
  1003       if (ik->nof_nonstatic_fields() == 1) {
  1004         // This should be true nonstatic_field_at requires calling
  1005         // nof_nonstatic_fields so check it anyway
  1006         ciConstant c = box->field_value(ik->nonstatic_field_at(0));
  1007         cache_offset = c.as_int();
  1009       return true;
  1012   return false;
  1015 // Returns true if the AliasType refers to the value field of an
  1016 // autobox object.  Currently only handles Integer.
  1017 static bool is_autobox_object(Compile::AliasType* atp) {
  1018   if (atp != NULL && atp->field() != NULL) {
  1019     ciField* field = atp->field();
  1020     ciSymbol* klass = field->holder()->name();
  1021     if (field->name() == ciSymbol::value_name() &&
  1022         field->holder()->uses_default_loader() &&
  1023         klass == ciSymbol::java_lang_Integer()) {
  1024       return true;
  1027   return false;
  1031 // We're loading from an object which has autobox behaviour.
  1032 // If this object is result of a valueOf call we'll have a phi
  1033 // merging a newly allocated object and a load from the cache.
  1034 // We want to replace this load with the original incoming
  1035 // argument to the valueOf call.
  1036 Node* LoadNode::eliminate_autobox(PhaseGVN* phase) {
  1037   Node* base = in(Address)->in(AddPNode::Base);
  1038   if (base->is_Phi() && base->req() == 3) {
  1039     AllocateNode* allocation = NULL;
  1040     int allocation_index = -1;
  1041     int load_index = -1;
  1042     for (uint i = 1; i < base->req(); i++) {
  1043       allocation = AllocateNode::Ideal_allocation(base->in(i), phase);
  1044       if (allocation != NULL) {
  1045         allocation_index = i;
  1046         load_index = 3 - allocation_index;
  1047         break;
  1050     LoadNode* load = NULL;
  1051     if (allocation != NULL && base->in(load_index)->is_Load()) {
  1052       load = base->in(load_index)->as_Load();
  1054     if (load != NULL && in(Memory)->is_Phi() && in(Memory)->in(0) == base->in(0)) {
  1055       // Push the loads from the phi that comes from valueOf up
  1056       // through it to allow elimination of the loads and the recovery
  1057       // of the original value.
  1058       Node* mem_phi = in(Memory);
  1059       Node* offset = in(Address)->in(AddPNode::Offset);
  1061       Node* in1 = clone();
  1062       Node* in1_addr = in1->in(Address)->clone();
  1063       in1_addr->set_req(AddPNode::Base, base->in(allocation_index));
  1064       in1_addr->set_req(AddPNode::Address, base->in(allocation_index));
  1065       in1_addr->set_req(AddPNode::Offset, offset);
  1066       in1->set_req(0, base->in(allocation_index));
  1067       in1->set_req(Address, in1_addr);
  1068       in1->set_req(Memory, mem_phi->in(allocation_index));
  1070       Node* in2 = clone();
  1071       Node* in2_addr = in2->in(Address)->clone();
  1072       in2_addr->set_req(AddPNode::Base, base->in(load_index));
  1073       in2_addr->set_req(AddPNode::Address, base->in(load_index));
  1074       in2_addr->set_req(AddPNode::Offset, offset);
  1075       in2->set_req(0, base->in(load_index));
  1076       in2->set_req(Address, in2_addr);
  1077       in2->set_req(Memory, mem_phi->in(load_index));
  1079       in1_addr = phase->transform(in1_addr);
  1080       in1 =      phase->transform(in1);
  1081       in2_addr = phase->transform(in2_addr);
  1082       in2 =      phase->transform(in2);
  1084       PhiNode* result = PhiNode::make_blank(base->in(0), this);
  1085       result->set_req(allocation_index, in1);
  1086       result->set_req(load_index, in2);
  1087       return result;
  1089   } else if (base->is_Load()) {
  1090     // Eliminate the load of Integer.value for integers from the cache
  1091     // array by deriving the value from the index into the array.
  1092     // Capture the offset of the load and then reverse the computation.
  1093     Node* load_base = base->in(Address)->in(AddPNode::Base);
  1094     if (load_base != NULL) {
  1095       Compile::AliasType* atp = phase->C->alias_type(load_base->adr_type());
  1096       intptr_t cache_offset;
  1097       int shift = -1;
  1098       Node* cache = NULL;
  1099       if (is_autobox_cache(atp)) {
  1100         shift  = exact_log2(type2aelembytes(T_OBJECT));
  1101         cache = AddPNode::Ideal_base_and_offset(load_base->in(Address), phase, cache_offset);
  1103       if (cache != NULL && base->in(Address)->is_AddP()) {
  1104         Node* elements[4];
  1105         int count = base->in(Address)->as_AddP()->unpack_offsets(elements, ARRAY_SIZE(elements));
  1106         int cache_low;
  1107         if (count > 0 && fetch_autobox_base(atp, cache_low)) {
  1108           int offset = arrayOopDesc::base_offset_in_bytes(memory_type()) - (cache_low << shift);
  1109           // Add up all the offsets making of the address of the load
  1110           Node* result = elements[0];
  1111           for (int i = 1; i < count; i++) {
  1112             result = phase->transform(new (phase->C, 3) AddXNode(result, elements[i]));
  1114           // Remove the constant offset from the address and then
  1115           // remove the scaling of the offset to recover the original index.
  1116           result = phase->transform(new (phase->C, 3) AddXNode(result, phase->MakeConX(-offset)));
  1117           if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) {
  1118             // Peel the shift off directly but wrap it in a dummy node
  1119             // since Ideal can't return existing nodes
  1120             result = new (phase->C, 3) RShiftXNode(result->in(1), phase->intcon(0));
  1121           } else {
  1122             result = new (phase->C, 3) RShiftXNode(result, phase->intcon(shift));
  1124 #ifdef _LP64
  1125           result = new (phase->C, 2) ConvL2INode(phase->transform(result));
  1126 #endif
  1127           return result;
  1132   return NULL;
  1135 //------------------------------split_through_phi------------------------------
  1136 // Split instance field load through Phi.
  1137 Node *LoadNode::split_through_phi(PhaseGVN *phase) {
  1138   Node* mem     = in(MemNode::Memory);
  1139   Node* address = in(MemNode::Address);
  1140   const TypePtr *addr_t = phase->type(address)->isa_ptr();
  1141   const TypeOopPtr *t_oop = addr_t->isa_oopptr();
  1143   assert(mem->is_Phi() && (t_oop != NULL) &&
  1144          t_oop->is_known_instance_field(), "invalide conditions");
  1146   Node *region = mem->in(0);
  1147   if (region == NULL) {
  1148     return NULL; // Wait stable graph
  1150   uint cnt = mem->req();
  1151   for( uint i = 1; i < cnt; i++ ) {
  1152     Node *in = mem->in(i);
  1153     if( in == NULL ) {
  1154       return NULL; // Wait stable graph
  1157   // Check for loop invariant.
  1158   if (cnt == 3) {
  1159     for( uint i = 1; i < cnt; i++ ) {
  1160       Node *in = mem->in(i);
  1161       Node* m = MemNode::optimize_memory_chain(in, addr_t, phase);
  1162       if (m == mem) {
  1163         set_req(MemNode::Memory, mem->in(cnt - i)); // Skip this phi.
  1164         return this;
  1168   // Split through Phi (see original code in loopopts.cpp).
  1169   assert(phase->C->have_alias_type(addr_t), "instance should have alias type");
  1171   // Do nothing here if Identity will find a value
  1172   // (to avoid infinite chain of value phis generation).
  1173   if ( !phase->eqv(this, this->Identity(phase)) )
  1174     return NULL;
  1176   // Skip the split if the region dominates some control edge of the address.
  1177   if (cnt == 3 && !MemNode::all_controls_dominate(address, region))
  1178     return NULL;
  1180   const Type* this_type = this->bottom_type();
  1181   int this_index  = phase->C->get_alias_index(addr_t);
  1182   int this_offset = addr_t->offset();
  1183   int this_iid    = addr_t->is_oopptr()->instance_id();
  1184   int wins = 0;
  1185   PhaseIterGVN *igvn = phase->is_IterGVN();
  1186   Node *phi = new (igvn->C, region->req()) PhiNode(region, this_type, NULL, this_iid, this_index, this_offset);
  1187   for( uint i = 1; i < region->req(); i++ ) {
  1188     Node *x;
  1189     Node* the_clone = NULL;
  1190     if( region->in(i) == phase->C->top() ) {
  1191       x = phase->C->top();      // Dead path?  Use a dead data op
  1192     } else {
  1193       x = this->clone();        // Else clone up the data op
  1194       the_clone = x;            // Remember for possible deletion.
  1195       // Alter data node to use pre-phi inputs
  1196       if( this->in(0) == region ) {
  1197         x->set_req( 0, region->in(i) );
  1198       } else {
  1199         x->set_req( 0, NULL );
  1201       for( uint j = 1; j < this->req(); j++ ) {
  1202         Node *in = this->in(j);
  1203         if( in->is_Phi() && in->in(0) == region )
  1204           x->set_req( j, in->in(i) ); // Use pre-Phi input for the clone
  1207     // Check for a 'win' on some paths
  1208     const Type *t = x->Value(igvn);
  1210     bool singleton = t->singleton();
  1212     // See comments in PhaseIdealLoop::split_thru_phi().
  1213     if( singleton && t == Type::TOP ) {
  1214       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
  1217     if( singleton ) {
  1218       wins++;
  1219       x = igvn->makecon(t);
  1220     } else {
  1221       // We now call Identity to try to simplify the cloned node.
  1222       // Note that some Identity methods call phase->type(this).
  1223       // Make sure that the type array is big enough for
  1224       // our new node, even though we may throw the node away.
  1225       // (This tweaking with igvn only works because x is a new node.)
  1226       igvn->set_type(x, t);
  1227       Node *y = x->Identity(igvn);
  1228       if( y != x ) {
  1229         wins++;
  1230         x = y;
  1231       } else {
  1232         y = igvn->hash_find(x);
  1233         if( y ) {
  1234           wins++;
  1235           x = y;
  1236         } else {
  1237           // Else x is a new node we are keeping
  1238           // We do not need register_new_node_with_optimizer
  1239           // because set_type has already been called.
  1240           igvn->_worklist.push(x);
  1244     if (x != the_clone && the_clone != NULL)
  1245       igvn->remove_dead_node(the_clone);
  1246     phi->set_req(i, x);
  1248   if( wins > 0 ) {
  1249     // Record Phi
  1250     igvn->register_new_node_with_optimizer(phi);
  1251     return phi;
  1253   igvn->remove_dead_node(phi);
  1254   return NULL;
  1257 //------------------------------Ideal------------------------------------------
  1258 // If the load is from Field memory and the pointer is non-null, we can
  1259 // zero out the control input.
  1260 // If the offset is constant and the base is an object allocation,
  1261 // try to hook me up to the exact initializing store.
  1262 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  1263   Node* p = MemNode::Ideal_common(phase, can_reshape);
  1264   if (p)  return (p == NodeSentinel) ? NULL : p;
  1266   Node* ctrl    = in(MemNode::Control);
  1267   Node* address = in(MemNode::Address);
  1269   // Skip up past a SafePoint control.  Cannot do this for Stores because
  1270   // pointer stores & cardmarks must stay on the same side of a SafePoint.
  1271   if( ctrl != NULL && ctrl->Opcode() == Op_SafePoint &&
  1272       phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw ) {
  1273     ctrl = ctrl->in(0);
  1274     set_req(MemNode::Control,ctrl);
  1277   // Check for useless control edge in some common special cases
  1278   if (in(MemNode::Control) != NULL) {
  1279     intptr_t ignore = 0;
  1280     Node*    base   = AddPNode::Ideal_base_and_offset(address, phase, ignore);
  1281     if (base != NULL
  1282         && phase->type(base)->higher_equal(TypePtr::NOTNULL)
  1283         && all_controls_dominate(base, phase->C->start())) {
  1284       // A method-invariant, non-null address (constant or 'this' argument).
  1285       set_req(MemNode::Control, NULL);
  1289   if (EliminateAutoBox && can_reshape && in(Address)->is_AddP()) {
  1290     Node* base = in(Address)->in(AddPNode::Base);
  1291     if (base != NULL) {
  1292       Compile::AliasType* atp = phase->C->alias_type(adr_type());
  1293       if (is_autobox_object(atp)) {
  1294         Node* result = eliminate_autobox(phase);
  1295         if (result != NULL) return result;
  1300   Node* mem = in(MemNode::Memory);
  1301   const TypePtr *addr_t = phase->type(address)->isa_ptr();
  1303   if (addr_t != NULL) {
  1304     // try to optimize our memory input
  1305     Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, phase);
  1306     if (opt_mem != mem) {
  1307       set_req(MemNode::Memory, opt_mem);
  1308       return this;
  1310     const TypeOopPtr *t_oop = addr_t->isa_oopptr();
  1311     if (can_reshape && opt_mem->is_Phi() &&
  1312         (t_oop != NULL) && t_oop->is_known_instance_field()) {
  1313       // Split instance field load through Phi.
  1314       Node* result = split_through_phi(phase);
  1315       if (result != NULL) return result;
  1319   // Check for prior store with a different base or offset; make Load
  1320   // independent.  Skip through any number of them.  Bail out if the stores
  1321   // are in an endless dead cycle and report no progress.  This is a key
  1322   // transform for Reflection.  However, if after skipping through the Stores
  1323   // we can't then fold up against a prior store do NOT do the transform as
  1324   // this amounts to using the 'Oracle' model of aliasing.  It leaves the same
  1325   // array memory alive twice: once for the hoisted Load and again after the
  1326   // bypassed Store.  This situation only works if EVERYBODY who does
  1327   // anti-dependence work knows how to bypass.  I.e. we need all
  1328   // anti-dependence checks to ask the same Oracle.  Right now, that Oracle is
  1329   // the alias index stuff.  So instead, peek through Stores and IFF we can
  1330   // fold up, do so.
  1331   Node* prev_mem = find_previous_store(phase);
  1332   // Steps (a), (b):  Walk past independent stores to find an exact match.
  1333   if (prev_mem != NULL && prev_mem != in(MemNode::Memory)) {
  1334     // (c) See if we can fold up on the spot, but don't fold up here.
  1335     // Fold-up might require truncation (for LoadB/LoadS/LoadC) or
  1336     // just return a prior value, which is done by Identity calls.
  1337     if (can_see_stored_value(prev_mem, phase)) {
  1338       // Make ready for step (d):
  1339       set_req(MemNode::Memory, prev_mem);
  1340       return this;
  1344   return NULL;                  // No further progress
  1347 // Helper to recognize certain Klass fields which are invariant across
  1348 // some group of array types (e.g., int[] or all T[] where T < Object).
  1349 const Type*
  1350 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
  1351                                  ciKlass* klass) const {
  1352   if (tkls->offset() == Klass::modifier_flags_offset_in_bytes() + (int)sizeof(oopDesc)) {
  1353     // The field is Klass::_modifier_flags.  Return its (constant) value.
  1354     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
  1355     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
  1356     return TypeInt::make(klass->modifier_flags());
  1358   if (tkls->offset() == Klass::access_flags_offset_in_bytes() + (int)sizeof(oopDesc)) {
  1359     // The field is Klass::_access_flags.  Return its (constant) value.
  1360     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
  1361     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
  1362     return TypeInt::make(klass->access_flags());
  1364   if (tkls->offset() == Klass::layout_helper_offset_in_bytes() + (int)sizeof(oopDesc)) {
  1365     // The field is Klass::_layout_helper.  Return its constant value if known.
  1366     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
  1367     return TypeInt::make(klass->layout_helper());
  1370   // No match.
  1371   return NULL;
  1374 //------------------------------Value-----------------------------------------
  1375 const Type *LoadNode::Value( PhaseTransform *phase ) const {
  1376   // Either input is TOP ==> the result is TOP
  1377   Node* mem = in(MemNode::Memory);
  1378   const Type *t1 = phase->type(mem);
  1379   if (t1 == Type::TOP)  return Type::TOP;
  1380   Node* adr = in(MemNode::Address);
  1381   const TypePtr* tp = phase->type(adr)->isa_ptr();
  1382   if (tp == NULL || tp->empty())  return Type::TOP;
  1383   int off = tp->offset();
  1384   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
  1386   // Try to guess loaded type from pointer type
  1387   if (tp->base() == Type::AryPtr) {
  1388     const Type *t = tp->is_aryptr()->elem();
  1389     // Don't do this for integer types. There is only potential profit if
  1390     // the element type t is lower than _type; that is, for int types, if _type is
  1391     // more restrictive than t.  This only happens here if one is short and the other
  1392     // char (both 16 bits), and in those cases we've made an intentional decision
  1393     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
  1394     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
  1395     //
  1396     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
  1397     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
  1398     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
  1399     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
  1400     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
  1401     // In fact, that could have been the original type of p1, and p1 could have
  1402     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
  1403     // expression (LShiftL quux 3) independently optimized to the constant 8.
  1404     if ((t->isa_int() == NULL) && (t->isa_long() == NULL)
  1405         && Opcode() != Op_LoadKlass) {
  1406       // t might actually be lower than _type, if _type is a unique
  1407       // concrete subclass of abstract class t.
  1408       // Make sure the reference is not into the header, by comparing
  1409       // the offset against the offset of the start of the array's data.
  1410       // Different array types begin at slightly different offsets (12 vs. 16).
  1411       // We choose T_BYTE as an example base type that is least restrictive
  1412       // as to alignment, which will therefore produce the smallest
  1413       // possible base offset.
  1414       const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
  1415       if ((uint)off >= (uint)min_base_off) {  // is the offset beyond the header?
  1416         const Type* jt = t->join(_type);
  1417         // In any case, do not allow the join, per se, to empty out the type.
  1418         if (jt->empty() && !t->empty()) {
  1419           // This can happen if a interface-typed array narrows to a class type.
  1420           jt = _type;
  1423         if (EliminateAutoBox) {
  1424           // The pointers in the autobox arrays are always non-null
  1425           Node* base = in(Address)->in(AddPNode::Base);
  1426           if (base != NULL) {
  1427             Compile::AliasType* atp = phase->C->alias_type(base->adr_type());
  1428             if (is_autobox_cache(atp)) {
  1429               return jt->join(TypePtr::NOTNULL)->is_ptr();
  1433         return jt;
  1436   } else if (tp->base() == Type::InstPtr) {
  1437     assert( off != Type::OffsetBot ||
  1438             // arrays can be cast to Objects
  1439             tp->is_oopptr()->klass()->is_java_lang_Object() ||
  1440             // unsafe field access may not have a constant offset
  1441             phase->C->has_unsafe_access(),
  1442             "Field accesses must be precise" );
  1443     // For oop loads, we expect the _type to be precise
  1444   } else if (tp->base() == Type::KlassPtr) {
  1445     assert( off != Type::OffsetBot ||
  1446             // arrays can be cast to Objects
  1447             tp->is_klassptr()->klass()->is_java_lang_Object() ||
  1448             // also allow array-loading from the primary supertype
  1449             // array during subtype checks
  1450             Opcode() == Op_LoadKlass,
  1451             "Field accesses must be precise" );
  1452     // For klass/static loads, we expect the _type to be precise
  1455   const TypeKlassPtr *tkls = tp->isa_klassptr();
  1456   if (tkls != NULL && !StressReflectiveCode) {
  1457     ciKlass* klass = tkls->klass();
  1458     if (klass->is_loaded() && tkls->klass_is_exact()) {
  1459       // We are loading a field from a Klass metaobject whose identity
  1460       // is known at compile time (the type is "exact" or "precise").
  1461       // Check for fields we know are maintained as constants by the VM.
  1462       if (tkls->offset() == Klass::super_check_offset_offset_in_bytes() + (int)sizeof(oopDesc)) {
  1463         // The field is Klass::_super_check_offset.  Return its (constant) value.
  1464         // (Folds up type checking code.)
  1465         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
  1466         return TypeInt::make(klass->super_check_offset());
  1468       // Compute index into primary_supers array
  1469       juint depth = (tkls->offset() - (Klass::primary_supers_offset_in_bytes() + (int)sizeof(oopDesc))) / sizeof(klassOop);
  1470       // Check for overflowing; use unsigned compare to handle the negative case.
  1471       if( depth < ciKlass::primary_super_limit() ) {
  1472         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
  1473         // (Folds up type checking code.)
  1474         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
  1475         ciKlass *ss = klass->super_of_depth(depth);
  1476         return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
  1478       const Type* aift = load_array_final_field(tkls, klass);
  1479       if (aift != NULL)  return aift;
  1480       if (tkls->offset() == in_bytes(arrayKlass::component_mirror_offset()) + (int)sizeof(oopDesc)
  1481           && klass->is_array_klass()) {
  1482         // The field is arrayKlass::_component_mirror.  Return its (constant) value.
  1483         // (Folds up aClassConstant.getComponentType, common in Arrays.copyOf.)
  1484         assert(Opcode() == Op_LoadP, "must load an oop from _component_mirror");
  1485         return TypeInstPtr::make(klass->as_array_klass()->component_mirror());
  1487       if (tkls->offset() == Klass::java_mirror_offset_in_bytes() + (int)sizeof(oopDesc)) {
  1488         // The field is Klass::_java_mirror.  Return its (constant) value.
  1489         // (Folds up the 2nd indirection in anObjConstant.getClass().)
  1490         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
  1491         return TypeInstPtr::make(klass->java_mirror());
  1495     // We can still check if we are loading from the primary_supers array at a
  1496     // shallow enough depth.  Even though the klass is not exact, entries less
  1497     // than or equal to its super depth are correct.
  1498     if (klass->is_loaded() ) {
  1499       ciType *inner = klass->klass();
  1500       while( inner->is_obj_array_klass() )
  1501         inner = inner->as_obj_array_klass()->base_element_type();
  1502       if( inner->is_instance_klass() &&
  1503           !inner->as_instance_klass()->flags().is_interface() ) {
  1504         // Compute index into primary_supers array
  1505         juint depth = (tkls->offset() - (Klass::primary_supers_offset_in_bytes() + (int)sizeof(oopDesc))) / sizeof(klassOop);
  1506         // Check for overflowing; use unsigned compare to handle the negative case.
  1507         if( depth < ciKlass::primary_super_limit() &&
  1508             depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
  1509           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
  1510           // (Folds up type checking code.)
  1511           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
  1512           ciKlass *ss = klass->super_of_depth(depth);
  1513           return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
  1518     // If the type is enough to determine that the thing is not an array,
  1519     // we can give the layout_helper a positive interval type.
  1520     // This will help short-circuit some reflective code.
  1521     if (tkls->offset() == Klass::layout_helper_offset_in_bytes() + (int)sizeof(oopDesc)
  1522         && !klass->is_array_klass() // not directly typed as an array
  1523         && !klass->is_interface()  // specifically not Serializable & Cloneable
  1524         && !klass->is_java_lang_Object()   // not the supertype of all T[]
  1525         ) {
  1526       // Note:  When interfaces are reliable, we can narrow the interface
  1527       // test to (klass != Serializable && klass != Cloneable).
  1528       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
  1529       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
  1530       // The key property of this type is that it folds up tests
  1531       // for array-ness, since it proves that the layout_helper is positive.
  1532       // Thus, a generic value like the basic object layout helper works fine.
  1533       return TypeInt::make(min_size, max_jint, Type::WidenMin);
  1537   // If we are loading from a freshly-allocated object, produce a zero,
  1538   // if the load is provably beyond the header of the object.
  1539   // (Also allow a variable load from a fresh array to produce zero.)
  1540   if (ReduceFieldZeroing) {
  1541     Node* value = can_see_stored_value(mem,phase);
  1542     if (value != NULL && value->is_Con())
  1543       return value->bottom_type();
  1546   const TypeOopPtr *tinst = tp->isa_oopptr();
  1547   if (tinst != NULL && tinst->is_known_instance_field()) {
  1548     // If we have an instance type and our memory input is the
  1549     // programs's initial memory state, there is no matching store,
  1550     // so just return a zero of the appropriate type
  1551     Node *mem = in(MemNode::Memory);
  1552     if (mem->is_Parm() && mem->in(0)->is_Start()) {
  1553       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
  1554       return Type::get_zero_type(_type->basic_type());
  1557   return _type;
  1560 //------------------------------match_edge-------------------------------------
  1561 // Do we Match on this edge index or not?  Match only the address.
  1562 uint LoadNode::match_edge(uint idx) const {
  1563   return idx == MemNode::Address;
  1566 //--------------------------LoadBNode::Ideal--------------------------------------
  1567 //
  1568 //  If the previous store is to the same address as this load,
  1569 //  and the value stored was larger than a byte, replace this load
  1570 //  with the value stored truncated to a byte.  If no truncation is
  1571 //  needed, the replacement is done in LoadNode::Identity().
  1572 //
  1573 Node *LoadBNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  1574   Node* mem = in(MemNode::Memory);
  1575   Node* value = can_see_stored_value(mem,phase);
  1576   if( value && !phase->type(value)->higher_equal( _type ) ) {
  1577     Node *result = phase->transform( new (phase->C, 3) LShiftINode(value, phase->intcon(24)) );
  1578     return new (phase->C, 3) RShiftINode(result, phase->intcon(24));
  1580   // Identity call will handle the case where truncation is not needed.
  1581   return LoadNode::Ideal(phase, can_reshape);
  1584 //--------------------------LoadCNode::Ideal--------------------------------------
  1585 //
  1586 //  If the previous store is to the same address as this load,
  1587 //  and the value stored was larger than a char, replace this load
  1588 //  with the value stored truncated to a char.  If no truncation is
  1589 //  needed, the replacement is done in LoadNode::Identity().
  1590 //
  1591 Node *LoadCNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  1592   Node* mem = in(MemNode::Memory);
  1593   Node* value = can_see_stored_value(mem,phase);
  1594   if( value && !phase->type(value)->higher_equal( _type ) )
  1595     return new (phase->C, 3) AndINode(value,phase->intcon(0xFFFF));
  1596   // Identity call will handle the case where truncation is not needed.
  1597   return LoadNode::Ideal(phase, can_reshape);
  1600 //--------------------------LoadSNode::Ideal--------------------------------------
  1601 //
  1602 //  If the previous store is to the same address as this load,
  1603 //  and the value stored was larger than a short, replace this load
  1604 //  with the value stored truncated to a short.  If no truncation is
  1605 //  needed, the replacement is done in LoadNode::Identity().
  1606 //
  1607 Node *LoadSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  1608   Node* mem = in(MemNode::Memory);
  1609   Node* value = can_see_stored_value(mem,phase);
  1610   if( value && !phase->type(value)->higher_equal( _type ) ) {
  1611     Node *result = phase->transform( new (phase->C, 3) LShiftINode(value, phase->intcon(16)) );
  1612     return new (phase->C, 3) RShiftINode(result, phase->intcon(16));
  1614   // Identity call will handle the case where truncation is not needed.
  1615   return LoadNode::Ideal(phase, can_reshape);
  1618 //=============================================================================
  1619 //----------------------------LoadKlassNode::make------------------------------
  1620 // Polymorphic factory method:
  1621 Node *LoadKlassNode::make( PhaseGVN& gvn, Node *mem, Node *adr, const TypePtr* at, const TypeKlassPtr *tk ) {
  1622   Compile* C = gvn.C;
  1623   Node *ctl = NULL;
  1624   // sanity check the alias category against the created node type
  1625   const TypeOopPtr *adr_type = adr->bottom_type()->isa_oopptr();
  1626   assert(adr_type != NULL, "expecting TypeOopPtr");
  1627 #ifdef _LP64
  1628   if (adr_type->is_ptr_to_narrowoop()) {
  1629     Node* load_klass = gvn.transform(new (C, 3) LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowoop()));
  1630     return new (C, 2) DecodeNNode(load_klass, load_klass->bottom_type()->make_ptr());
  1632 #endif
  1633   assert(!adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
  1634   return new (C, 3) LoadKlassNode(ctl, mem, adr, at, tk);
  1637 //------------------------------Value------------------------------------------
  1638 const Type *LoadKlassNode::Value( PhaseTransform *phase ) const {
  1639   return klass_value_common(phase);
  1642 const Type *LoadNode::klass_value_common( PhaseTransform *phase ) const {
  1643   // Either input is TOP ==> the result is TOP
  1644   const Type *t1 = phase->type( in(MemNode::Memory) );
  1645   if (t1 == Type::TOP)  return Type::TOP;
  1646   Node *adr = in(MemNode::Address);
  1647   const Type *t2 = phase->type( adr );
  1648   if (t2 == Type::TOP)  return Type::TOP;
  1649   const TypePtr *tp = t2->is_ptr();
  1650   if (TypePtr::above_centerline(tp->ptr()) ||
  1651       tp->ptr() == TypePtr::Null)  return Type::TOP;
  1653   // Return a more precise klass, if possible
  1654   const TypeInstPtr *tinst = tp->isa_instptr();
  1655   if (tinst != NULL) {
  1656     ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
  1657     int offset = tinst->offset();
  1658     if (ik == phase->C->env()->Class_klass()
  1659         && (offset == java_lang_Class::klass_offset_in_bytes() ||
  1660             offset == java_lang_Class::array_klass_offset_in_bytes())) {
  1661       // We are loading a special hidden field from a Class mirror object,
  1662       // the field which points to the VM's Klass metaobject.
  1663       ciType* t = tinst->java_mirror_type();
  1664       // java_mirror_type returns non-null for compile-time Class constants.
  1665       if (t != NULL) {
  1666         // constant oop => constant klass
  1667         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
  1668           return TypeKlassPtr::make(ciArrayKlass::make(t));
  1670         if (!t->is_klass()) {
  1671           // a primitive Class (e.g., int.class) has NULL for a klass field
  1672           return TypePtr::NULL_PTR;
  1674         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
  1675         return TypeKlassPtr::make(t->as_klass());
  1677       // non-constant mirror, so we can't tell what's going on
  1679     if( !ik->is_loaded() )
  1680       return _type;             // Bail out if not loaded
  1681     if (offset == oopDesc::klass_offset_in_bytes()) {
  1682       if (tinst->klass_is_exact()) {
  1683         return TypeKlassPtr::make(ik);
  1685       // See if we can become precise: no subklasses and no interface
  1686       // (Note:  We need to support verified interfaces.)
  1687       if (!ik->is_interface() && !ik->has_subklass()) {
  1688         //assert(!UseExactTypes, "this code should be useless with exact types");
  1689         // Add a dependence; if any subclass added we need to recompile
  1690         if (!ik->is_final()) {
  1691           // %%% should use stronger assert_unique_concrete_subtype instead
  1692           phase->C->dependencies()->assert_leaf_type(ik);
  1694         // Return precise klass
  1695         return TypeKlassPtr::make(ik);
  1698       // Return root of possible klass
  1699       return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
  1703   // Check for loading klass from an array
  1704   const TypeAryPtr *tary = tp->isa_aryptr();
  1705   if( tary != NULL ) {
  1706     ciKlass *tary_klass = tary->klass();
  1707     if (tary_klass != NULL   // can be NULL when at BOTTOM or TOP
  1708         && tary->offset() == oopDesc::klass_offset_in_bytes()) {
  1709       if (tary->klass_is_exact()) {
  1710         return TypeKlassPtr::make(tary_klass);
  1712       ciArrayKlass *ak = tary->klass()->as_array_klass();
  1713       // If the klass is an object array, we defer the question to the
  1714       // array component klass.
  1715       if( ak->is_obj_array_klass() ) {
  1716         assert( ak->is_loaded(), "" );
  1717         ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
  1718         if( base_k->is_loaded() && base_k->is_instance_klass() ) {
  1719           ciInstanceKlass* ik = base_k->as_instance_klass();
  1720           // See if we can become precise: no subklasses and no interface
  1721           if (!ik->is_interface() && !ik->has_subklass()) {
  1722             //assert(!UseExactTypes, "this code should be useless with exact types");
  1723             // Add a dependence; if any subclass added we need to recompile
  1724             if (!ik->is_final()) {
  1725               phase->C->dependencies()->assert_leaf_type(ik);
  1727             // Return precise array klass
  1728             return TypeKlassPtr::make(ak);
  1731         return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
  1732       } else {                  // Found a type-array?
  1733         //assert(!UseExactTypes, "this code should be useless with exact types");
  1734         assert( ak->is_type_array_klass(), "" );
  1735         return TypeKlassPtr::make(ak); // These are always precise
  1740   // Check for loading klass from an array klass
  1741   const TypeKlassPtr *tkls = tp->isa_klassptr();
  1742   if (tkls != NULL && !StressReflectiveCode) {
  1743     ciKlass* klass = tkls->klass();
  1744     if( !klass->is_loaded() )
  1745       return _type;             // Bail out if not loaded
  1746     if( klass->is_obj_array_klass() &&
  1747         (uint)tkls->offset() == objArrayKlass::element_klass_offset_in_bytes() + sizeof(oopDesc)) {
  1748       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
  1749       // // Always returning precise element type is incorrect,
  1750       // // e.g., element type could be object and array may contain strings
  1751       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
  1753       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
  1754       // according to the element type's subclassing.
  1755       return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
  1757     if( klass->is_instance_klass() && tkls->klass_is_exact() &&
  1758         (uint)tkls->offset() == Klass::super_offset_in_bytes() + sizeof(oopDesc)) {
  1759       ciKlass* sup = klass->as_instance_klass()->super();
  1760       // The field is Klass::_super.  Return its (constant) value.
  1761       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
  1762       return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
  1766   // Bailout case
  1767   return LoadNode::Value(phase);
  1770 //------------------------------Identity---------------------------------------
  1771 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
  1772 // Also feed through the klass in Allocate(...klass...)._klass.
  1773 Node* LoadKlassNode::Identity( PhaseTransform *phase ) {
  1774   return klass_identity_common(phase);
  1777 Node* LoadNode::klass_identity_common(PhaseTransform *phase ) {
  1778   Node* x = LoadNode::Identity(phase);
  1779   if (x != this)  return x;
  1781   // Take apart the address into an oop and and offset.
  1782   // Return 'this' if we cannot.
  1783   Node*    adr    = in(MemNode::Address);
  1784   intptr_t offset = 0;
  1785   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
  1786   if (base == NULL)     return this;
  1787   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
  1788   if (toop == NULL)     return this;
  1790   // We can fetch the klass directly through an AllocateNode.
  1791   // This works even if the klass is not constant (clone or newArray).
  1792   if (offset == oopDesc::klass_offset_in_bytes()) {
  1793     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
  1794     if (allocated_klass != NULL) {
  1795       return allocated_klass;
  1799   // Simplify k.java_mirror.as_klass to plain k, where k is a klassOop.
  1800   // Simplify ak.component_mirror.array_klass to plain ak, ak an arrayKlass.
  1801   // See inline_native_Class_query for occurrences of these patterns.
  1802   // Java Example:  x.getClass().isAssignableFrom(y)
  1803   // Java Example:  Array.newInstance(x.getClass().getComponentType(), n)
  1804   //
  1805   // This improves reflective code, often making the Class
  1806   // mirror go completely dead.  (Current exception:  Class
  1807   // mirrors may appear in debug info, but we could clean them out by
  1808   // introducing a new debug info operator for klassOop.java_mirror).
  1809   if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
  1810       && (offset == java_lang_Class::klass_offset_in_bytes() ||
  1811           offset == java_lang_Class::array_klass_offset_in_bytes())) {
  1812     // We are loading a special hidden field from a Class mirror,
  1813     // the field which points to its Klass or arrayKlass metaobject.
  1814     if (base->is_Load()) {
  1815       Node* adr2 = base->in(MemNode::Address);
  1816       const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
  1817       if (tkls != NULL && !tkls->empty()
  1818           && (tkls->klass()->is_instance_klass() ||
  1819               tkls->klass()->is_array_klass())
  1820           && adr2->is_AddP()
  1821           ) {
  1822         int mirror_field = Klass::java_mirror_offset_in_bytes();
  1823         if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
  1824           mirror_field = in_bytes(arrayKlass::component_mirror_offset());
  1826         if (tkls->offset() == mirror_field + (int)sizeof(oopDesc)) {
  1827           return adr2->in(AddPNode::Base);
  1833   return this;
  1837 //------------------------------Value------------------------------------------
  1838 const Type *LoadNKlassNode::Value( PhaseTransform *phase ) const {
  1839   const Type *t = klass_value_common(phase);
  1840   if (t == Type::TOP)
  1841     return t;
  1843   return t->make_narrowoop();
  1846 //------------------------------Identity---------------------------------------
  1847 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
  1848 // Also feed through the klass in Allocate(...klass...)._klass.
  1849 Node* LoadNKlassNode::Identity( PhaseTransform *phase ) {
  1850   Node *x = klass_identity_common(phase);
  1852   const Type *t = phase->type( x );
  1853   if( t == Type::TOP ) return x;
  1854   if( t->isa_narrowoop()) return x;
  1856   return phase->transform(new (phase->C, 2) EncodePNode(x, t->make_narrowoop()));
  1859 //------------------------------Value-----------------------------------------
  1860 const Type *LoadRangeNode::Value( PhaseTransform *phase ) const {
  1861   // Either input is TOP ==> the result is TOP
  1862   const Type *t1 = phase->type( in(MemNode::Memory) );
  1863   if( t1 == Type::TOP ) return Type::TOP;
  1864   Node *adr = in(MemNode::Address);
  1865   const Type *t2 = phase->type( adr );
  1866   if( t2 == Type::TOP ) return Type::TOP;
  1867   const TypePtr *tp = t2->is_ptr();
  1868   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
  1869   const TypeAryPtr *tap = tp->isa_aryptr();
  1870   if( !tap ) return _type;
  1871   return tap->size();
  1874 //------------------------------Identity---------------------------------------
  1875 // Feed through the length in AllocateArray(...length...)._length.
  1876 Node* LoadRangeNode::Identity( PhaseTransform *phase ) {
  1877   Node* x = LoadINode::Identity(phase);
  1878   if (x != this)  return x;
  1880   // Take apart the address into an oop and and offset.
  1881   // Return 'this' if we cannot.
  1882   Node*    adr    = in(MemNode::Address);
  1883   intptr_t offset = 0;
  1884   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
  1885   if (base == NULL)     return this;
  1886   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
  1887   if (tary == NULL)     return this;
  1889   // We can fetch the length directly through an AllocateArrayNode.
  1890   // This works even if the length is not constant (clone or newArray).
  1891   if (offset == arrayOopDesc::length_offset_in_bytes()) {
  1892     Node* allocated_length = AllocateArrayNode::Ideal_length(base, phase);
  1893     if (allocated_length != NULL) {
  1894       return allocated_length;
  1898   return this;
  1901 //=============================================================================
  1902 //---------------------------StoreNode::make-----------------------------------
  1903 // Polymorphic factory method:
  1904 StoreNode* StoreNode::make( PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt ) {
  1905   Compile* C = gvn.C;
  1907   switch (bt) {
  1908   case T_BOOLEAN:
  1909   case T_BYTE:    return new (C, 4) StoreBNode(ctl, mem, adr, adr_type, val);
  1910   case T_INT:     return new (C, 4) StoreINode(ctl, mem, adr, adr_type, val);
  1911   case T_CHAR:
  1912   case T_SHORT:   return new (C, 4) StoreCNode(ctl, mem, adr, adr_type, val);
  1913   case T_LONG:    return new (C, 4) StoreLNode(ctl, mem, adr, adr_type, val);
  1914   case T_FLOAT:   return new (C, 4) StoreFNode(ctl, mem, adr, adr_type, val);
  1915   case T_DOUBLE:  return new (C, 4) StoreDNode(ctl, mem, adr, adr_type, val);
  1916   case T_ADDRESS:
  1917   case T_OBJECT:
  1918 #ifdef _LP64
  1919     if (adr->bottom_type()->is_ptr_to_narrowoop() ||
  1920         (UseCompressedOops && val->bottom_type()->isa_klassptr() &&
  1921          adr->bottom_type()->isa_rawptr())) {
  1922       val = gvn.transform(new (C, 2) EncodePNode(val, val->bottom_type()->make_narrowoop()));
  1923       return new (C, 4) StoreNNode(ctl, mem, adr, adr_type, val);
  1924     } else
  1925 #endif
  1927       return new (C, 4) StorePNode(ctl, mem, adr, adr_type, val);
  1930   ShouldNotReachHere();
  1931   return (StoreNode*)NULL;
  1934 StoreLNode* StoreLNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val) {
  1935   bool require_atomic = true;
  1936   return new (C, 4) StoreLNode(ctl, mem, adr, adr_type, val, require_atomic);
  1940 //--------------------------bottom_type----------------------------------------
  1941 const Type *StoreNode::bottom_type() const {
  1942   return Type::MEMORY;
  1945 //------------------------------hash-------------------------------------------
  1946 uint StoreNode::hash() const {
  1947   // unroll addition of interesting fields
  1948   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
  1950   // Since they are not commoned, do not hash them:
  1951   return NO_HASH;
  1954 //------------------------------Ideal------------------------------------------
  1955 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
  1956 // When a store immediately follows a relevant allocation/initialization,
  1957 // try to capture it into the initialization, or hoist it above.
  1958 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  1959   Node* p = MemNode::Ideal_common(phase, can_reshape);
  1960   if (p)  return (p == NodeSentinel) ? NULL : p;
  1962   Node* mem     = in(MemNode::Memory);
  1963   Node* address = in(MemNode::Address);
  1965   // Back-to-back stores to same address?  Fold em up.
  1966   // Generally unsafe if I have intervening uses...
  1967   if (mem->is_Store() && phase->eqv_uncast(mem->in(MemNode::Address), address)) {
  1968     // Looking at a dead closed cycle of memory?
  1969     assert(mem != mem->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
  1971     assert(Opcode() == mem->Opcode() ||
  1972            phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw,
  1973            "no mismatched stores, except on raw memory");
  1975     if (mem->outcnt() == 1 &&           // check for intervening uses
  1976         mem->as_Store()->memory_size() <= this->memory_size()) {
  1977       // If anybody other than 'this' uses 'mem', we cannot fold 'mem' away.
  1978       // For example, 'mem' might be the final state at a conditional return.
  1979       // Or, 'mem' might be used by some node which is live at the same time
  1980       // 'this' is live, which might be unschedulable.  So, require exactly
  1981       // ONE user, the 'this' store, until such time as we clone 'mem' for
  1982       // each of 'mem's uses (thus making the exactly-1-user-rule hold true).
  1983       if (can_reshape) {  // (%%% is this an anachronism?)
  1984         set_req_X(MemNode::Memory, mem->in(MemNode::Memory),
  1985                   phase->is_IterGVN());
  1986       } else {
  1987         // It's OK to do this in the parser, since DU info is always accurate,
  1988         // and the parser always refers to nodes via SafePointNode maps.
  1989         set_req(MemNode::Memory, mem->in(MemNode::Memory));
  1991       return this;
  1995   // Capture an unaliased, unconditional, simple store into an initializer.
  1996   // Or, if it is independent of the allocation, hoist it above the allocation.
  1997   if (ReduceFieldZeroing && /*can_reshape &&*/
  1998       mem->is_Proj() && mem->in(0)->is_Initialize()) {
  1999     InitializeNode* init = mem->in(0)->as_Initialize();
  2000     intptr_t offset = init->can_capture_store(this, phase);
  2001     if (offset > 0) {
  2002       Node* moved = init->capture_store(this, offset, phase);
  2003       // If the InitializeNode captured me, it made a raw copy of me,
  2004       // and I need to disappear.
  2005       if (moved != NULL) {
  2006         // %%% hack to ensure that Ideal returns a new node:
  2007         mem = MergeMemNode::make(phase->C, mem);
  2008         return mem;             // fold me away
  2013   return NULL;                  // No further progress
  2016 //------------------------------Value-----------------------------------------
  2017 const Type *StoreNode::Value( PhaseTransform *phase ) const {
  2018   // Either input is TOP ==> the result is TOP
  2019   const Type *t1 = phase->type( in(MemNode::Memory) );
  2020   if( t1 == Type::TOP ) return Type::TOP;
  2021   const Type *t2 = phase->type( in(MemNode::Address) );
  2022   if( t2 == Type::TOP ) return Type::TOP;
  2023   const Type *t3 = phase->type( in(MemNode::ValueIn) );
  2024   if( t3 == Type::TOP ) return Type::TOP;
  2025   return Type::MEMORY;
  2028 //------------------------------Identity---------------------------------------
  2029 // Remove redundant stores:
  2030 //   Store(m, p, Load(m, p)) changes to m.
  2031 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
  2032 Node *StoreNode::Identity( PhaseTransform *phase ) {
  2033   Node* mem = in(MemNode::Memory);
  2034   Node* adr = in(MemNode::Address);
  2035   Node* val = in(MemNode::ValueIn);
  2037   // Load then Store?  Then the Store is useless
  2038   if (val->is_Load() &&
  2039       phase->eqv_uncast( val->in(MemNode::Address), adr ) &&
  2040       phase->eqv_uncast( val->in(MemNode::Memory ), mem ) &&
  2041       val->as_Load()->store_Opcode() == Opcode()) {
  2042     return mem;
  2045   // Two stores in a row of the same value?
  2046   if (mem->is_Store() &&
  2047       phase->eqv_uncast( mem->in(MemNode::Address), adr ) &&
  2048       phase->eqv_uncast( mem->in(MemNode::ValueIn), val ) &&
  2049       mem->Opcode() == Opcode()) {
  2050     return mem;
  2053   // Store of zero anywhere into a freshly-allocated object?
  2054   // Then the store is useless.
  2055   // (It must already have been captured by the InitializeNode.)
  2056   if (ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
  2057     // a newly allocated object is already all-zeroes everywhere
  2058     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
  2059       return mem;
  2062     // the store may also apply to zero-bits in an earlier object
  2063     Node* prev_mem = find_previous_store(phase);
  2064     // Steps (a), (b):  Walk past independent stores to find an exact match.
  2065     if (prev_mem != NULL) {
  2066       Node* prev_val = can_see_stored_value(prev_mem, phase);
  2067       if (prev_val != NULL && phase->eqv(prev_val, val)) {
  2068         // prev_val and val might differ by a cast; it would be good
  2069         // to keep the more informative of the two.
  2070         return mem;
  2075   return this;
  2078 //------------------------------match_edge-------------------------------------
  2079 // Do we Match on this edge index or not?  Match only memory & value
  2080 uint StoreNode::match_edge(uint idx) const {
  2081   return idx == MemNode::Address || idx == MemNode::ValueIn;
  2084 //------------------------------cmp--------------------------------------------
  2085 // Do not common stores up together.  They generally have to be split
  2086 // back up anyways, so do not bother.
  2087 uint StoreNode::cmp( const Node &n ) const {
  2088   return (&n == this);          // Always fail except on self
  2091 //------------------------------Ideal_masked_input-----------------------------
  2092 // Check for a useless mask before a partial-word store
  2093 // (StoreB ... (AndI valIn conIa) )
  2094 // If (conIa & mask == mask) this simplifies to
  2095 // (StoreB ... (valIn) )
  2096 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
  2097   Node *val = in(MemNode::ValueIn);
  2098   if( val->Opcode() == Op_AndI ) {
  2099     const TypeInt *t = phase->type( val->in(2) )->isa_int();
  2100     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
  2101       set_req(MemNode::ValueIn, val->in(1));
  2102       return this;
  2105   return NULL;
  2109 //------------------------------Ideal_sign_extended_input----------------------
  2110 // Check for useless sign-extension before a partial-word store
  2111 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
  2112 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
  2113 // (StoreB ... (valIn) )
  2114 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
  2115   Node *val = in(MemNode::ValueIn);
  2116   if( val->Opcode() == Op_RShiftI ) {
  2117     const TypeInt *t = phase->type( val->in(2) )->isa_int();
  2118     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
  2119       Node *shl = val->in(1);
  2120       if( shl->Opcode() == Op_LShiftI ) {
  2121         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
  2122         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
  2123           set_req(MemNode::ValueIn, shl->in(1));
  2124           return this;
  2129   return NULL;
  2132 //------------------------------value_never_loaded-----------------------------------
  2133 // Determine whether there are any possible loads of the value stored.
  2134 // For simplicity, we actually check if there are any loads from the
  2135 // address stored to, not just for loads of the value stored by this node.
  2136 //
  2137 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
  2138   Node *adr = in(Address);
  2139   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
  2140   if (adr_oop == NULL)
  2141     return false;
  2142   if (!adr_oop->is_known_instance_field())
  2143     return false; // if not a distinct instance, there may be aliases of the address
  2144   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
  2145     Node *use = adr->fast_out(i);
  2146     int opc = use->Opcode();
  2147     if (use->is_Load() || use->is_LoadStore()) {
  2148       return false;
  2151   return true;
  2154 //=============================================================================
  2155 //------------------------------Ideal------------------------------------------
  2156 // If the store is from an AND mask that leaves the low bits untouched, then
  2157 // we can skip the AND operation.  If the store is from a sign-extension
  2158 // (a left shift, then right shift) we can skip both.
  2159 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2160   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
  2161   if( progress != NULL ) return progress;
  2163   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
  2164   if( progress != NULL ) return progress;
  2166   // Finally check the default case
  2167   return StoreNode::Ideal(phase, can_reshape);
  2170 //=============================================================================
  2171 //------------------------------Ideal------------------------------------------
  2172 // If the store is from an AND mask that leaves the low bits untouched, then
  2173 // we can skip the AND operation
  2174 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2175   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
  2176   if( progress != NULL ) return progress;
  2178   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
  2179   if( progress != NULL ) return progress;
  2181   // Finally check the default case
  2182   return StoreNode::Ideal(phase, can_reshape);
  2185 //=============================================================================
  2186 //------------------------------Identity---------------------------------------
  2187 Node *StoreCMNode::Identity( PhaseTransform *phase ) {
  2188   // No need to card mark when storing a null ptr
  2189   Node* my_store = in(MemNode::OopStore);
  2190   if (my_store->is_Store()) {
  2191     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
  2192     if( t1 == TypePtr::NULL_PTR ) {
  2193       return in(MemNode::Memory);
  2196   return this;
  2199 //------------------------------Value-----------------------------------------
  2200 const Type *StoreCMNode::Value( PhaseTransform *phase ) const {
  2201   // Either input is TOP ==> the result is TOP
  2202   const Type *t = phase->type( in(MemNode::Memory) );
  2203   if( t == Type::TOP ) return Type::TOP;
  2204   t = phase->type( in(MemNode::Address) );
  2205   if( t == Type::TOP ) return Type::TOP;
  2206   t = phase->type( in(MemNode::ValueIn) );
  2207   if( t == Type::TOP ) return Type::TOP;
  2208   // If extra input is TOP ==> the result is TOP
  2209   t = phase->type( in(MemNode::OopStore) );
  2210   if( t == Type::TOP ) return Type::TOP;
  2212   return StoreNode::Value( phase );
  2216 //=============================================================================
  2217 //----------------------------------SCMemProjNode------------------------------
  2218 const Type * SCMemProjNode::Value( PhaseTransform *phase ) const
  2220   return bottom_type();
  2223 //=============================================================================
  2224 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : Node(5) {
  2225   init_req(MemNode::Control, c  );
  2226   init_req(MemNode::Memory , mem);
  2227   init_req(MemNode::Address, adr);
  2228   init_req(MemNode::ValueIn, val);
  2229   init_req(         ExpectedIn, ex );
  2230   init_class_id(Class_LoadStore);
  2234 //=============================================================================
  2235 //-------------------------------adr_type--------------------------------------
  2236 // Do we Match on this edge index or not?  Do not match memory
  2237 const TypePtr* ClearArrayNode::adr_type() const {
  2238   Node *adr = in(3);
  2239   return MemNode::calculate_adr_type(adr->bottom_type());
  2242 //------------------------------match_edge-------------------------------------
  2243 // Do we Match on this edge index or not?  Do not match memory
  2244 uint ClearArrayNode::match_edge(uint idx) const {
  2245   return idx > 1;
  2248 //------------------------------Identity---------------------------------------
  2249 // Clearing a zero length array does nothing
  2250 Node *ClearArrayNode::Identity( PhaseTransform *phase ) {
  2251   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
  2254 //------------------------------Idealize---------------------------------------
  2255 // Clearing a short array is faster with stores
  2256 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2257   const int unit = BytesPerLong;
  2258   const TypeX* t = phase->type(in(2))->isa_intptr_t();
  2259   if (!t)  return NULL;
  2260   if (!t->is_con())  return NULL;
  2261   intptr_t raw_count = t->get_con();
  2262   intptr_t size = raw_count;
  2263   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
  2264   // Clearing nothing uses the Identity call.
  2265   // Negative clears are possible on dead ClearArrays
  2266   // (see jck test stmt114.stmt11402.val).
  2267   if (size <= 0 || size % unit != 0)  return NULL;
  2268   intptr_t count = size / unit;
  2269   // Length too long; use fast hardware clear
  2270   if (size > Matcher::init_array_short_size)  return NULL;
  2271   Node *mem = in(1);
  2272   if( phase->type(mem)==Type::TOP ) return NULL;
  2273   Node *adr = in(3);
  2274   const Type* at = phase->type(adr);
  2275   if( at==Type::TOP ) return NULL;
  2276   const TypePtr* atp = at->isa_ptr();
  2277   // adjust atp to be the correct array element address type
  2278   if (atp == NULL)  atp = TypePtr::BOTTOM;
  2279   else              atp = atp->add_offset(Type::OffsetBot);
  2280   // Get base for derived pointer purposes
  2281   if( adr->Opcode() != Op_AddP ) Unimplemented();
  2282   Node *base = adr->in(1);
  2284   Node *zero = phase->makecon(TypeLong::ZERO);
  2285   Node *off  = phase->MakeConX(BytesPerLong);
  2286   mem = new (phase->C, 4) StoreLNode(in(0),mem,adr,atp,zero);
  2287   count--;
  2288   while( count-- ) {
  2289     mem = phase->transform(mem);
  2290     adr = phase->transform(new (phase->C, 4) AddPNode(base,adr,off));
  2291     mem = new (phase->C, 4) StoreLNode(in(0),mem,adr,atp,zero);
  2293   return mem;
  2296 //----------------------------clear_memory-------------------------------------
  2297 // Generate code to initialize object storage to zero.
  2298 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
  2299                                    intptr_t start_offset,
  2300                                    Node* end_offset,
  2301                                    PhaseGVN* phase) {
  2302   Compile* C = phase->C;
  2303   intptr_t offset = start_offset;
  2305   int unit = BytesPerLong;
  2306   if ((offset % unit) != 0) {
  2307     Node* adr = new (C, 4) AddPNode(dest, dest, phase->MakeConX(offset));
  2308     adr = phase->transform(adr);
  2309     const TypePtr* atp = TypeRawPtr::BOTTOM;
  2310     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT);
  2311     mem = phase->transform(mem);
  2312     offset += BytesPerInt;
  2314   assert((offset % unit) == 0, "");
  2316   // Initialize the remaining stuff, if any, with a ClearArray.
  2317   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
  2320 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
  2321                                    Node* start_offset,
  2322                                    Node* end_offset,
  2323                                    PhaseGVN* phase) {
  2324   if (start_offset == end_offset) {
  2325     // nothing to do
  2326     return mem;
  2329   Compile* C = phase->C;
  2330   int unit = BytesPerLong;
  2331   Node* zbase = start_offset;
  2332   Node* zend  = end_offset;
  2334   // Scale to the unit required by the CPU:
  2335   if (!Matcher::init_array_count_is_in_bytes) {
  2336     Node* shift = phase->intcon(exact_log2(unit));
  2337     zbase = phase->transform( new(C,3) URShiftXNode(zbase, shift) );
  2338     zend  = phase->transform( new(C,3) URShiftXNode(zend,  shift) );
  2341   Node* zsize = phase->transform( new(C,3) SubXNode(zend, zbase) );
  2342   Node* zinit = phase->zerocon((unit == BytesPerLong) ? T_LONG : T_INT);
  2344   // Bulk clear double-words
  2345   Node* adr = phase->transform( new(C,4) AddPNode(dest, dest, start_offset) );
  2346   mem = new (C, 4) ClearArrayNode(ctl, mem, zsize, adr);
  2347   return phase->transform(mem);
  2350 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
  2351                                    intptr_t start_offset,
  2352                                    intptr_t end_offset,
  2353                                    PhaseGVN* phase) {
  2354   if (start_offset == end_offset) {
  2355     // nothing to do
  2356     return mem;
  2359   Compile* C = phase->C;
  2360   assert((end_offset % BytesPerInt) == 0, "odd end offset");
  2361   intptr_t done_offset = end_offset;
  2362   if ((done_offset % BytesPerLong) != 0) {
  2363     done_offset -= BytesPerInt;
  2365   if (done_offset > start_offset) {
  2366     mem = clear_memory(ctl, mem, dest,
  2367                        start_offset, phase->MakeConX(done_offset), phase);
  2369   if (done_offset < end_offset) { // emit the final 32-bit store
  2370     Node* adr = new (C, 4) AddPNode(dest, dest, phase->MakeConX(done_offset));
  2371     adr = phase->transform(adr);
  2372     const TypePtr* atp = TypeRawPtr::BOTTOM;
  2373     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT);
  2374     mem = phase->transform(mem);
  2375     done_offset += BytesPerInt;
  2377   assert(done_offset == end_offset, "");
  2378   return mem;
  2381 //=============================================================================
  2382 // Do we match on this edge? No memory edges
  2383 uint StrCompNode::match_edge(uint idx) const {
  2384   return idx == 5 || idx == 6;
  2387 //------------------------------Ideal------------------------------------------
  2388 // Return a node which is more "ideal" than the current node.  Strip out
  2389 // control copies
  2390 Node *StrCompNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2391   return remove_dead_region(phase, can_reshape) ? this : NULL;
  2394 //------------------------------Ideal------------------------------------------
  2395 // Return a node which is more "ideal" than the current node.  Strip out
  2396 // control copies
  2397 Node *AryEqNode::Ideal(PhaseGVN *phase, bool can_reshape){
  2398   return remove_dead_region(phase, can_reshape) ? this : NULL;
  2402 //=============================================================================
  2403 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
  2404   : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
  2405     _adr_type(C->get_adr_type(alias_idx))
  2407   init_class_id(Class_MemBar);
  2408   Node* top = C->top();
  2409   init_req(TypeFunc::I_O,top);
  2410   init_req(TypeFunc::FramePtr,top);
  2411   init_req(TypeFunc::ReturnAdr,top);
  2412   if (precedent != NULL)
  2413     init_req(TypeFunc::Parms, precedent);
  2416 //------------------------------cmp--------------------------------------------
  2417 uint MemBarNode::hash() const { return NO_HASH; }
  2418 uint MemBarNode::cmp( const Node &n ) const {
  2419   return (&n == this);          // Always fail except on self
  2422 //------------------------------make-------------------------------------------
  2423 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
  2424   int len = Precedent + (pn == NULL? 0: 1);
  2425   switch (opcode) {
  2426   case Op_MemBarAcquire:   return new(C, len) MemBarAcquireNode(C,  atp, pn);
  2427   case Op_MemBarRelease:   return new(C, len) MemBarReleaseNode(C,  atp, pn);
  2428   case Op_MemBarVolatile:  return new(C, len) MemBarVolatileNode(C, atp, pn);
  2429   case Op_MemBarCPUOrder:  return new(C, len) MemBarCPUOrderNode(C, atp, pn);
  2430   case Op_Initialize:      return new(C, len) InitializeNode(C,     atp, pn);
  2431   default:                 ShouldNotReachHere(); return NULL;
  2435 //------------------------------Ideal------------------------------------------
  2436 // Return a node which is more "ideal" than the current node.  Strip out
  2437 // control copies
  2438 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  2439   if (remove_dead_region(phase, can_reshape))  return this;
  2440   return NULL;
  2443 //------------------------------Value------------------------------------------
  2444 const Type *MemBarNode::Value( PhaseTransform *phase ) const {
  2445   if( !in(0) ) return Type::TOP;
  2446   if( phase->type(in(0)) == Type::TOP )
  2447     return Type::TOP;
  2448   return TypeTuple::MEMBAR;
  2451 //------------------------------match------------------------------------------
  2452 // Construct projections for memory.
  2453 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
  2454   switch (proj->_con) {
  2455   case TypeFunc::Control:
  2456   case TypeFunc::Memory:
  2457     return new (m->C, 1) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
  2459   ShouldNotReachHere();
  2460   return NULL;
  2463 //===========================InitializeNode====================================
  2464 // SUMMARY:
  2465 // This node acts as a memory barrier on raw memory, after some raw stores.
  2466 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
  2467 // The Initialize can 'capture' suitably constrained stores as raw inits.
  2468 // It can coalesce related raw stores into larger units (called 'tiles').
  2469 // It can avoid zeroing new storage for memory units which have raw inits.
  2470 // At macro-expansion, it is marked 'complete', and does not optimize further.
  2471 //
  2472 // EXAMPLE:
  2473 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
  2474 //   ctl = incoming control; mem* = incoming memory
  2475 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
  2476 // First allocate uninitialized memory and fill in the header:
  2477 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
  2478 //   ctl := alloc.Control; mem* := alloc.Memory*
  2479 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
  2480 // Then initialize to zero the non-header parts of the raw memory block:
  2481 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
  2482 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
  2483 // After the initialize node executes, the object is ready for service:
  2484 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
  2485 // Suppose its body is immediately initialized as {1,2}:
  2486 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
  2487 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
  2488 //   mem.SLICE(#short[*]) := store2
  2489 //
  2490 // DETAILS:
  2491 // An InitializeNode collects and isolates object initialization after
  2492 // an AllocateNode and before the next possible safepoint.  As a
  2493 // memory barrier (MemBarNode), it keeps critical stores from drifting
  2494 // down past any safepoint or any publication of the allocation.
  2495 // Before this barrier, a newly-allocated object may have uninitialized bits.
  2496 // After this barrier, it may be treated as a real oop, and GC is allowed.
  2497 //
  2498 // The semantics of the InitializeNode include an implicit zeroing of
  2499 // the new object from object header to the end of the object.
  2500 // (The object header and end are determined by the AllocateNode.)
  2501 //
  2502 // Certain stores may be added as direct inputs to the InitializeNode.
  2503 // These stores must update raw memory, and they must be to addresses
  2504 // derived from the raw address produced by AllocateNode, and with
  2505 // a constant offset.  They must be ordered by increasing offset.
  2506 // The first one is at in(RawStores), the last at in(req()-1).
  2507 // Unlike most memory operations, they are not linked in a chain,
  2508 // but are displayed in parallel as users of the rawmem output of
  2509 // the allocation.
  2510 //
  2511 // (See comments in InitializeNode::capture_store, which continue
  2512 // the example given above.)
  2513 //
  2514 // When the associated Allocate is macro-expanded, the InitializeNode
  2515 // may be rewritten to optimize collected stores.  A ClearArrayNode
  2516 // may also be created at that point to represent any required zeroing.
  2517 // The InitializeNode is then marked 'complete', prohibiting further
  2518 // capturing of nearby memory operations.
  2519 //
  2520 // During macro-expansion, all captured initializations which store
  2521 // constant values of 32 bits or smaller are coalesced (if advantagous)
  2522 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
  2523 // initialized in fewer memory operations.  Memory words which are
  2524 // covered by neither tiles nor non-constant stores are pre-zeroed
  2525 // by explicit stores of zero.  (The code shape happens to do all
  2526 // zeroing first, then all other stores, with both sequences occurring
  2527 // in order of ascending offsets.)
  2528 //
  2529 // Alternatively, code may be inserted between an AllocateNode and its
  2530 // InitializeNode, to perform arbitrary initialization of the new object.
  2531 // E.g., the object copying intrinsics insert complex data transfers here.
  2532 // The initialization must then be marked as 'complete' disable the
  2533 // built-in zeroing semantics and the collection of initializing stores.
  2534 //
  2535 // While an InitializeNode is incomplete, reads from the memory state
  2536 // produced by it are optimizable if they match the control edge and
  2537 // new oop address associated with the allocation/initialization.
  2538 // They return a stored value (if the offset matches) or else zero.
  2539 // A write to the memory state, if it matches control and address,
  2540 // and if it is to a constant offset, may be 'captured' by the
  2541 // InitializeNode.  It is cloned as a raw memory operation and rewired
  2542 // inside the initialization, to the raw oop produced by the allocation.
  2543 // Operations on addresses which are provably distinct (e.g., to
  2544 // other AllocateNodes) are allowed to bypass the initialization.
  2545 //
  2546 // The effect of all this is to consolidate object initialization
  2547 // (both arrays and non-arrays, both piecewise and bulk) into a
  2548 // single location, where it can be optimized as a unit.
  2549 //
  2550 // Only stores with an offset less than TrackedInitializationLimit words
  2551 // will be considered for capture by an InitializeNode.  This puts a
  2552 // reasonable limit on the complexity of optimized initializations.
  2554 //---------------------------InitializeNode------------------------------------
  2555 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
  2556   : _is_complete(false),
  2557     MemBarNode(C, adr_type, rawoop)
  2559   init_class_id(Class_Initialize);
  2561   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
  2562   assert(in(RawAddress) == rawoop, "proper init");
  2563   // Note:  allocation() can be NULL, for secondary initialization barriers
  2566 // Since this node is not matched, it will be processed by the
  2567 // register allocator.  Declare that there are no constraints
  2568 // on the allocation of the RawAddress edge.
  2569 const RegMask &InitializeNode::in_RegMask(uint idx) const {
  2570   // This edge should be set to top, by the set_complete.  But be conservative.
  2571   if (idx == InitializeNode::RawAddress)
  2572     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
  2573   return RegMask::Empty;
  2576 Node* InitializeNode::memory(uint alias_idx) {
  2577   Node* mem = in(Memory);
  2578   if (mem->is_MergeMem()) {
  2579     return mem->as_MergeMem()->memory_at(alias_idx);
  2580   } else {
  2581     // incoming raw memory is not split
  2582     return mem;
  2586 bool InitializeNode::is_non_zero() {
  2587   if (is_complete())  return false;
  2588   remove_extra_zeroes();
  2589   return (req() > RawStores);
  2592 void InitializeNode::set_complete(PhaseGVN* phase) {
  2593   assert(!is_complete(), "caller responsibility");
  2594   _is_complete = true;
  2596   // After this node is complete, it contains a bunch of
  2597   // raw-memory initializations.  There is no need for
  2598   // it to have anything to do with non-raw memory effects.
  2599   // Therefore, tell all non-raw users to re-optimize themselves,
  2600   // after skipping the memory effects of this initialization.
  2601   PhaseIterGVN* igvn = phase->is_IterGVN();
  2602   if (igvn)  igvn->add_users_to_worklist(this);
  2605 // convenience function
  2606 // return false if the init contains any stores already
  2607 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
  2608   InitializeNode* init = initialization();
  2609   if (init == NULL || init->is_complete())  return false;
  2610   init->remove_extra_zeroes();
  2611   // for now, if this allocation has already collected any inits, bail:
  2612   if (init->is_non_zero())  return false;
  2613   init->set_complete(phase);
  2614   return true;
  2617 void InitializeNode::remove_extra_zeroes() {
  2618   if (req() == RawStores)  return;
  2619   Node* zmem = zero_memory();
  2620   uint fill = RawStores;
  2621   for (uint i = fill; i < req(); i++) {
  2622     Node* n = in(i);
  2623     if (n->is_top() || n == zmem)  continue;  // skip
  2624     if (fill < i)  set_req(fill, n);          // compact
  2625     ++fill;
  2627   // delete any empty spaces created:
  2628   while (fill < req()) {
  2629     del_req(fill);
  2633 // Helper for remembering which stores go with which offsets.
  2634 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
  2635   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
  2636   intptr_t offset = -1;
  2637   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
  2638                                                phase, offset);
  2639   if (base == NULL)     return -1;  // something is dead,
  2640   if (offset < 0)       return -1;  //        dead, dead
  2641   return offset;
  2644 // Helper for proving that an initialization expression is
  2645 // "simple enough" to be folded into an object initialization.
  2646 // Attempts to prove that a store's initial value 'n' can be captured
  2647 // within the initialization without creating a vicious cycle, such as:
  2648 //     { Foo p = new Foo(); p.next = p; }
  2649 // True for constants and parameters and small combinations thereof.
  2650 bool InitializeNode::detect_init_independence(Node* n,
  2651                                               bool st_is_pinned,
  2652                                               int& count) {
  2653   if (n == NULL)      return true;   // (can this really happen?)
  2654   if (n->is_Proj())   n = n->in(0);
  2655   if (n == this)      return false;  // found a cycle
  2656   if (n->is_Con())    return true;
  2657   if (n->is_Start())  return true;   // params, etc., are OK
  2658   if (n->is_Root())   return true;   // even better
  2660   Node* ctl = n->in(0);
  2661   if (ctl != NULL && !ctl->is_top()) {
  2662     if (ctl->is_Proj())  ctl = ctl->in(0);
  2663     if (ctl == this)  return false;
  2665     // If we already know that the enclosing memory op is pinned right after
  2666     // the init, then any control flow that the store has picked up
  2667     // must have preceded the init, or else be equal to the init.
  2668     // Even after loop optimizations (which might change control edges)
  2669     // a store is never pinned *before* the availability of its inputs.
  2670     if (!MemNode::all_controls_dominate(n, this))
  2671       return false;                  // failed to prove a good control
  2675   // Check data edges for possible dependencies on 'this'.
  2676   if ((count += 1) > 20)  return false;  // complexity limit
  2677   for (uint i = 1; i < n->req(); i++) {
  2678     Node* m = n->in(i);
  2679     if (m == NULL || m == n || m->is_top())  continue;
  2680     uint first_i = n->find_edge(m);
  2681     if (i != first_i)  continue;  // process duplicate edge just once
  2682     if (!detect_init_independence(m, st_is_pinned, count)) {
  2683       return false;
  2687   return true;
  2690 // Here are all the checks a Store must pass before it can be moved into
  2691 // an initialization.  Returns zero if a check fails.
  2692 // On success, returns the (constant) offset to which the store applies,
  2693 // within the initialized memory.
  2694 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase) {
  2695   const int FAIL = 0;
  2696   if (st->req() != MemNode::ValueIn + 1)
  2697     return FAIL;                // an inscrutable StoreNode (card mark?)
  2698   Node* ctl = st->in(MemNode::Control);
  2699   if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
  2700     return FAIL;                // must be unconditional after the initialization
  2701   Node* mem = st->in(MemNode::Memory);
  2702   if (!(mem->is_Proj() && mem->in(0) == this))
  2703     return FAIL;                // must not be preceded by other stores
  2704   Node* adr = st->in(MemNode::Address);
  2705   intptr_t offset;
  2706   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
  2707   if (alloc == NULL)
  2708     return FAIL;                // inscrutable address
  2709   if (alloc != allocation())
  2710     return FAIL;                // wrong allocation!  (store needs to float up)
  2711   Node* val = st->in(MemNode::ValueIn);
  2712   int complexity_count = 0;
  2713   if (!detect_init_independence(val, true, complexity_count))
  2714     return FAIL;                // stored value must be 'simple enough'
  2716   return offset;                // success
  2719 // Find the captured store in(i) which corresponds to the range
  2720 // [start..start+size) in the initialized object.
  2721 // If there is one, return its index i.  If there isn't, return the
  2722 // negative of the index where it should be inserted.
  2723 // Return 0 if the queried range overlaps an initialization boundary
  2724 // or if dead code is encountered.
  2725 // If size_in_bytes is zero, do not bother with overlap checks.
  2726 int InitializeNode::captured_store_insertion_point(intptr_t start,
  2727                                                    int size_in_bytes,
  2728                                                    PhaseTransform* phase) {
  2729   const int FAIL = 0, MAX_STORE = BytesPerLong;
  2731   if (is_complete())
  2732     return FAIL;                // arraycopy got here first; punt
  2734   assert(allocation() != NULL, "must be present");
  2736   // no negatives, no header fields:
  2737   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
  2739   // after a certain size, we bail out on tracking all the stores:
  2740   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
  2741   if (start >= ti_limit)  return FAIL;
  2743   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
  2744     if (i >= limit)  return -(int)i; // not found; here is where to put it
  2746     Node*    st     = in(i);
  2747     intptr_t st_off = get_store_offset(st, phase);
  2748     if (st_off < 0) {
  2749       if (st != zero_memory()) {
  2750         return FAIL;            // bail out if there is dead garbage
  2752     } else if (st_off > start) {
  2753       // ...we are done, since stores are ordered
  2754       if (st_off < start + size_in_bytes) {
  2755         return FAIL;            // the next store overlaps
  2757       return -(int)i;           // not found; here is where to put it
  2758     } else if (st_off < start) {
  2759       if (size_in_bytes != 0 &&
  2760           start < st_off + MAX_STORE &&
  2761           start < st_off + st->as_Store()->memory_size()) {
  2762         return FAIL;            // the previous store overlaps
  2764     } else {
  2765       if (size_in_bytes != 0 &&
  2766           st->as_Store()->memory_size() != size_in_bytes) {
  2767         return FAIL;            // mismatched store size
  2769       return i;
  2772     ++i;
  2776 // Look for a captured store which initializes at the offset 'start'
  2777 // with the given size.  If there is no such store, and no other
  2778 // initialization interferes, then return zero_memory (the memory
  2779 // projection of the AllocateNode).
  2780 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
  2781                                           PhaseTransform* phase) {
  2782   assert(stores_are_sane(phase), "");
  2783   int i = captured_store_insertion_point(start, size_in_bytes, phase);
  2784   if (i == 0) {
  2785     return NULL;                // something is dead
  2786   } else if (i < 0) {
  2787     return zero_memory();       // just primordial zero bits here
  2788   } else {
  2789     Node* st = in(i);           // here is the store at this position
  2790     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
  2791     return st;
  2795 // Create, as a raw pointer, an address within my new object at 'offset'.
  2796 Node* InitializeNode::make_raw_address(intptr_t offset,
  2797                                        PhaseTransform* phase) {
  2798   Node* addr = in(RawAddress);
  2799   if (offset != 0) {
  2800     Compile* C = phase->C;
  2801     addr = phase->transform( new (C, 4) AddPNode(C->top(), addr,
  2802                                                  phase->MakeConX(offset)) );
  2804   return addr;
  2807 // Clone the given store, converting it into a raw store
  2808 // initializing a field or element of my new object.
  2809 // Caller is responsible for retiring the original store,
  2810 // with subsume_node or the like.
  2811 //
  2812 // From the example above InitializeNode::InitializeNode,
  2813 // here are the old stores to be captured:
  2814 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
  2815 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
  2816 //
  2817 // Here is the changed code; note the extra edges on init:
  2818 //   alloc = (Allocate ...)
  2819 //   rawoop = alloc.RawAddress
  2820 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
  2821 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
  2822 //   init = (Initialize alloc.Control alloc.Memory rawoop
  2823 //                      rawstore1 rawstore2)
  2824 //
  2825 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
  2826                                     PhaseTransform* phase) {
  2827   assert(stores_are_sane(phase), "");
  2829   if (start < 0)  return NULL;
  2830   assert(can_capture_store(st, phase) == start, "sanity");
  2832   Compile* C = phase->C;
  2833   int size_in_bytes = st->memory_size();
  2834   int i = captured_store_insertion_point(start, size_in_bytes, phase);
  2835   if (i == 0)  return NULL;     // bail out
  2836   Node* prev_mem = NULL;        // raw memory for the captured store
  2837   if (i > 0) {
  2838     prev_mem = in(i);           // there is a pre-existing store under this one
  2839     set_req(i, C->top());       // temporarily disconnect it
  2840     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
  2841   } else {
  2842     i = -i;                     // no pre-existing store
  2843     prev_mem = zero_memory();   // a slice of the newly allocated object
  2844     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
  2845       set_req(--i, C->top());   // reuse this edge; it has been folded away
  2846     else
  2847       ins_req(i, C->top());     // build a new edge
  2849   Node* new_st = st->clone();
  2850   new_st->set_req(MemNode::Control, in(Control));
  2851   new_st->set_req(MemNode::Memory,  prev_mem);
  2852   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
  2853   new_st = phase->transform(new_st);
  2855   // At this point, new_st might have swallowed a pre-existing store
  2856   // at the same offset, or perhaps new_st might have disappeared,
  2857   // if it redundantly stored the same value (or zero to fresh memory).
  2859   // In any case, wire it in:
  2860   set_req(i, new_st);
  2862   // The caller may now kill the old guy.
  2863   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
  2864   assert(check_st == new_st || check_st == NULL, "must be findable");
  2865   assert(!is_complete(), "");
  2866   return new_st;
  2869 static bool store_constant(jlong* tiles, int num_tiles,
  2870                            intptr_t st_off, int st_size,
  2871                            jlong con) {
  2872   if ((st_off & (st_size-1)) != 0)
  2873     return false;               // strange store offset (assume size==2**N)
  2874   address addr = (address)tiles + st_off;
  2875   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
  2876   switch (st_size) {
  2877   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
  2878   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
  2879   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
  2880   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
  2881   default: return false;        // strange store size (detect size!=2**N here)
  2883   return true;                  // return success to caller
  2886 // Coalesce subword constants into int constants and possibly
  2887 // into long constants.  The goal, if the CPU permits,
  2888 // is to initialize the object with a small number of 64-bit tiles.
  2889 // Also, convert floating-point constants to bit patterns.
  2890 // Non-constants are not relevant to this pass.
  2891 //
  2892 // In terms of the running example on InitializeNode::InitializeNode
  2893 // and InitializeNode::capture_store, here is the transformation
  2894 // of rawstore1 and rawstore2 into rawstore12:
  2895 //   alloc = (Allocate ...)
  2896 //   rawoop = alloc.RawAddress
  2897 //   tile12 = 0x00010002
  2898 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
  2899 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
  2900 //
  2901 void
  2902 InitializeNode::coalesce_subword_stores(intptr_t header_size,
  2903                                         Node* size_in_bytes,
  2904                                         PhaseGVN* phase) {
  2905   Compile* C = phase->C;
  2907   assert(stores_are_sane(phase), "");
  2908   // Note:  After this pass, they are not completely sane,
  2909   // since there may be some overlaps.
  2911   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
  2913   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
  2914   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
  2915   size_limit = MIN2(size_limit, ti_limit);
  2916   size_limit = align_size_up(size_limit, BytesPerLong);
  2917   int num_tiles = size_limit / BytesPerLong;
  2919   // allocate space for the tile map:
  2920   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
  2921   jlong  tiles_buf[small_len];
  2922   Node*  nodes_buf[small_len];
  2923   jlong  inits_buf[small_len];
  2924   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
  2925                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
  2926   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
  2927                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
  2928   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
  2929                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
  2930   // tiles: exact bitwise model of all primitive constants
  2931   // nodes: last constant-storing node subsumed into the tiles model
  2932   // inits: which bytes (in each tile) are touched by any initializations
  2934   //// Pass A: Fill in the tile model with any relevant stores.
  2936   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
  2937   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
  2938   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
  2939   Node* zmem = zero_memory(); // initially zero memory state
  2940   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
  2941     Node* st = in(i);
  2942     intptr_t st_off = get_store_offset(st, phase);
  2944     // Figure out the store's offset and constant value:
  2945     if (st_off < header_size)             continue; //skip (ignore header)
  2946     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
  2947     int st_size = st->as_Store()->memory_size();
  2948     if (st_off + st_size > size_limit)    break;
  2950     // Record which bytes are touched, whether by constant or not.
  2951     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
  2952       continue;                 // skip (strange store size)
  2954     const Type* val = phase->type(st->in(MemNode::ValueIn));
  2955     if (!val->singleton())                continue; //skip (non-con store)
  2956     BasicType type = val->basic_type();
  2958     jlong con = 0;
  2959     switch (type) {
  2960     case T_INT:    con = val->is_int()->get_con();  break;
  2961     case T_LONG:   con = val->is_long()->get_con(); break;
  2962     case T_FLOAT:  con = jint_cast(val->getf());    break;
  2963     case T_DOUBLE: con = jlong_cast(val->getd());   break;
  2964     default:                              continue; //skip (odd store type)
  2967     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
  2968         st->Opcode() == Op_StoreL) {
  2969       continue;                 // This StoreL is already optimal.
  2972     // Store down the constant.
  2973     store_constant(tiles, num_tiles, st_off, st_size, con);
  2975     intptr_t j = st_off >> LogBytesPerLong;
  2977     if (type == T_INT && st_size == BytesPerInt
  2978         && (st_off & BytesPerInt) == BytesPerInt) {
  2979       jlong lcon = tiles[j];
  2980       if (!Matcher::isSimpleConstant64(lcon) &&
  2981           st->Opcode() == Op_StoreI) {
  2982         // This StoreI is already optimal by itself.
  2983         jint* intcon = (jint*) &tiles[j];
  2984         intcon[1] = 0;  // undo the store_constant()
  2986         // If the previous store is also optimal by itself, back up and
  2987         // undo the action of the previous loop iteration... if we can.
  2988         // But if we can't, just let the previous half take care of itself.
  2989         st = nodes[j];
  2990         st_off -= BytesPerInt;
  2991         con = intcon[0];
  2992         if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
  2993           assert(st_off >= header_size, "still ignoring header");
  2994           assert(get_store_offset(st, phase) == st_off, "must be");
  2995           assert(in(i-1) == zmem, "must be");
  2996           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
  2997           assert(con == tcon->is_int()->get_con(), "must be");
  2998           // Undo the effects of the previous loop trip, which swallowed st:
  2999           intcon[0] = 0;        // undo store_constant()
  3000           set_req(i-1, st);     // undo set_req(i, zmem)
  3001           nodes[j] = NULL;      // undo nodes[j] = st
  3002           --old_subword;        // undo ++old_subword
  3004         continue;               // This StoreI is already optimal.
  3008     // This store is not needed.
  3009     set_req(i, zmem);
  3010     nodes[j] = st;              // record for the moment
  3011     if (st_size < BytesPerLong) // something has changed
  3012           ++old_subword;        // includes int/float, but who's counting...
  3013     else  ++old_long;
  3016   if ((old_subword + old_long) == 0)
  3017     return;                     // nothing more to do
  3019   //// Pass B: Convert any non-zero tiles into optimal constant stores.
  3020   // Be sure to insert them before overlapping non-constant stores.
  3021   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
  3022   for (int j = 0; j < num_tiles; j++) {
  3023     jlong con  = tiles[j];
  3024     jlong init = inits[j];
  3025     if (con == 0)  continue;
  3026     jint con0,  con1;           // split the constant, address-wise
  3027     jint init0, init1;          // split the init map, address-wise
  3028     { union { jlong con; jint intcon[2]; } u;
  3029       u.con = con;
  3030       con0  = u.intcon[0];
  3031       con1  = u.intcon[1];
  3032       u.con = init;
  3033       init0 = u.intcon[0];
  3034       init1 = u.intcon[1];
  3037     Node* old = nodes[j];
  3038     assert(old != NULL, "need the prior store");
  3039     intptr_t offset = (j * BytesPerLong);
  3041     bool split = !Matcher::isSimpleConstant64(con);
  3043     if (offset < header_size) {
  3044       assert(offset + BytesPerInt >= header_size, "second int counts");
  3045       assert(*(jint*)&tiles[j] == 0, "junk in header");
  3046       split = true;             // only the second word counts
  3047       // Example:  int a[] = { 42 ... }
  3048     } else if (con0 == 0 && init0 == -1) {
  3049       split = true;             // first word is covered by full inits
  3050       // Example:  int a[] = { ... foo(), 42 ... }
  3051     } else if (con1 == 0 && init1 == -1) {
  3052       split = true;             // second word is covered by full inits
  3053       // Example:  int a[] = { ... 42, foo() ... }
  3056     // Here's a case where init0 is neither 0 nor -1:
  3057     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
  3058     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
  3059     // In this case the tile is not split; it is (jlong)42.
  3060     // The big tile is stored down, and then the foo() value is inserted.
  3061     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
  3063     Node* ctl = old->in(MemNode::Control);
  3064     Node* adr = make_raw_address(offset, phase);
  3065     const TypePtr* atp = TypeRawPtr::BOTTOM;
  3067     // One or two coalesced stores to plop down.
  3068     Node*    st[2];
  3069     intptr_t off[2];
  3070     int  nst = 0;
  3071     if (!split) {
  3072       ++new_long;
  3073       off[nst] = offset;
  3074       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
  3075                                   phase->longcon(con), T_LONG);
  3076     } else {
  3077       // Omit either if it is a zero.
  3078       if (con0 != 0) {
  3079         ++new_int;
  3080         off[nst]  = offset;
  3081         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
  3082                                     phase->intcon(con0), T_INT);
  3084       if (con1 != 0) {
  3085         ++new_int;
  3086         offset += BytesPerInt;
  3087         adr = make_raw_address(offset, phase);
  3088         off[nst]  = offset;
  3089         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
  3090                                     phase->intcon(con1), T_INT);
  3094     // Insert second store first, then the first before the second.
  3095     // Insert each one just before any overlapping non-constant stores.
  3096     while (nst > 0) {
  3097       Node* st1 = st[--nst];
  3098       C->copy_node_notes_to(st1, old);
  3099       st1 = phase->transform(st1);
  3100       offset = off[nst];
  3101       assert(offset >= header_size, "do not smash header");
  3102       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
  3103       guarantee(ins_idx != 0, "must re-insert constant store");
  3104       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
  3105       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
  3106         set_req(--ins_idx, st1);
  3107       else
  3108         ins_req(ins_idx, st1);
  3112   if (PrintCompilation && WizardMode)
  3113     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
  3114                   old_subword, old_long, new_int, new_long);
  3115   if (C->log() != NULL)
  3116     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
  3117                    old_subword, old_long, new_int, new_long);
  3119   // Clean up any remaining occurrences of zmem:
  3120   remove_extra_zeroes();
  3123 // Explore forward from in(start) to find the first fully initialized
  3124 // word, and return its offset.  Skip groups of subword stores which
  3125 // together initialize full words.  If in(start) is itself part of a
  3126 // fully initialized word, return the offset of in(start).  If there
  3127 // are no following full-word stores, or if something is fishy, return
  3128 // a negative value.
  3129 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
  3130   int       int_map = 0;
  3131   intptr_t  int_map_off = 0;
  3132   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
  3134   for (uint i = start, limit = req(); i < limit; i++) {
  3135     Node* st = in(i);
  3137     intptr_t st_off = get_store_offset(st, phase);
  3138     if (st_off < 0)  break;  // return conservative answer
  3140     int st_size = st->as_Store()->memory_size();
  3141     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
  3142       return st_off;            // we found a complete word init
  3145     // update the map:
  3147     intptr_t this_int_off = align_size_down(st_off, BytesPerInt);
  3148     if (this_int_off != int_map_off) {
  3149       // reset the map:
  3150       int_map = 0;
  3151       int_map_off = this_int_off;
  3154     int subword_off = st_off - this_int_off;
  3155     int_map |= right_n_bits(st_size) << subword_off;
  3156     if ((int_map & FULL_MAP) == FULL_MAP) {
  3157       return this_int_off;      // we found a complete word init
  3160     // Did this store hit or cross the word boundary?
  3161     intptr_t next_int_off = align_size_down(st_off + st_size, BytesPerInt);
  3162     if (next_int_off == this_int_off + BytesPerInt) {
  3163       // We passed the current int, without fully initializing it.
  3164       int_map_off = next_int_off;
  3165       int_map >>= BytesPerInt;
  3166     } else if (next_int_off > this_int_off + BytesPerInt) {
  3167       // We passed the current and next int.
  3168       return this_int_off + BytesPerInt;
  3172   return -1;
  3176 // Called when the associated AllocateNode is expanded into CFG.
  3177 // At this point, we may perform additional optimizations.
  3178 // Linearize the stores by ascending offset, to make memory
  3179 // activity as coherent as possible.
  3180 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
  3181                                       intptr_t header_size,
  3182                                       Node* size_in_bytes,
  3183                                       PhaseGVN* phase) {
  3184   assert(!is_complete(), "not already complete");
  3185   assert(stores_are_sane(phase), "");
  3186   assert(allocation() != NULL, "must be present");
  3188   remove_extra_zeroes();
  3190   if (ReduceFieldZeroing || ReduceBulkZeroing)
  3191     // reduce instruction count for common initialization patterns
  3192     coalesce_subword_stores(header_size, size_in_bytes, phase);
  3194   Node* zmem = zero_memory();   // initially zero memory state
  3195   Node* inits = zmem;           // accumulating a linearized chain of inits
  3196   #ifdef ASSERT
  3197   intptr_t first_offset = allocation()->minimum_header_size();
  3198   intptr_t last_init_off = first_offset;  // previous init offset
  3199   intptr_t last_init_end = first_offset;  // previous init offset+size
  3200   intptr_t last_tile_end = first_offset;  // previous tile offset+size
  3201   #endif
  3202   intptr_t zeroes_done = header_size;
  3204   bool do_zeroing = true;       // we might give up if inits are very sparse
  3205   int  big_init_gaps = 0;       // how many large gaps have we seen?
  3207   if (ZeroTLAB)  do_zeroing = false;
  3208   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
  3210   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
  3211     Node* st = in(i);
  3212     intptr_t st_off = get_store_offset(st, phase);
  3213     if (st_off < 0)
  3214       break;                    // unknown junk in the inits
  3215     if (st->in(MemNode::Memory) != zmem)
  3216       break;                    // complicated store chains somehow in list
  3218     int st_size = st->as_Store()->memory_size();
  3219     intptr_t next_init_off = st_off + st_size;
  3221     if (do_zeroing && zeroes_done < next_init_off) {
  3222       // See if this store needs a zero before it or under it.
  3223       intptr_t zeroes_needed = st_off;
  3225       if (st_size < BytesPerInt) {
  3226         // Look for subword stores which only partially initialize words.
  3227         // If we find some, we must lay down some word-level zeroes first,
  3228         // underneath the subword stores.
  3229         //
  3230         // Examples:
  3231         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
  3232         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
  3233         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
  3234         //
  3235         // Note:  coalesce_subword_stores may have already done this,
  3236         // if it was prompted by constant non-zero subword initializers.
  3237         // But this case can still arise with non-constant stores.
  3239         intptr_t next_full_store = find_next_fullword_store(i, phase);
  3241         // In the examples above:
  3242         //   in(i)          p   q   r   s     x   y     z
  3243         //   st_off        12  13  14  15    12  13    14
  3244         //   st_size        1   1   1   1     1   1     1
  3245         //   next_full_s.  12  16  16  16    16  16    16
  3246         //   z's_done      12  16  16  16    12  16    12
  3247         //   z's_needed    12  16  16  16    16  16    16
  3248         //   zsize          0   0   0   0     4   0     4
  3249         if (next_full_store < 0) {
  3250           // Conservative tack:  Zero to end of current word.
  3251           zeroes_needed = align_size_up(zeroes_needed, BytesPerInt);
  3252         } else {
  3253           // Zero to beginning of next fully initialized word.
  3254           // Or, don't zero at all, if we are already in that word.
  3255           assert(next_full_store >= zeroes_needed, "must go forward");
  3256           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
  3257           zeroes_needed = next_full_store;
  3261       if (zeroes_needed > zeroes_done) {
  3262         intptr_t zsize = zeroes_needed - zeroes_done;
  3263         // Do some incremental zeroing on rawmem, in parallel with inits.
  3264         zeroes_done = align_size_down(zeroes_done, BytesPerInt);
  3265         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
  3266                                               zeroes_done, zeroes_needed,
  3267                                               phase);
  3268         zeroes_done = zeroes_needed;
  3269         if (zsize > Matcher::init_array_short_size && ++big_init_gaps > 2)
  3270           do_zeroing = false;   // leave the hole, next time
  3274     // Collect the store and move on:
  3275     st->set_req(MemNode::Memory, inits);
  3276     inits = st;                 // put it on the linearized chain
  3277     set_req(i, zmem);           // unhook from previous position
  3279     if (zeroes_done == st_off)
  3280       zeroes_done = next_init_off;
  3282     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
  3284     #ifdef ASSERT
  3285     // Various order invariants.  Weaker than stores_are_sane because
  3286     // a large constant tile can be filled in by smaller non-constant stores.
  3287     assert(st_off >= last_init_off, "inits do not reverse");
  3288     last_init_off = st_off;
  3289     const Type* val = NULL;
  3290     if (st_size >= BytesPerInt &&
  3291         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
  3292         (int)val->basic_type() < (int)T_OBJECT) {
  3293       assert(st_off >= last_tile_end, "tiles do not overlap");
  3294       assert(st_off >= last_init_end, "tiles do not overwrite inits");
  3295       last_tile_end = MAX2(last_tile_end, next_init_off);
  3296     } else {
  3297       intptr_t st_tile_end = align_size_up(next_init_off, BytesPerLong);
  3298       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
  3299       assert(st_off      >= last_init_end, "inits do not overlap");
  3300       last_init_end = next_init_off;  // it's a non-tile
  3302     #endif //ASSERT
  3305   remove_extra_zeroes();        // clear out all the zmems left over
  3306   add_req(inits);
  3308   if (!ZeroTLAB) {
  3309     // If anything remains to be zeroed, zero it all now.
  3310     zeroes_done = align_size_down(zeroes_done, BytesPerInt);
  3311     // if it is the last unused 4 bytes of an instance, forget about it
  3312     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
  3313     if (zeroes_done + BytesPerLong >= size_limit) {
  3314       assert(allocation() != NULL, "");
  3315       Node* klass_node = allocation()->in(AllocateNode::KlassNode);
  3316       ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
  3317       if (zeroes_done == k->layout_helper())
  3318         zeroes_done = size_limit;
  3320     if (zeroes_done < size_limit) {
  3321       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
  3322                                             zeroes_done, size_in_bytes, phase);
  3326   set_complete(phase);
  3327   return rawmem;
  3331 #ifdef ASSERT
  3332 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
  3333   if (is_complete())
  3334     return true;                // stores could be anything at this point
  3335   assert(allocation() != NULL, "must be present");
  3336   intptr_t last_off = allocation()->minimum_header_size();
  3337   for (uint i = InitializeNode::RawStores; i < req(); i++) {
  3338     Node* st = in(i);
  3339     intptr_t st_off = get_store_offset(st, phase);
  3340     if (st_off < 0)  continue;  // ignore dead garbage
  3341     if (last_off > st_off) {
  3342       tty->print_cr("*** bad store offset at %d: %d > %d", i, last_off, st_off);
  3343       this->dump(2);
  3344       assert(false, "ascending store offsets");
  3345       return false;
  3347     last_off = st_off + st->as_Store()->memory_size();
  3349   return true;
  3351 #endif //ASSERT
  3356 //============================MergeMemNode=====================================
  3357 //
  3358 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
  3359 // contributing store or call operations.  Each contributor provides the memory
  3360 // state for a particular "alias type" (see Compile::alias_type).  For example,
  3361 // if a MergeMem has an input X for alias category #6, then any memory reference
  3362 // to alias category #6 may use X as its memory state input, as an exact equivalent
  3363 // to using the MergeMem as a whole.
  3364 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
  3365 //
  3366 // (Here, the <N> notation gives the index of the relevant adr_type.)
  3367 //
  3368 // In one special case (and more cases in the future), alias categories overlap.
  3369 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
  3370 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
  3371 // it is exactly equivalent to that state W:
  3372 //   MergeMem(<Bot>: W) <==> W
  3373 //
  3374 // Usually, the merge has more than one input.  In that case, where inputs
  3375 // overlap (i.e., one is Bot), the narrower alias type determines the memory
  3376 // state for that type, and the wider alias type (Bot) fills in everywhere else:
  3377 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
  3378 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
  3379 //
  3380 // A merge can take a "wide" memory state as one of its narrow inputs.
  3381 // This simply means that the merge observes out only the relevant parts of
  3382 // the wide input.  That is, wide memory states arriving at narrow merge inputs
  3383 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
  3384 //
  3385 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
  3386 // and that memory slices "leak through":
  3387 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
  3388 //
  3389 // But, in such a cascade, repeated memory slices can "block the leak":
  3390 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
  3391 //
  3392 // In the last example, Y is not part of the combined memory state of the
  3393 // outermost MergeMem.  The system must, of course, prevent unschedulable
  3394 // memory states from arising, so you can be sure that the state Y is somehow
  3395 // a precursor to state Y'.
  3396 //
  3397 //
  3398 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
  3399 // of each MergeMemNode array are exactly the numerical alias indexes, including
  3400 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
  3401 // Compile::alias_type (and kin) produce and manage these indexes.
  3402 //
  3403 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
  3404 // (Note that this provides quick access to the top node inside MergeMem methods,
  3405 // without the need to reach out via TLS to Compile::current.)
  3406 //
  3407 // As a consequence of what was just described, a MergeMem that represents a full
  3408 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
  3409 // containing all alias categories.
  3410 //
  3411 // MergeMem nodes never (?) have control inputs, so in(0) is NULL.
  3412 //
  3413 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
  3414 // a memory state for the alias type <N>, or else the top node, meaning that
  3415 // there is no particular input for that alias type.  Note that the length of
  3416 // a MergeMem is variable, and may be extended at any time to accommodate new
  3417 // memory states at larger alias indexes.  When merges grow, they are of course
  3418 // filled with "top" in the unused in() positions.
  3419 //
  3420 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
  3421 // (Top was chosen because it works smoothly with passes like GCM.)
  3422 //
  3423 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
  3424 // the type of random VM bits like TLS references.)  Since it is always the
  3425 // first non-Bot memory slice, some low-level loops use it to initialize an
  3426 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
  3427 //
  3428 //
  3429 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
  3430 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
  3431 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
  3432 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
  3433 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
  3434 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
  3435 //
  3436 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
  3437 // really that different from the other memory inputs.  An abbreviation called
  3438 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
  3439 //
  3440 //
  3441 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
  3442 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
  3443 // that "emerges though" the base memory will be marked as excluding the alias types
  3444 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
  3445 //
  3446 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
  3447 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
  3448 //
  3449 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
  3450 // (It is currently unimplemented.)  As you can see, the resulting merge is
  3451 // actually a disjoint union of memory states, rather than an overlay.
  3452 //
  3454 //------------------------------MergeMemNode-----------------------------------
  3455 Node* MergeMemNode::make_empty_memory() {
  3456   Node* empty_memory = (Node*) Compile::current()->top();
  3457   assert(empty_memory->is_top(), "correct sentinel identity");
  3458   return empty_memory;
  3461 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
  3462   init_class_id(Class_MergeMem);
  3463   // all inputs are nullified in Node::Node(int)
  3464   // set_input(0, NULL);  // no control input
  3466   // Initialize the edges uniformly to top, for starters.
  3467   Node* empty_mem = make_empty_memory();
  3468   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
  3469     init_req(i,empty_mem);
  3471   assert(empty_memory() == empty_mem, "");
  3473   if( new_base != NULL && new_base->is_MergeMem() ) {
  3474     MergeMemNode* mdef = new_base->as_MergeMem();
  3475     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
  3476     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
  3477       mms.set_memory(mms.memory2());
  3479     assert(base_memory() == mdef->base_memory(), "");
  3480   } else {
  3481     set_base_memory(new_base);
  3485 // Make a new, untransformed MergeMem with the same base as 'mem'.
  3486 // If mem is itself a MergeMem, populate the result with the same edges.
  3487 MergeMemNode* MergeMemNode::make(Compile* C, Node* mem) {
  3488   return new(C, 1+Compile::AliasIdxRaw) MergeMemNode(mem);
  3491 //------------------------------cmp--------------------------------------------
  3492 uint MergeMemNode::hash() const { return NO_HASH; }
  3493 uint MergeMemNode::cmp( const Node &n ) const {
  3494   return (&n == this);          // Always fail except on self
  3497 //------------------------------Identity---------------------------------------
  3498 Node* MergeMemNode::Identity(PhaseTransform *phase) {
  3499   // Identity if this merge point does not record any interesting memory
  3500   // disambiguations.
  3501   Node* base_mem = base_memory();
  3502   Node* empty_mem = empty_memory();
  3503   if (base_mem != empty_mem) {  // Memory path is not dead?
  3504     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  3505       Node* mem = in(i);
  3506       if (mem != empty_mem && mem != base_mem) {
  3507         return this;            // Many memory splits; no change
  3511   return base_mem;              // No memory splits; ID on the one true input
  3514 //------------------------------Ideal------------------------------------------
  3515 // This method is invoked recursively on chains of MergeMem nodes
  3516 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
  3517   // Remove chain'd MergeMems
  3518   //
  3519   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
  3520   // relative to the "in(Bot)".  Since we are patching both at the same time,
  3521   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
  3522   // but rewrite each "in(i)" relative to the new "in(Bot)".
  3523   Node *progress = NULL;
  3526   Node* old_base = base_memory();
  3527   Node* empty_mem = empty_memory();
  3528   if (old_base == empty_mem)
  3529     return NULL; // Dead memory path.
  3531   MergeMemNode* old_mbase;
  3532   if (old_base != NULL && old_base->is_MergeMem())
  3533     old_mbase = old_base->as_MergeMem();
  3534   else
  3535     old_mbase = NULL;
  3536   Node* new_base = old_base;
  3538   // simplify stacked MergeMems in base memory
  3539   if (old_mbase)  new_base = old_mbase->base_memory();
  3541   // the base memory might contribute new slices beyond my req()
  3542   if (old_mbase)  grow_to_match(old_mbase);
  3544   // Look carefully at the base node if it is a phi.
  3545   PhiNode* phi_base;
  3546   if (new_base != NULL && new_base->is_Phi())
  3547     phi_base = new_base->as_Phi();
  3548   else
  3549     phi_base = NULL;
  3551   Node*    phi_reg = NULL;
  3552   uint     phi_len = (uint)-1;
  3553   if (phi_base != NULL && !phi_base->is_copy()) {
  3554     // do not examine phi if degraded to a copy
  3555     phi_reg = phi_base->region();
  3556     phi_len = phi_base->req();
  3557     // see if the phi is unfinished
  3558     for (uint i = 1; i < phi_len; i++) {
  3559       if (phi_base->in(i) == NULL) {
  3560         // incomplete phi; do not look at it yet!
  3561         phi_reg = NULL;
  3562         phi_len = (uint)-1;
  3563         break;
  3568   // Note:  We do not call verify_sparse on entry, because inputs
  3569   // can normalize to the base_memory via subsume_node or similar
  3570   // mechanisms.  This method repairs that damage.
  3572   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
  3574   // Look at each slice.
  3575   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  3576     Node* old_in = in(i);
  3577     // calculate the old memory value
  3578     Node* old_mem = old_in;
  3579     if (old_mem == empty_mem)  old_mem = old_base;
  3580     assert(old_mem == memory_at(i), "");
  3582     // maybe update (reslice) the old memory value
  3584     // simplify stacked MergeMems
  3585     Node* new_mem = old_mem;
  3586     MergeMemNode* old_mmem;
  3587     if (old_mem != NULL && old_mem->is_MergeMem())
  3588       old_mmem = old_mem->as_MergeMem();
  3589     else
  3590       old_mmem = NULL;
  3591     if (old_mmem == this) {
  3592       // This can happen if loops break up and safepoints disappear.
  3593       // A merge of BotPtr (default) with a RawPtr memory derived from a
  3594       // safepoint can be rewritten to a merge of the same BotPtr with
  3595       // the BotPtr phi coming into the loop.  If that phi disappears
  3596       // also, we can end up with a self-loop of the mergemem.
  3597       // In general, if loops degenerate and memory effects disappear,
  3598       // a mergemem can be left looking at itself.  This simply means
  3599       // that the mergemem's default should be used, since there is
  3600       // no longer any apparent effect on this slice.
  3601       // Note: If a memory slice is a MergeMem cycle, it is unreachable
  3602       //       from start.  Update the input to TOP.
  3603       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
  3605     else if (old_mmem != NULL) {
  3606       new_mem = old_mmem->memory_at(i);
  3608     // else preceeding memory was not a MergeMem
  3610     // replace equivalent phis (unfortunately, they do not GVN together)
  3611     if (new_mem != NULL && new_mem != new_base &&
  3612         new_mem->req() == phi_len && new_mem->in(0) == phi_reg) {
  3613       if (new_mem->is_Phi()) {
  3614         PhiNode* phi_mem = new_mem->as_Phi();
  3615         for (uint i = 1; i < phi_len; i++) {
  3616           if (phi_base->in(i) != phi_mem->in(i)) {
  3617             phi_mem = NULL;
  3618             break;
  3621         if (phi_mem != NULL) {
  3622           // equivalent phi nodes; revert to the def
  3623           new_mem = new_base;
  3628     // maybe store down a new value
  3629     Node* new_in = new_mem;
  3630     if (new_in == new_base)  new_in = empty_mem;
  3632     if (new_in != old_in) {
  3633       // Warning:  Do not combine this "if" with the previous "if"
  3634       // A memory slice might have be be rewritten even if it is semantically
  3635       // unchanged, if the base_memory value has changed.
  3636       set_req(i, new_in);
  3637       progress = this;          // Report progress
  3641   if (new_base != old_base) {
  3642     set_req(Compile::AliasIdxBot, new_base);
  3643     // Don't use set_base_memory(new_base), because we need to update du.
  3644     assert(base_memory() == new_base, "");
  3645     progress = this;
  3648   if( base_memory() == this ) {
  3649     // a self cycle indicates this memory path is dead
  3650     set_req(Compile::AliasIdxBot, empty_mem);
  3653   // Resolve external cycles by calling Ideal on a MergeMem base_memory
  3654   // Recursion must occur after the self cycle check above
  3655   if( base_memory()->is_MergeMem() ) {
  3656     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
  3657     Node *m = phase->transform(new_mbase);  // Rollup any cycles
  3658     if( m != NULL && (m->is_top() ||
  3659         m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem) ) {
  3660       // propagate rollup of dead cycle to self
  3661       set_req(Compile::AliasIdxBot, empty_mem);
  3665   if( base_memory() == empty_mem ) {
  3666     progress = this;
  3667     // Cut inputs during Parse phase only.
  3668     // During Optimize phase a dead MergeMem node will be subsumed by Top.
  3669     if( !can_reshape ) {
  3670       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  3671         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
  3676   if( !progress && base_memory()->is_Phi() && can_reshape ) {
  3677     // Check if PhiNode::Ideal's "Split phis through memory merges"
  3678     // transform should be attempted. Look for this->phi->this cycle.
  3679     uint merge_width = req();
  3680     if (merge_width > Compile::AliasIdxRaw) {
  3681       PhiNode* phi = base_memory()->as_Phi();
  3682       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
  3683         if (phi->in(i) == this) {
  3684           phase->is_IterGVN()->_worklist.push(phi);
  3685           break;
  3691   assert(progress || verify_sparse(), "please, no dups of base");
  3692   return progress;
  3695 //-------------------------set_base_memory-------------------------------------
  3696 void MergeMemNode::set_base_memory(Node *new_base) {
  3697   Node* empty_mem = empty_memory();
  3698   set_req(Compile::AliasIdxBot, new_base);
  3699   assert(memory_at(req()) == new_base, "must set default memory");
  3700   // Clear out other occurrences of new_base:
  3701   if (new_base != empty_mem) {
  3702     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  3703       if (in(i) == new_base)  set_req(i, empty_mem);
  3708 //------------------------------out_RegMask------------------------------------
  3709 const RegMask &MergeMemNode::out_RegMask() const {
  3710   return RegMask::Empty;
  3713 //------------------------------dump_spec--------------------------------------
  3714 #ifndef PRODUCT
  3715 void MergeMemNode::dump_spec(outputStream *st) const {
  3716   st->print(" {");
  3717   Node* base_mem = base_memory();
  3718   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
  3719     Node* mem = memory_at(i);
  3720     if (mem == base_mem) { st->print(" -"); continue; }
  3721     st->print( " N%d:", mem->_idx );
  3722     Compile::current()->get_adr_type(i)->dump_on(st);
  3724   st->print(" }");
  3726 #endif // !PRODUCT
  3729 #ifdef ASSERT
  3730 static bool might_be_same(Node* a, Node* b) {
  3731   if (a == b)  return true;
  3732   if (!(a->is_Phi() || b->is_Phi()))  return false;
  3733   // phis shift around during optimization
  3734   return true;  // pretty stupid...
  3737 // verify a narrow slice (either incoming or outgoing)
  3738 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
  3739   if (!VerifyAliases)       return;  // don't bother to verify unless requested
  3740   if (is_error_reported())  return;  // muzzle asserts when debugging an error
  3741   if (Node::in_dump())      return;  // muzzle asserts when printing
  3742   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
  3743   assert(n != NULL, "");
  3744   // Elide intervening MergeMem's
  3745   while (n->is_MergeMem()) {
  3746     n = n->as_MergeMem()->memory_at(alias_idx);
  3748   Compile* C = Compile::current();
  3749   const TypePtr* n_adr_type = n->adr_type();
  3750   if (n == m->empty_memory()) {
  3751     // Implicit copy of base_memory()
  3752   } else if (n_adr_type != TypePtr::BOTTOM) {
  3753     assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
  3754     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
  3755   } else {
  3756     // A few places like make_runtime_call "know" that VM calls are narrow,
  3757     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
  3758     bool expected_wide_mem = false;
  3759     if (n == m->base_memory()) {
  3760       expected_wide_mem = true;
  3761     } else if (alias_idx == Compile::AliasIdxRaw ||
  3762                n == m->memory_at(Compile::AliasIdxRaw)) {
  3763       expected_wide_mem = true;
  3764     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
  3765       // memory can "leak through" calls on channels that
  3766       // are write-once.  Allow this also.
  3767       expected_wide_mem = true;
  3769     assert(expected_wide_mem, "expected narrow slice replacement");
  3772 #else // !ASSERT
  3773 #define verify_memory_slice(m,i,n) (0)  // PRODUCT version is no-op
  3774 #endif
  3777 //-----------------------------memory_at---------------------------------------
  3778 Node* MergeMemNode::memory_at(uint alias_idx) const {
  3779   assert(alias_idx >= Compile::AliasIdxRaw ||
  3780          alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
  3781          "must avoid base_memory and AliasIdxTop");
  3783   // Otherwise, it is a narrow slice.
  3784   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
  3785   Compile *C = Compile::current();
  3786   if (is_empty_memory(n)) {
  3787     // the array is sparse; empty slots are the "top" node
  3788     n = base_memory();
  3789     assert(Node::in_dump()
  3790            || n == NULL || n->bottom_type() == Type::TOP
  3791            || n->adr_type() == TypePtr::BOTTOM
  3792            || n->adr_type() == TypeRawPtr::BOTTOM
  3793            || Compile::current()->AliasLevel() == 0,
  3794            "must be a wide memory");
  3795     // AliasLevel == 0 if we are organizing the memory states manually.
  3796     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
  3797   } else {
  3798     // make sure the stored slice is sane
  3799     #ifdef ASSERT
  3800     if (is_error_reported() || Node::in_dump()) {
  3801     } else if (might_be_same(n, base_memory())) {
  3802       // Give it a pass:  It is a mostly harmless repetition of the base.
  3803       // This can arise normally from node subsumption during optimization.
  3804     } else {
  3805       verify_memory_slice(this, alias_idx, n);
  3807     #endif
  3809   return n;
  3812 //---------------------------set_memory_at-------------------------------------
  3813 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
  3814   verify_memory_slice(this, alias_idx, n);
  3815   Node* empty_mem = empty_memory();
  3816   if (n == base_memory())  n = empty_mem;  // collapse default
  3817   uint need_req = alias_idx+1;
  3818   if (req() < need_req) {
  3819     if (n == empty_mem)  return;  // already the default, so do not grow me
  3820     // grow the sparse array
  3821     do {
  3822       add_req(empty_mem);
  3823     } while (req() < need_req);
  3825   set_req( alias_idx, n );
  3830 //--------------------------iteration_setup------------------------------------
  3831 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
  3832   if (other != NULL) {
  3833     grow_to_match(other);
  3834     // invariant:  the finite support of mm2 is within mm->req()
  3835     #ifdef ASSERT
  3836     for (uint i = req(); i < other->req(); i++) {
  3837       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
  3839     #endif
  3841   // Replace spurious copies of base_memory by top.
  3842   Node* base_mem = base_memory();
  3843   if (base_mem != NULL && !base_mem->is_top()) {
  3844     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
  3845       if (in(i) == base_mem)
  3846         set_req(i, empty_memory());
  3851 //---------------------------grow_to_match-------------------------------------
  3852 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
  3853   Node* empty_mem = empty_memory();
  3854   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
  3855   // look for the finite support of the other memory
  3856   for (uint i = other->req(); --i >= req(); ) {
  3857     if (other->in(i) != empty_mem) {
  3858       uint new_len = i+1;
  3859       while (req() < new_len)  add_req(empty_mem);
  3860       break;
  3865 //---------------------------verify_sparse-------------------------------------
  3866 #ifndef PRODUCT
  3867 bool MergeMemNode::verify_sparse() const {
  3868   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
  3869   Node* base_mem = base_memory();
  3870   // The following can happen in degenerate cases, since empty==top.
  3871   if (is_empty_memory(base_mem))  return true;
  3872   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
  3873     assert(in(i) != NULL, "sane slice");
  3874     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
  3876   return true;
  3879 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
  3880   Node* n;
  3881   n = mm->in(idx);
  3882   if (mem == n)  return true;  // might be empty_memory()
  3883   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
  3884   if (mem == n)  return true;
  3885   while (n->is_Phi() && (n = n->as_Phi()->is_copy()) != NULL) {
  3886     if (mem == n)  return true;
  3887     if (n == NULL)  break;
  3889   return false;
  3891 #endif // !PRODUCT

mercurial