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