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