1 /*
2  * Copyright (c) 1997, 2020, 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 #include "precompiled.hpp"
26 #include "classfile/javaClasses.hpp"
27 #include "compiler/compileLog.hpp"
28 #include "gc/shared/barrierSet.hpp"
29 #include "gc/shared/c2/barrierSetC2.hpp"
30 #include "memory/allocation.inline.hpp"
31 #include "memory/resourceArea.hpp"
32 #include "oops/objArrayKlass.hpp"
33 #include "opto/addnode.hpp"
34 #include "opto/arraycopynode.hpp"
35 #include "opto/cfgnode.hpp"
36 #include "opto/compile.hpp"
37 #include "opto/connode.hpp"
38 #include "opto/convertnode.hpp"
39 #include "opto/loopnode.hpp"
40 #include "opto/machnode.hpp"
41 #include "opto/matcher.hpp"
42 #include "opto/memnode.hpp"
43 #include "opto/mulnode.hpp"
44 #include "opto/narrowptrnode.hpp"
45 #include "opto/phaseX.hpp"
46 #include "opto/regmask.hpp"
47 #include "opto/rootnode.hpp"
48 #include "utilities/align.hpp"
49 #include "utilities/copy.hpp"
50 #include "utilities/macros.hpp"
51 #include "utilities/powerOfTwo.hpp"
52 #include "utilities/vmError.hpp"
53 
54 // Portions of code courtesy of Clifford Click
55 
56 // Optimization - Graph Style
57 
58 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
59 
60 //=============================================================================
size_of() const61 uint MemNode::size_of() const { return sizeof(*this); }
62 
adr_type() const63 const TypePtr *MemNode::adr_type() const {
64   Node* adr = in(Address);
65   if (adr == NULL)  return NULL; // node is dead
66   const TypePtr* cross_check = NULL;
67   DEBUG_ONLY(cross_check = _adr_type);
68   return calculate_adr_type(adr->bottom_type(), cross_check);
69 }
70 
check_if_adr_maybe_raw(Node * adr)71 bool MemNode::check_if_adr_maybe_raw(Node* adr) {
72   if (adr != NULL) {
73     if (adr->bottom_type()->base() == Type::RawPtr || adr->bottom_type()->base() == Type::AnyPtr) {
74       return true;
75     }
76   }
77   return false;
78 }
79 
80 #ifndef PRODUCT
dump_spec(outputStream * st) const81 void MemNode::dump_spec(outputStream *st) const {
82   if (in(Address) == NULL)  return; // node is dead
83 #ifndef ASSERT
84   // fake the missing field
85   const TypePtr* _adr_type = NULL;
86   if (in(Address) != NULL)
87     _adr_type = in(Address)->bottom_type()->isa_ptr();
88 #endif
89   dump_adr_type(this, _adr_type, st);
90 
91   Compile* C = Compile::current();
92   if (C->alias_type(_adr_type)->is_volatile()) {
93     st->print(" Volatile!");
94   }
95   if (_unaligned_access) {
96     st->print(" unaligned");
97   }
98   if (_mismatched_access) {
99     st->print(" mismatched");
100   }
101   if (_unsafe_access) {
102     st->print(" unsafe");
103   }
104 }
105 
dump_adr_type(const Node * mem,const TypePtr * adr_type,outputStream * st)106 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
107   st->print(" @");
108   if (adr_type == NULL) {
109     st->print("NULL");
110   } else {
111     adr_type->dump_on(st);
112     Compile* C = Compile::current();
113     Compile::AliasType* atp = NULL;
114     if (C->have_alias_type(adr_type))  atp = C->alias_type(adr_type);
115     if (atp == NULL)
116       st->print(", idx=?\?;");
117     else if (atp->index() == Compile::AliasIdxBot)
118       st->print(", idx=Bot;");
119     else if (atp->index() == Compile::AliasIdxTop)
120       st->print(", idx=Top;");
121     else if (atp->index() == Compile::AliasIdxRaw)
122       st->print(", idx=Raw;");
123     else {
124       ciField* field = atp->field();
125       if (field) {
126         st->print(", name=");
127         field->print_name_on(st);
128       }
129       st->print(", idx=%d;", atp->index());
130     }
131   }
132 }
133 
134 extern void print_alias_types();
135 
136 #endif
137 
optimize_simple_memory_chain(Node * mchain,const TypeOopPtr * t_oop,Node * load,PhaseGVN * phase)138 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) {
139   assert((t_oop != NULL), "sanity");
140   bool is_instance = t_oop->is_known_instance_field();
141   bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() &&
142                              (load != NULL) && load->is_Load() &&
143                              (phase->is_IterGVN() != NULL);
144   if (!(is_instance || is_boxed_value_load))
145     return mchain;  // don't try to optimize non-instance types
146   uint instance_id = t_oop->instance_id();
147   Node *start_mem = phase->C->start()->proj_out_or_null(TypeFunc::Memory);
148   Node *prev = NULL;
149   Node *result = mchain;
150   while (prev != result) {
151     prev = result;
152     if (result == start_mem)
153       break;  // hit one of our sentinels
154     // skip over a call which does not affect this memory slice
155     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
156       Node *proj_in = result->in(0);
157       if (proj_in->is_Allocate() && proj_in->_idx == instance_id) {
158         break;  // hit one of our sentinels
159       } else if (proj_in->is_Call()) {
160         // ArrayCopyNodes processed here as well
161         CallNode *call = proj_in->as_Call();
162         if (!call->may_modify(t_oop, phase)) { // returns false for instances
163           result = call->in(TypeFunc::Memory);
164         }
165       } else if (proj_in->is_Initialize()) {
166         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
167         // Stop if this is the initialization for the object instance which
168         // contains this memory slice, otherwise skip over it.
169         if ((alloc == NULL) || (alloc->_idx == instance_id)) {
170           break;
171         }
172         if (is_instance) {
173           result = proj_in->in(TypeFunc::Memory);
174         } else if (is_boxed_value_load) {
175           Node* klass = alloc->in(AllocateNode::KlassNode);
176           const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr();
177           if (tklass->klass_is_exact() && !tklass->klass()->equals(t_oop->klass())) {
178             result = proj_in->in(TypeFunc::Memory); // not related allocation
179           }
180         }
181       } else if (proj_in->is_MemBar()) {
182         ArrayCopyNode* ac = NULL;
183         if (ArrayCopyNode::may_modify(t_oop, proj_in->as_MemBar(), phase, ac)) {
184           break;
185         }
186         result = proj_in->in(TypeFunc::Memory);
187       } else {
188         assert(false, "unexpected projection");
189       }
190     } else if (result->is_ClearArray()) {
191       if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) {
192         // Can not bypass initialization of the instance
193         // we are looking for.
194         break;
195       }
196       // Otherwise skip it (the call updated 'result' value).
197     } else if (result->is_MergeMem()) {
198       result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, NULL, tty);
199     }
200   }
201   return result;
202 }
203 
optimize_memory_chain(Node * mchain,const TypePtr * t_adr,Node * load,PhaseGVN * phase)204 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) {
205   const TypeOopPtr* t_oop = t_adr->isa_oopptr();
206   if (t_oop == NULL)
207     return mchain;  // don't try to optimize non-oop types
208   Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase);
209   bool is_instance = t_oop->is_known_instance_field();
210   PhaseIterGVN *igvn = phase->is_IterGVN();
211   if (is_instance && igvn != NULL && result->is_Phi()) {
212     PhiNode *mphi = result->as_Phi();
213     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
214     const TypePtr *t = mphi->adr_type();
215     if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ||
216         (t->isa_oopptr() && !t->is_oopptr()->is_known_instance() &&
217          t->is_oopptr()->cast_to_exactness(true)
218            ->is_oopptr()->cast_to_ptr_type(t_oop->ptr())
219             ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop)) {
220       // clone the Phi with our address type
221       result = mphi->split_out_instance(t_adr, igvn);
222     } else {
223       assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
224     }
225   }
226   return result;
227 }
228 
step_through_mergemem(PhaseGVN * phase,MergeMemNode * mmem,const TypePtr * tp,const TypePtr * adr_check,outputStream * st)229 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem,  const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
230   uint alias_idx = phase->C->get_alias_index(tp);
231   Node *mem = mmem;
232 #ifdef ASSERT
233   {
234     // Check that current type is consistent with the alias index used during graph construction
235     assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
236     bool consistent =  adr_check == NULL || adr_check->empty() ||
237                        phase->C->must_alias(adr_check, alias_idx );
238     // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
239     if( !consistent && adr_check != NULL && !adr_check->empty() &&
240                tp->isa_aryptr() &&        tp->offset() == Type::OffsetBot &&
241         adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
242         ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
243           adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
244           adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
245       // don't assert if it is dead code.
246       consistent = true;
247     }
248     if( !consistent ) {
249       st->print("alias_idx==%d, adr_check==", alias_idx);
250       if( adr_check == NULL ) {
251         st->print("NULL");
252       } else {
253         adr_check->dump();
254       }
255       st->cr();
256       print_alias_types();
257       assert(consistent, "adr_check must match alias idx");
258     }
259   }
260 #endif
261   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
262   // means an array I have not precisely typed yet.  Do not do any
263   // alias stuff with it any time soon.
264   const TypeOopPtr *toop = tp->isa_oopptr();
265   if( tp->base() != Type::AnyPtr &&
266       !(toop &&
267         toop->klass() != NULL &&
268         toop->klass()->is_java_lang_Object() &&
269         toop->offset() == Type::OffsetBot) ) {
270     // compress paths and change unreachable cycles to TOP
271     // If not, we can update the input infinitely along a MergeMem cycle
272     // Equivalent code in PhiNode::Ideal
273     Node* m  = phase->transform(mmem);
274     // If transformed to a MergeMem, get the desired slice
275     // Otherwise the returned node represents memory for every slice
276     mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
277     // Update input if it is progress over what we have now
278   }
279   return mem;
280 }
281 
282 //--------------------------Ideal_common---------------------------------------
283 // Look for degenerate control and memory inputs.  Bypass MergeMem inputs.
284 // Unhook non-raw memories from complete (macro-expanded) initializations.
Ideal_common(PhaseGVN * phase,bool can_reshape)285 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
286   // If our control input is a dead region, kill all below the region
287   Node *ctl = in(MemNode::Control);
288   if (ctl && remove_dead_region(phase, can_reshape))
289     return this;
290   ctl = in(MemNode::Control);
291   // Don't bother trying to transform a dead node
292   if (ctl && ctl->is_top())  return NodeSentinel;
293 
294   PhaseIterGVN *igvn = phase->is_IterGVN();
295   // Wait if control on the worklist.
296   if (ctl && can_reshape && igvn != NULL) {
297     Node* bol = NULL;
298     Node* cmp = NULL;
299     if (ctl->in(0)->is_If()) {
300       assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity");
301       bol = ctl->in(0)->in(1);
302       if (bol->is_Bool())
303         cmp = ctl->in(0)->in(1)->in(1);
304     }
305     if (igvn->_worklist.member(ctl) ||
306         (bol != NULL && igvn->_worklist.member(bol)) ||
307         (cmp != NULL && igvn->_worklist.member(cmp)) ) {
308       // This control path may be dead.
309       // Delay this memory node transformation until the control is processed.
310       igvn->_worklist.push(this);
311       return NodeSentinel; // caller will return NULL
312     }
313   }
314   // Ignore if memory is dead, or self-loop
315   Node *mem = in(MemNode::Memory);
316   if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return NULL
317   assert(mem != this, "dead loop in MemNode::Ideal");
318 
319   if (can_reshape && igvn != NULL && igvn->_worklist.member(mem)) {
320     // This memory slice may be dead.
321     // Delay this mem node transformation until the memory is processed.
322     igvn->_worklist.push(this);
323     return NodeSentinel; // caller will return NULL
324   }
325 
326   Node *address = in(MemNode::Address);
327   const Type *t_adr = phase->type(address);
328   if (t_adr == Type::TOP)              return NodeSentinel; // caller will return NULL
329 
330   if (can_reshape && is_unsafe_access() && (t_adr == TypePtr::NULL_PTR)) {
331     // Unsafe off-heap access with zero address. Remove access and other control users
332     // to not confuse optimizations and add a HaltNode to fail if this is ever executed.
333     assert(ctl != NULL, "unsafe accesses should be control dependent");
334     for (DUIterator_Fast imax, i = ctl->fast_outs(imax); i < imax; i++) {
335       Node* u = ctl->fast_out(i);
336       if (u != ctl) {
337         igvn->rehash_node_delayed(u);
338         int nb = u->replace_edge(ctl, phase->C->top());
339         --i, imax -= nb;
340       }
341     }
342     Node* frame = igvn->transform(new ParmNode(phase->C->start(), TypeFunc::FramePtr));
343     Node* halt = igvn->transform(new HaltNode(ctl, frame, "unsafe off-heap access with zero address"));
344     phase->C->root()->add_req(halt);
345     return this;
346   }
347 
348   if (can_reshape && igvn != NULL &&
349       (igvn->_worklist.member(address) ||
350        (igvn->_worklist.size() > 0 && t_adr != adr_type())) ) {
351     // The address's base and type may change when the address is processed.
352     // Delay this mem node transformation until the address is processed.
353     igvn->_worklist.push(this);
354     return NodeSentinel; // caller will return NULL
355   }
356 
357   // Do NOT remove or optimize the next lines: ensure a new alias index
358   // is allocated for an oop pointer type before Escape Analysis.
359   // Note: C++ will not remove it since the call has side effect.
360   if (t_adr->isa_oopptr()) {
361     int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
362   }
363 
364   Node* base = NULL;
365   if (address->is_AddP()) {
366     base = address->in(AddPNode::Base);
367   }
368   if (base != NULL && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
369       !t_adr->isa_rawptr()) {
370     // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
371     // Skip this node optimization if its address has TOP base.
372     return NodeSentinel; // caller will return NULL
373   }
374 
375   // Avoid independent memory operations
376   Node* old_mem = mem;
377 
378   // The code which unhooks non-raw memories from complete (macro-expanded)
379   // initializations was removed. After macro-expansion all stores catched
380   // by Initialize node became raw stores and there is no information
381   // which memory slices they modify. So it is unsafe to move any memory
382   // operation above these stores. Also in most cases hooked non-raw memories
383   // were already unhooked by using information from detect_ptr_independence()
384   // and find_previous_store().
385 
386   if (mem->is_MergeMem()) {
387     MergeMemNode* mmem = mem->as_MergeMem();
388     const TypePtr *tp = t_adr->is_ptr();
389 
390     mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
391   }
392 
393   if (mem != old_mem) {
394     set_req(MemNode::Memory, mem);
395     if (can_reshape && old_mem->outcnt() == 0 && igvn != NULL) {
396       igvn->_worklist.push(old_mem);
397     }
398     if (phase->type(mem) == Type::TOP) return NodeSentinel;
399     return this;
400   }
401 
402   // let the subclass continue analyzing...
403   return NULL;
404 }
405 
406 // Helper function for proving some simple control dominations.
407 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
408 // Already assumes that 'dom' is available at 'sub', and that 'sub'
409 // is not a constant (dominated by the method's StartNode).
410 // Used by MemNode::find_previous_store to prove that the
411 // control input of a memory operation predates (dominates)
412 // an allocation it wants to look past.
all_controls_dominate(Node * dom,Node * sub)413 bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
414   if (dom == NULL || dom->is_top() || sub == NULL || sub->is_top())
415     return false; // Conservative answer for dead code
416 
417   // Check 'dom'. Skip Proj and CatchProj nodes.
418   dom = dom->find_exact_control(dom);
419   if (dom == NULL || dom->is_top())
420     return false; // Conservative answer for dead code
421 
422   if (dom == sub) {
423     // For the case when, for example, 'sub' is Initialize and the original
424     // 'dom' is Proj node of the 'sub'.
425     return false;
426   }
427 
428   if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub)
429     return true;
430 
431   // 'dom' dominates 'sub' if its control edge and control edges
432   // of all its inputs dominate or equal to sub's control edge.
433 
434   // Currently 'sub' is either Allocate, Initialize or Start nodes.
435   // Or Region for the check in LoadNode::Ideal();
436   // 'sub' should have sub->in(0) != NULL.
437   assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() ||
438          sub->is_Region() || sub->is_Call(), "expecting only these nodes");
439 
440   // Get control edge of 'sub'.
441   Node* orig_sub = sub;
442   sub = sub->find_exact_control(sub->in(0));
443   if (sub == NULL || sub->is_top())
444     return false; // Conservative answer for dead code
445 
446   assert(sub->is_CFG(), "expecting control");
447 
448   if (sub == dom)
449     return true;
450 
451   if (sub->is_Start() || sub->is_Root())
452     return false;
453 
454   {
455     // Check all control edges of 'dom'.
456 
457     ResourceMark rm;
458     Node_List nlist;
459     Unique_Node_List dom_list;
460 
461     dom_list.push(dom);
462     bool only_dominating_controls = false;
463 
464     for (uint next = 0; next < dom_list.size(); next++) {
465       Node* n = dom_list.at(next);
466       if (n == orig_sub)
467         return false; // One of dom's inputs dominated by sub.
468       if (!n->is_CFG() && n->pinned()) {
469         // Check only own control edge for pinned non-control nodes.
470         n = n->find_exact_control(n->in(0));
471         if (n == NULL || n->is_top())
472           return false; // Conservative answer for dead code
473         assert(n->is_CFG(), "expecting control");
474         dom_list.push(n);
475       } else if (n->is_Con() || n->is_Start() || n->is_Root()) {
476         only_dominating_controls = true;
477       } else if (n->is_CFG()) {
478         if (n->dominates(sub, nlist))
479           only_dominating_controls = true;
480         else
481           return false;
482       } else {
483         // First, own control edge.
484         Node* m = n->find_exact_control(n->in(0));
485         if (m != NULL) {
486           if (m->is_top())
487             return false; // Conservative answer for dead code
488           dom_list.push(m);
489         }
490         // Now, the rest of edges.
491         uint cnt = n->req();
492         for (uint i = 1; i < cnt; i++) {
493           m = n->find_exact_control(n->in(i));
494           if (m == NULL || m->is_top())
495             continue;
496           dom_list.push(m);
497         }
498       }
499     }
500     return only_dominating_controls;
501   }
502 }
503 
504 //---------------------detect_ptr_independence---------------------------------
505 // Used by MemNode::find_previous_store to prove that two base
506 // pointers are never equal.
507 // The pointers are accompanied by their associated allocations,
508 // if any, which have been previously discovered by the caller.
detect_ptr_independence(Node * p1,AllocateNode * a1,Node * p2,AllocateNode * a2,PhaseTransform * phase)509 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
510                                       Node* p2, AllocateNode* a2,
511                                       PhaseTransform* phase) {
512   // Attempt to prove that these two pointers cannot be aliased.
513   // They may both manifestly be allocations, and they should differ.
514   // Or, if they are not both allocations, they can be distinct constants.
515   // Otherwise, one is an allocation and the other a pre-existing value.
516   if (a1 == NULL && a2 == NULL) {           // neither an allocation
517     return (p1 != p2) && p1->is_Con() && p2->is_Con();
518   } else if (a1 != NULL && a2 != NULL) {    // both allocations
519     return (a1 != a2);
520   } else if (a1 != NULL) {                  // one allocation a1
521     // (Note:  p2->is_Con implies p2->in(0)->is_Root, which dominates.)
522     return all_controls_dominate(p2, a1);
523   } else { //(a2 != NULL)                   // one allocation a2
524     return all_controls_dominate(p1, a2);
525   }
526   return false;
527 }
528 
529 
530 // Find an arraycopy that must have set (can_see_stored_value=true) or
531 // could have set (can_see_stored_value=false) the value for this load
find_previous_arraycopy(PhaseTransform * phase,Node * ld_alloc,Node * & mem,bool can_see_stored_value) const532 Node* LoadNode::find_previous_arraycopy(PhaseTransform* phase, Node* ld_alloc, Node*& mem, bool can_see_stored_value) const {
533   ArrayCopyNode* ac = find_array_copy_clone(phase, ld_alloc, mem);
534   if (ac != NULL) {
535     Node* ld_addp = in(MemNode::Address);
536     Node* src = ac->in(ArrayCopyNode::Src);
537     const TypeAryPtr* ary_t = phase->type(src)->isa_aryptr();
538 
539     // This is a load from a cloned array. The corresponding arraycopy ac must
540     // have set the value for the load and we can return ac but only if the load
541     // is known to be within bounds. This is checked below.
542     if (ary_t != NULL && ld_addp->is_AddP()) {
543       Node* ld_offs = ld_addp->in(AddPNode::Offset);
544       BasicType ary_elem = ary_t->klass()->as_array_klass()->element_type()->basic_type();
545       jlong header = arrayOopDesc::base_offset_in_bytes(ary_elem);
546       jlong elemsize = type2aelembytes(ary_elem);
547 
548       const TypeX*   ld_offs_t = phase->type(ld_offs)->isa_intptr_t();
549       const TypeInt* sizetype  = ary_t->size();
550 
551       if (ld_offs_t->_lo >= header && ld_offs_t->_hi < (sizetype->_lo * elemsize + header)) {
552         // The load is known to be within bounds. It receives its value from ac.
553         return ac;
554       }
555       // The load is known to be out-of-bounds.
556     }
557     // The load could be out-of-bounds. It must not be hoisted but must remain
558     // dependent on the runtime range check. This is achieved by returning NULL.
559   } else if (mem->is_Proj() && mem->in(0) != NULL && mem->in(0)->is_ArrayCopy()) {
560     ArrayCopyNode* ac = mem->in(0)->as_ArrayCopy();
561 
562     if (ac->is_arraycopy_validated() ||
563         ac->is_copyof_validated() ||
564         ac->is_copyofrange_validated()) {
565       Node* ld_addp = in(MemNode::Address);
566       if (ld_addp->is_AddP()) {
567         Node* ld_base = ld_addp->in(AddPNode::Address);
568         Node* ld_offs = ld_addp->in(AddPNode::Offset);
569 
570         Node* dest = ac->in(ArrayCopyNode::Dest);
571 
572         if (dest == ld_base) {
573           const TypeX *ld_offs_t = phase->type(ld_offs)->isa_intptr_t();
574           if (ac->modifies(ld_offs_t->_lo, ld_offs_t->_hi, phase, can_see_stored_value)) {
575             return ac;
576           }
577           if (!can_see_stored_value) {
578             mem = ac->in(TypeFunc::Memory);
579           }
580         }
581       }
582     }
583   }
584   return NULL;
585 }
586 
find_array_copy_clone(PhaseTransform * phase,Node * ld_alloc,Node * mem) const587 ArrayCopyNode* MemNode::find_array_copy_clone(PhaseTransform* phase, Node* ld_alloc, Node* mem) const {
588   if (mem->is_Proj() && mem->in(0) != NULL && (mem->in(0)->Opcode() == Op_MemBarStoreStore ||
589                                                  mem->in(0)->Opcode() == Op_MemBarCPUOrder)) {
590     if (ld_alloc != NULL) {
591       // Check if there is an array copy for a clone
592       Node* mb = mem->in(0);
593       ArrayCopyNode* ac = NULL;
594       if (mb->in(0) != NULL && mb->in(0)->is_Proj() &&
595           mb->in(0)->in(0) != NULL && mb->in(0)->in(0)->is_ArrayCopy()) {
596         ac = mb->in(0)->in(0)->as_ArrayCopy();
597       } else {
598         // Step over GC barrier when ReduceInitialCardMarks is disabled
599         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
600         Node* control_proj_ac = bs->step_over_gc_barrier(mb->in(0));
601 
602         if (control_proj_ac->is_Proj() && control_proj_ac->in(0)->is_ArrayCopy()) {
603           ac = control_proj_ac->in(0)->as_ArrayCopy();
604         }
605       }
606 
607       if (ac != NULL && ac->is_clonebasic()) {
608         AllocateNode* alloc = AllocateNode::Ideal_allocation(ac->in(ArrayCopyNode::Dest), phase);
609         if (alloc != NULL && alloc == ld_alloc) {
610           return ac;
611         }
612       }
613     }
614   }
615   return NULL;
616 }
617 
618 // The logic for reordering loads and stores uses four steps:
619 // (a) Walk carefully past stores and initializations which we
620 //     can prove are independent of this load.
621 // (b) Observe that the next memory state makes an exact match
622 //     with self (load or store), and locate the relevant store.
623 // (c) Ensure that, if we were to wire self directly to the store,
624 //     the optimizer would fold it up somehow.
625 // (d) Do the rewiring, and return, depending on some other part of
626 //     the optimizer to fold up the load.
627 // This routine handles steps (a) and (b).  Steps (c) and (d) are
628 // specific to loads and stores, so they are handled by the callers.
629 // (Currently, only LoadNode::Ideal has steps (c), (d).  More later.)
630 //
find_previous_store(PhaseTransform * phase)631 Node* MemNode::find_previous_store(PhaseTransform* phase) {
632   Node*         ctrl   = in(MemNode::Control);
633   Node*         adr    = in(MemNode::Address);
634   intptr_t      offset = 0;
635   Node*         base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
636   AllocateNode* alloc  = AllocateNode::Ideal_allocation(base, phase);
637 
638   if (offset == Type::OffsetBot)
639     return NULL;            // cannot unalias unless there are precise offsets
640 
641   const bool adr_maybe_raw = check_if_adr_maybe_raw(adr);
642   const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
643 
644   intptr_t size_in_bytes = memory_size();
645 
646   Node* mem = in(MemNode::Memory);   // start searching here...
647 
648   int cnt = 50;             // Cycle limiter
649   for (;;) {                // While we can dance past unrelated stores...
650     if (--cnt < 0)  break;  // Caught in cycle or a complicated dance?
651 
652     Node* prev = mem;
653     if (mem->is_Store()) {
654       Node* st_adr = mem->in(MemNode::Address);
655       intptr_t st_offset = 0;
656       Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
657       if (st_base == NULL)
658         break;              // inscrutable pointer
659 
660       // For raw accesses it's not enough to prove that constant offsets don't intersect.
661       // We need the bases to be the equal in order for the offset check to make sense.
662       if ((adr_maybe_raw || check_if_adr_maybe_raw(st_adr)) && st_base != base) {
663         break;
664       }
665 
666       if (st_offset != offset && st_offset != Type::OffsetBot) {
667         const int MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize);
668         assert(mem->as_Store()->memory_size() <= MAX_STORE, "");
669         if (st_offset >= offset + size_in_bytes ||
670             st_offset <= offset - MAX_STORE ||
671             st_offset <= offset - mem->as_Store()->memory_size()) {
672           // Success:  The offsets are provably independent.
673           // (You may ask, why not just test st_offset != offset and be done?
674           // The answer is that stores of different sizes can co-exist
675           // in the same sequence of RawMem effects.  We sometimes initialize
676           // a whole 'tile' of array elements with a single jint or jlong.)
677           mem = mem->in(MemNode::Memory);
678           continue;           // (a) advance through independent store memory
679         }
680       }
681       if (st_base != base &&
682           detect_ptr_independence(base, alloc,
683                                   st_base,
684                                   AllocateNode::Ideal_allocation(st_base, phase),
685                                   phase)) {
686         // Success:  The bases are provably independent.
687         mem = mem->in(MemNode::Memory);
688         continue;           // (a) advance through independent store memory
689       }
690 
691       // (b) At this point, if the bases or offsets do not agree, we lose,
692       // since we have not managed to prove 'this' and 'mem' independent.
693       if (st_base == base && st_offset == offset) {
694         return mem;         // let caller handle steps (c), (d)
695       }
696 
697     } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
698       InitializeNode* st_init = mem->in(0)->as_Initialize();
699       AllocateNode*  st_alloc = st_init->allocation();
700       if (st_alloc == NULL)
701         break;              // something degenerated
702       bool known_identical = false;
703       bool known_independent = false;
704       if (alloc == st_alloc)
705         known_identical = true;
706       else if (alloc != NULL)
707         known_independent = true;
708       else if (all_controls_dominate(this, st_alloc))
709         known_independent = true;
710 
711       if (known_independent) {
712         // The bases are provably independent: Either they are
713         // manifestly distinct allocations, or else the control
714         // of this load dominates the store's allocation.
715         int alias_idx = phase->C->get_alias_index(adr_type());
716         if (alias_idx == Compile::AliasIdxRaw) {
717           mem = st_alloc->in(TypeFunc::Memory);
718         } else {
719           mem = st_init->memory(alias_idx);
720         }
721         continue;           // (a) advance through independent store memory
722       }
723 
724       // (b) at this point, if we are not looking at a store initializing
725       // the same allocation we are loading from, we lose.
726       if (known_identical) {
727         // From caller, can_see_stored_value will consult find_captured_store.
728         return mem;         // let caller handle steps (c), (d)
729       }
730 
731     } else if (find_previous_arraycopy(phase, alloc, mem, false) != NULL) {
732       if (prev != mem) {
733         // Found an arraycopy but it doesn't affect that load
734         continue;
735       }
736       // Found an arraycopy that may affect that load
737       return mem;
738     } else if (addr_t != NULL && addr_t->is_known_instance_field()) {
739       // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
740       if (mem->is_Proj() && mem->in(0)->is_Call()) {
741         // ArrayCopyNodes processed here as well.
742         CallNode *call = mem->in(0)->as_Call();
743         if (!call->may_modify(addr_t, phase)) {
744           mem = call->in(TypeFunc::Memory);
745           continue;         // (a) advance through independent call memory
746         }
747       } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
748         ArrayCopyNode* ac = NULL;
749         if (ArrayCopyNode::may_modify(addr_t, mem->in(0)->as_MemBar(), phase, ac)) {
750           break;
751         }
752         mem = mem->in(0)->in(TypeFunc::Memory);
753         continue;           // (a) advance through independent MemBar memory
754       } else if (mem->is_ClearArray()) {
755         if (ClearArrayNode::step_through(&mem, (uint)addr_t->instance_id(), phase)) {
756           // (the call updated 'mem' value)
757           continue;         // (a) advance through independent allocation memory
758         } else {
759           // Can not bypass initialization of the instance
760           // we are looking for.
761           return mem;
762         }
763       } else if (mem->is_MergeMem()) {
764         int alias_idx = phase->C->get_alias_index(adr_type());
765         mem = mem->as_MergeMem()->memory_at(alias_idx);
766         continue;           // (a) advance through independent MergeMem memory
767       }
768     }
769 
770     // Unless there is an explicit 'continue', we must bail out here,
771     // because 'mem' is an inscrutable memory state (e.g., a call).
772     break;
773   }
774 
775   return NULL;              // bail out
776 }
777 
778 //----------------------calculate_adr_type-------------------------------------
779 // Helper function.  Notices when the given type of address hits top or bottom.
780 // Also, asserts a cross-check of the type against the expected address type.
calculate_adr_type(const Type * t,const TypePtr * cross_check)781 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
782   if (t == Type::TOP)  return NULL; // does not touch memory any more?
783   #ifdef ASSERT
784   if (!VerifyAliases || VMError::is_error_reported() || Node::in_dump())  cross_check = NULL;
785   #endif
786   const TypePtr* tp = t->isa_ptr();
787   if (tp == NULL) {
788     assert(cross_check == NULL || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
789     return TypePtr::BOTTOM;           // touches lots of memory
790   } else {
791     #ifdef ASSERT
792     // %%%% [phh] We don't check the alias index if cross_check is
793     //            TypeRawPtr::BOTTOM.  Needs to be investigated.
794     if (cross_check != NULL &&
795         cross_check != TypePtr::BOTTOM &&
796         cross_check != TypeRawPtr::BOTTOM) {
797       // Recheck the alias index, to see if it has changed (due to a bug).
798       Compile* C = Compile::current();
799       assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
800              "must stay in the original alias category");
801       // The type of the address must be contained in the adr_type,
802       // disregarding "null"-ness.
803       // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
804       const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
805       assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(),
806              "real address must not escape from expected memory type");
807     }
808     #endif
809     return tp;
810   }
811 }
812 
813 //=============================================================================
814 // Should LoadNode::Ideal() attempt to remove control edges?
can_remove_control() const815 bool LoadNode::can_remove_control() const {
816   return true;
817 }
size_of() const818 uint LoadNode::size_of() const { return sizeof(*this); }
cmp(const Node & n) const819 bool LoadNode::cmp( const Node &n ) const
820 { return !Type::cmp( _type, ((LoadNode&)n)._type ); }
bottom_type() const821 const Type *LoadNode::bottom_type() const { return _type; }
ideal_reg() const822 uint LoadNode::ideal_reg() const {
823   return _type->ideal_reg();
824 }
825 
826 #ifndef PRODUCT
dump_spec(outputStream * st) const827 void LoadNode::dump_spec(outputStream *st) const {
828   MemNode::dump_spec(st);
829   if( !Verbose && !WizardMode ) {
830     // standard dump does this in Verbose and WizardMode
831     st->print(" #"); _type->dump_on(st);
832   }
833   if (!depends_only_on_test()) {
834     st->print(" (does not depend only on test)");
835   }
836 }
837 #endif
838 
839 #ifdef ASSERT
840 //----------------------------is_immutable_value-------------------------------
841 // Helper function to allow a raw load without control edge for some cases
is_immutable_value(Node * adr)842 bool LoadNode::is_immutable_value(Node* adr) {
843   return (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() &&
844           adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
845           (adr->in(AddPNode::Offset)->find_intptr_t_con(-1) ==
846            in_bytes(JavaThread::osthread_offset()) ||
847            adr->in(AddPNode::Offset)->find_intptr_t_con(-1) ==
848            in_bytes(JavaThread::threadObj_offset())));
849 }
850 #endif
851 
852 //----------------------------LoadNode::make-----------------------------------
853 // Polymorphic factory method:
make(PhaseGVN & gvn,Node * ctl,Node * mem,Node * adr,const TypePtr * adr_type,const Type * rt,BasicType bt,MemOrd mo,ControlDependency control_dependency,bool unaligned,bool mismatched,bool unsafe,uint8_t barrier_data)854 Node *LoadNode::make(PhaseGVN& gvn, Node *ctl, Node *mem, Node *adr, const TypePtr* adr_type, const Type *rt, BasicType bt, MemOrd mo,
855                      ControlDependency control_dependency, bool unaligned, bool mismatched, bool unsafe, uint8_t barrier_data) {
856   Compile* C = gvn.C;
857 
858   // sanity check the alias category against the created node type
859   assert(!(adr_type->isa_oopptr() &&
860            adr_type->offset() == oopDesc::klass_offset_in_bytes()),
861          "use LoadKlassNode instead");
862   assert(!(adr_type->isa_aryptr() &&
863            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
864          "use LoadRangeNode instead");
865   // Check control edge of raw loads
866   assert( ctl != NULL || C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
867           // oop will be recorded in oop map if load crosses safepoint
868           rt->isa_oopptr() || is_immutable_value(adr),
869           "raw memory operations should have control edge");
870   LoadNode* load = NULL;
871   switch (bt) {
872   case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
873   case T_BYTE:    load = new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
874   case T_INT:     load = new LoadINode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
875   case T_CHAR:    load = new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
876   case T_SHORT:   load = new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(),  mo, control_dependency); break;
877   case T_LONG:    load = new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency); break;
878   case T_FLOAT:   load = new LoadFNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency); break;
879   case T_DOUBLE:  load = new LoadDNode (ctl, mem, adr, adr_type, rt,            mo, control_dependency); break;
880   case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(),  mo, control_dependency); break;
881   case T_OBJECT:
882 #ifdef _LP64
883     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
884       load = new LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency);
885     } else
886 #endif
887     {
888       assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop");
889       load = new LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency);
890     }
891     break;
892   default:
893     ShouldNotReachHere();
894     break;
895   }
896   assert(load != NULL, "LoadNode should have been created");
897   if (unaligned) {
898     load->set_unaligned_access();
899   }
900   if (mismatched) {
901     load->set_mismatched_access();
902   }
903   if (unsafe) {
904     load->set_unsafe_access();
905   }
906   load->set_barrier_data(barrier_data);
907   if (load->Opcode() == Op_LoadN) {
908     Node* ld = gvn.transform(load);
909     return new DecodeNNode(ld, ld->bottom_type()->make_ptr());
910   }
911 
912   return load;
913 }
914 
make_atomic(Node * ctl,Node * mem,Node * adr,const TypePtr * adr_type,const Type * rt,MemOrd mo,ControlDependency control_dependency,bool unaligned,bool mismatched,bool unsafe,uint8_t barrier_data)915 LoadLNode* LoadLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo,
916                                   ControlDependency control_dependency, bool unaligned, bool mismatched, bool unsafe, uint8_t barrier_data) {
917   bool require_atomic = true;
918   LoadLNode* load = new LoadLNode(ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic);
919   if (unaligned) {
920     load->set_unaligned_access();
921   }
922   if (mismatched) {
923     load->set_mismatched_access();
924   }
925   if (unsafe) {
926     load->set_unsafe_access();
927   }
928   load->set_barrier_data(barrier_data);
929   return load;
930 }
931 
make_atomic(Node * ctl,Node * mem,Node * adr,const TypePtr * adr_type,const Type * rt,MemOrd mo,ControlDependency control_dependency,bool unaligned,bool mismatched,bool unsafe,uint8_t barrier_data)932 LoadDNode* LoadDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo,
933                                   ControlDependency control_dependency, bool unaligned, bool mismatched, bool unsafe, uint8_t barrier_data) {
934   bool require_atomic = true;
935   LoadDNode* load = new LoadDNode(ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic);
936   if (unaligned) {
937     load->set_unaligned_access();
938   }
939   if (mismatched) {
940     load->set_mismatched_access();
941   }
942   if (unsafe) {
943     load->set_unsafe_access();
944   }
945   load->set_barrier_data(barrier_data);
946   return load;
947 }
948 
949 
950 
951 //------------------------------hash-------------------------------------------
hash() const952 uint LoadNode::hash() const {
953   // unroll addition of interesting fields
954   return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
955 }
956 
skip_through_membars(Compile::AliasType * atp,const TypeInstPtr * tp,bool eliminate_boxing)957 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) {
958   if ((atp != NULL) && (atp->index() >= Compile::AliasIdxRaw)) {
959     bool non_volatile = (atp->field() != NULL) && !atp->field()->is_volatile();
960     bool is_stable_ary = FoldStableValues &&
961                          (tp != NULL) && (tp->isa_aryptr() != NULL) &&
962                          tp->isa_aryptr()->is_stable();
963 
964     return (eliminate_boxing && non_volatile) || is_stable_ary;
965   }
966 
967   return false;
968 }
969 
970 // Is the value loaded previously stored by an arraycopy? If so return
971 // a load node that reads from the source array so we may be able to
972 // optimize out the ArrayCopy node later.
can_see_arraycopy_value(Node * st,PhaseGVN * phase) const973 Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseGVN* phase) const {
974   Node* ld_adr = in(MemNode::Address);
975   intptr_t ld_off = 0;
976   AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
977   Node* ac = find_previous_arraycopy(phase, ld_alloc, st, true);
978   if (ac != NULL) {
979     assert(ac->is_ArrayCopy(), "what kind of node can this be?");
980 
981     Node* mem = ac->in(TypeFunc::Memory);
982     Node* ctl = ac->in(0);
983     Node* src = ac->in(ArrayCopyNode::Src);
984 
985     if (!ac->as_ArrayCopy()->is_clonebasic() && !phase->type(src)->isa_aryptr()) {
986       return NULL;
987     }
988 
989     LoadNode* ld = clone()->as_Load();
990     Node* addp = in(MemNode::Address)->clone();
991     if (ac->as_ArrayCopy()->is_clonebasic()) {
992       assert(ld_alloc != NULL, "need an alloc");
993       assert(addp->is_AddP(), "address must be addp");
994       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
995       assert(bs->step_over_gc_barrier(addp->in(AddPNode::Base)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern");
996       assert(bs->step_over_gc_barrier(addp->in(AddPNode::Address)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern");
997       addp->set_req(AddPNode::Base, src);
998       addp->set_req(AddPNode::Address, src);
999     } else {
1000       assert(ac->as_ArrayCopy()->is_arraycopy_validated() ||
1001              ac->as_ArrayCopy()->is_copyof_validated() ||
1002              ac->as_ArrayCopy()->is_copyofrange_validated(), "only supported cases");
1003       assert(addp->in(AddPNode::Base) == addp->in(AddPNode::Address), "should be");
1004       addp->set_req(AddPNode::Base, src);
1005       addp->set_req(AddPNode::Address, src);
1006 
1007       const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr();
1008       BasicType ary_elem  = ary_t->klass()->as_array_klass()->element_type()->basic_type();
1009       uint header = arrayOopDesc::base_offset_in_bytes(ary_elem);
1010       uint shift  = exact_log2(type2aelembytes(ary_elem));
1011 
1012       Node* diff = phase->transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
1013 #ifdef _LP64
1014       diff = phase->transform(new ConvI2LNode(diff));
1015 #endif
1016       diff = phase->transform(new LShiftXNode(diff, phase->intcon(shift)));
1017 
1018       Node* offset = phase->transform(new AddXNode(addp->in(AddPNode::Offset), diff));
1019       addp->set_req(AddPNode::Offset, offset);
1020     }
1021     addp = phase->transform(addp);
1022 #ifdef ASSERT
1023     const TypePtr* adr_type = phase->type(addp)->is_ptr();
1024     ld->_adr_type = adr_type;
1025 #endif
1026     ld->set_req(MemNode::Address, addp);
1027     ld->set_req(0, ctl);
1028     ld->set_req(MemNode::Memory, mem);
1029     // load depends on the tests that validate the arraycopy
1030     ld->_control_dependency = UnknownControl;
1031     return ld;
1032   }
1033   return NULL;
1034 }
1035 
1036 
1037 //---------------------------can_see_stored_value------------------------------
1038 // This routine exists to make sure this set of tests is done the same
1039 // everywhere.  We need to make a coordinated change: first LoadNode::Ideal
1040 // will change the graph shape in a way which makes memory alive twice at the
1041 // same time (uses the Oracle model of aliasing), then some
1042 // LoadXNode::Identity will fold things back to the equivalence-class model
1043 // of aliasing.
can_see_stored_value(Node * st,PhaseTransform * phase) const1044 Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
1045   Node* ld_adr = in(MemNode::Address);
1046   intptr_t ld_off = 0;
1047   Node* ld_base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ld_off);
1048   Node* ld_alloc = AllocateNode::Ideal_allocation(ld_base, phase);
1049   const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
1050   Compile::AliasType* atp = (tp != NULL) ? phase->C->alias_type(tp) : NULL;
1051   // This is more general than load from boxing objects.
1052   if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) {
1053     uint alias_idx = atp->index();
1054     bool final = !atp->is_rewritable();
1055     Node* result = NULL;
1056     Node* current = st;
1057     // Skip through chains of MemBarNodes checking the MergeMems for
1058     // new states for the slice of this load.  Stop once any other
1059     // kind of node is encountered.  Loads from final memory can skip
1060     // through any kind of MemBar but normal loads shouldn't skip
1061     // through MemBarAcquire since the could allow them to move out of
1062     // a synchronized region.
1063     while (current->is_Proj()) {
1064       int opc = current->in(0)->Opcode();
1065       if ((final && (opc == Op_MemBarAcquire ||
1066                      opc == Op_MemBarAcquireLock ||
1067                      opc == Op_LoadFence)) ||
1068           opc == Op_MemBarRelease ||
1069           opc == Op_StoreFence ||
1070           opc == Op_MemBarReleaseLock ||
1071           opc == Op_MemBarStoreStore ||
1072           opc == Op_MemBarCPUOrder) {
1073         Node* mem = current->in(0)->in(TypeFunc::Memory);
1074         if (mem->is_MergeMem()) {
1075           MergeMemNode* merge = mem->as_MergeMem();
1076           Node* new_st = merge->memory_at(alias_idx);
1077           if (new_st == merge->base_memory()) {
1078             // Keep searching
1079             current = new_st;
1080             continue;
1081           }
1082           // Save the new memory state for the slice and fall through
1083           // to exit.
1084           result = new_st;
1085         }
1086       }
1087       break;
1088     }
1089     if (result != NULL) {
1090       st = result;
1091     }
1092   }
1093 
1094   // Loop around twice in the case Load -> Initialize -> Store.
1095   // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
1096   for (int trip = 0; trip <= 1; trip++) {
1097 
1098     if (st->is_Store()) {
1099       Node* st_adr = st->in(MemNode::Address);
1100       if (st_adr != ld_adr) {
1101         // Try harder before giving up. Unify base pointers with casts (e.g., raw/non-raw pointers).
1102         intptr_t st_off = 0;
1103         Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_off);
1104         if (ld_base == NULL)                                   return NULL;
1105         if (st_base == NULL)                                   return NULL;
1106         if (!ld_base->eqv_uncast(st_base, /*keep_deps=*/true)) return NULL;
1107         if (ld_off != st_off)                                  return NULL;
1108         if (ld_off == Type::OffsetBot)                         return NULL;
1109         // Same base, same offset.
1110         // Possible improvement for arrays: check index value instead of absolute offset.
1111 
1112         // At this point we have proven something like this setup:
1113         //   B = << base >>
1114         //   L =  LoadQ(AddP(Check/CastPP(B), #Off))
1115         //   S = StoreQ(AddP(             B , #Off), V)
1116         // (Actually, we haven't yet proven the Q's are the same.)
1117         // In other words, we are loading from a casted version of
1118         // the same pointer-and-offset that we stored to.
1119         // Casted version may carry a dependency and it is respected.
1120         // Thus, we are able to replace L by V.
1121       }
1122       // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
1123       if (store_Opcode() != st->Opcode())
1124         return NULL;
1125       return st->in(MemNode::ValueIn);
1126     }
1127 
1128     // A load from a freshly-created object always returns zero.
1129     // (This can happen after LoadNode::Ideal resets the load's memory input
1130     // to find_captured_store, which returned InitializeNode::zero_memory.)
1131     if (st->is_Proj() && st->in(0)->is_Allocate() &&
1132         (st->in(0) == ld_alloc) &&
1133         (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) {
1134       // return a zero value for the load's basic type
1135       // (This is one of the few places where a generic PhaseTransform
1136       // can create new nodes.  Think of it as lazily manifesting
1137       // virtually pre-existing constants.)
1138       if (memory_type() != T_VOID) {
1139         if (ReduceBulkZeroing || find_array_copy_clone(phase, ld_alloc, in(MemNode::Memory)) == NULL) {
1140           // If ReduceBulkZeroing is disabled, we need to check if the allocation does not belong to an
1141           // ArrayCopyNode clone. If it does, then we cannot assume zero since the initialization is done
1142           // by the ArrayCopyNode.
1143           return phase->zerocon(memory_type());
1144         }
1145       } else {
1146         // TODO: materialize all-zero vector constant
1147         assert(!isa_Load() || as_Load()->type()->isa_vect(), "");
1148       }
1149     }
1150 
1151     // A load from an initialization barrier can match a captured store.
1152     if (st->is_Proj() && st->in(0)->is_Initialize()) {
1153       InitializeNode* init = st->in(0)->as_Initialize();
1154       AllocateNode* alloc = init->allocation();
1155       if ((alloc != NULL) && (alloc == ld_alloc)) {
1156         // examine a captured store value
1157         st = init->find_captured_store(ld_off, memory_size(), phase);
1158         if (st != NULL) {
1159           continue;             // take one more trip around
1160         }
1161       }
1162     }
1163 
1164     // Load boxed value from result of valueOf() call is input parameter.
1165     if (this->is_Load() && ld_adr->is_AddP() &&
1166         (tp != NULL) && tp->is_ptr_to_boxed_value()) {
1167       intptr_t ignore = 0;
1168       Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore);
1169       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1170       base = bs->step_over_gc_barrier(base);
1171       if (base != NULL && base->is_Proj() &&
1172           base->as_Proj()->_con == TypeFunc::Parms &&
1173           base->in(0)->is_CallStaticJava() &&
1174           base->in(0)->as_CallStaticJava()->is_boxing_method()) {
1175         return base->in(0)->in(TypeFunc::Parms);
1176       }
1177     }
1178 
1179     break;
1180   }
1181 
1182   return NULL;
1183 }
1184 
1185 //----------------------is_instance_field_load_with_local_phi------------------
is_instance_field_load_with_local_phi(Node * ctrl)1186 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
1187   if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl &&
1188       in(Address)->is_AddP() ) {
1189     const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr();
1190     // Only instances and boxed values.
1191     if( t_oop != NULL &&
1192         (t_oop->is_ptr_to_boxed_value() ||
1193          t_oop->is_known_instance_field()) &&
1194         t_oop->offset() != Type::OffsetBot &&
1195         t_oop->offset() != Type::OffsetTop) {
1196       return true;
1197     }
1198   }
1199   return false;
1200 }
1201 
1202 //------------------------------Identity---------------------------------------
1203 // Loads are identity if previous store is to same address
Identity(PhaseGVN * phase)1204 Node* LoadNode::Identity(PhaseGVN* phase) {
1205   // If the previous store-maker is the right kind of Store, and the store is
1206   // to the same address, then we are equal to the value stored.
1207   Node* mem = in(Memory);
1208   Node* value = can_see_stored_value(mem, phase);
1209   if( value ) {
1210     // byte, short & char stores truncate naturally.
1211     // A load has to load the truncated value which requires
1212     // some sort of masking operation and that requires an
1213     // Ideal call instead of an Identity call.
1214     if (memory_size() < BytesPerInt) {
1215       // If the input to the store does not fit with the load's result type,
1216       // it must be truncated via an Ideal call.
1217       if (!phase->type(value)->higher_equal(phase->type(this)))
1218         return this;
1219     }
1220     // (This works even when value is a Con, but LoadNode::Value
1221     // usually runs first, producing the singleton type of the Con.)
1222     return value;
1223   }
1224 
1225   // Search for an existing data phi which was generated before for the same
1226   // instance's field to avoid infinite generation of phis in a loop.
1227   Node *region = mem->in(0);
1228   if (is_instance_field_load_with_local_phi(region)) {
1229     const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr();
1230     int this_index  = phase->C->get_alias_index(addr_t);
1231     int this_offset = addr_t->offset();
1232     int this_iid    = addr_t->instance_id();
1233     if (!addr_t->is_known_instance() &&
1234          addr_t->is_ptr_to_boxed_value()) {
1235       // Use _idx of address base (could be Phi node) for boxed values.
1236       intptr_t   ignore = 0;
1237       Node*      base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1238       if (base == NULL) {
1239         return this;
1240       }
1241       this_iid = base->_idx;
1242     }
1243     const Type* this_type = bottom_type();
1244     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1245       Node* phi = region->fast_out(i);
1246       if (phi->is_Phi() && phi != mem &&
1247           phi->as_Phi()->is_same_inst_field(this_type, (int)mem->_idx, this_iid, this_index, this_offset)) {
1248         return phi;
1249       }
1250     }
1251   }
1252 
1253   return this;
1254 }
1255 
1256 // Construct an equivalent unsigned load.
convert_to_unsigned_load(PhaseGVN & gvn)1257 Node* LoadNode::convert_to_unsigned_load(PhaseGVN& gvn) {
1258   BasicType bt = T_ILLEGAL;
1259   const Type* rt = NULL;
1260   switch (Opcode()) {
1261     case Op_LoadUB: return this;
1262     case Op_LoadUS: return this;
1263     case Op_LoadB: bt = T_BOOLEAN; rt = TypeInt::UBYTE; break;
1264     case Op_LoadS: bt = T_CHAR;    rt = TypeInt::CHAR;  break;
1265     default:
1266       assert(false, "no unsigned variant: %s", Name());
1267       return NULL;
1268   }
1269   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1270                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1271                         is_unaligned_access(), is_mismatched_access());
1272 }
1273 
1274 // Construct an equivalent signed load.
convert_to_signed_load(PhaseGVN & gvn)1275 Node* LoadNode::convert_to_signed_load(PhaseGVN& gvn) {
1276   BasicType bt = T_ILLEGAL;
1277   const Type* rt = NULL;
1278   switch (Opcode()) {
1279     case Op_LoadUB: bt = T_BYTE;  rt = TypeInt::BYTE;  break;
1280     case Op_LoadUS: bt = T_SHORT; rt = TypeInt::SHORT; break;
1281     case Op_LoadB: // fall through
1282     case Op_LoadS: // fall through
1283     case Op_LoadI: // fall through
1284     case Op_LoadL: return this;
1285     default:
1286       assert(false, "no signed variant: %s", Name());
1287       return NULL;
1288   }
1289   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1290                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1291                         is_unaligned_access(), is_mismatched_access());
1292 }
1293 
has_reinterpret_variant(const Type * rt)1294 bool LoadNode::has_reinterpret_variant(const Type* rt) {
1295   BasicType bt = rt->basic_type();
1296   switch (Opcode()) {
1297     case Op_LoadI: return (bt == T_FLOAT);
1298     case Op_LoadL: return (bt == T_DOUBLE);
1299     case Op_LoadF: return (bt == T_INT);
1300     case Op_LoadD: return (bt == T_LONG);
1301 
1302     default: return false;
1303   }
1304 }
1305 
convert_to_reinterpret_load(PhaseGVN & gvn,const Type * rt)1306 Node* LoadNode::convert_to_reinterpret_load(PhaseGVN& gvn, const Type* rt) {
1307   BasicType bt = rt->basic_type();
1308   assert(has_reinterpret_variant(rt), "no reinterpret variant: %s %s", Name(), type2name(bt));
1309   bool is_mismatched = is_mismatched_access();
1310   const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr();
1311   if (raw_type == NULL) {
1312     is_mismatched = true; // conservatively match all non-raw accesses as mismatched
1313   }
1314   return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1315                         raw_adr_type(), rt, bt, _mo, _control_dependency,
1316                         is_unaligned_access(), is_mismatched);
1317 }
1318 
has_reinterpret_variant(const Type * vt)1319 bool StoreNode::has_reinterpret_variant(const Type* vt) {
1320   BasicType bt = vt->basic_type();
1321   switch (Opcode()) {
1322     case Op_StoreI: return (bt == T_FLOAT);
1323     case Op_StoreL: return (bt == T_DOUBLE);
1324     case Op_StoreF: return (bt == T_INT);
1325     case Op_StoreD: return (bt == T_LONG);
1326 
1327     default: return false;
1328   }
1329 }
1330 
convert_to_reinterpret_store(PhaseGVN & gvn,Node * val,const Type * vt)1331 Node* StoreNode::convert_to_reinterpret_store(PhaseGVN& gvn, Node* val, const Type* vt) {
1332   BasicType bt = vt->basic_type();
1333   assert(has_reinterpret_variant(vt), "no reinterpret variant: %s %s", Name(), type2name(bt));
1334   StoreNode* st = StoreNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), raw_adr_type(), val, bt, _mo);
1335 
1336   bool is_mismatched = is_mismatched_access();
1337   const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr();
1338   if (raw_type == NULL) {
1339     is_mismatched = true; // conservatively match all non-raw accesses as mismatched
1340   }
1341   if (is_mismatched) {
1342     st->set_mismatched_access();
1343   }
1344   return st;
1345 }
1346 
1347 // We're loading from an object which has autobox behaviour.
1348 // If this object is result of a valueOf call we'll have a phi
1349 // merging a newly allocated object and a load from the cache.
1350 // We want to replace this load with the original incoming
1351 // argument to the valueOf call.
eliminate_autobox(PhaseGVN * phase)1352 Node* LoadNode::eliminate_autobox(PhaseGVN* phase) {
1353   assert(phase->C->eliminate_boxing(), "sanity");
1354   intptr_t ignore = 0;
1355   Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1356   if ((base == NULL) || base->is_Phi()) {
1357     // Push the loads from the phi that comes from valueOf up
1358     // through it to allow elimination of the loads and the recovery
1359     // of the original value. It is done in split_through_phi().
1360     return NULL;
1361   } else if (base->is_Load() ||
1362              (base->is_DecodeN() && base->in(1)->is_Load())) {
1363     // Eliminate the load of boxed value for integer types from the cache
1364     // array by deriving the value from the index into the array.
1365     // Capture the offset of the load and then reverse the computation.
1366 
1367     // Get LoadN node which loads a boxing object from 'cache' array.
1368     if (base->is_DecodeN()) {
1369       base = base->in(1);
1370     }
1371     if (!base->in(Address)->is_AddP()) {
1372       return NULL; // Complex address
1373     }
1374     AddPNode* address = base->in(Address)->as_AddP();
1375     Node* cache_base = address->in(AddPNode::Base);
1376     if ((cache_base != NULL) && cache_base->is_DecodeN()) {
1377       // Get ConP node which is static 'cache' field.
1378       cache_base = cache_base->in(1);
1379     }
1380     if ((cache_base != NULL) && cache_base->is_Con()) {
1381       const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr();
1382       if ((base_type != NULL) && base_type->is_autobox_cache()) {
1383         Node* elements[4];
1384         int shift = exact_log2(type2aelembytes(T_OBJECT));
1385         int count = address->unpack_offsets(elements, ARRAY_SIZE(elements));
1386         if (count > 0 && elements[0]->is_Con() &&
1387             (count == 1 ||
1388              (count == 2 && elements[1]->Opcode() == Op_LShiftX &&
1389                             elements[1]->in(2) == phase->intcon(shift)))) {
1390           ciObjArray* array = base_type->const_oop()->as_obj_array();
1391           // Fetch the box object cache[0] at the base of the array and get its value
1392           ciInstance* box = array->obj_at(0)->as_instance();
1393           ciInstanceKlass* ik = box->klass()->as_instance_klass();
1394           assert(ik->is_box_klass(), "sanity");
1395           assert(ik->nof_nonstatic_fields() == 1, "change following code");
1396           if (ik->nof_nonstatic_fields() == 1) {
1397             // This should be true nonstatic_field_at requires calling
1398             // nof_nonstatic_fields so check it anyway
1399             ciConstant c = box->field_value(ik->nonstatic_field_at(0));
1400             BasicType bt = c.basic_type();
1401             // Only integer types have boxing cache.
1402             assert(bt == T_BOOLEAN || bt == T_CHAR  ||
1403                    bt == T_BYTE    || bt == T_SHORT ||
1404                    bt == T_INT     || bt == T_LONG, "wrong type = %s", type2name(bt));
1405             jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int();
1406             if (cache_low != (int)cache_low) {
1407               return NULL; // should not happen since cache is array indexed by value
1408             }
1409             jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift);
1410             if (offset != (int)offset) {
1411               return NULL; // should not happen since cache is array indexed by value
1412             }
1413            // Add up all the offsets making of the address of the load
1414             Node* result = elements[0];
1415             for (int i = 1; i < count; i++) {
1416               result = phase->transform(new AddXNode(result, elements[i]));
1417             }
1418             // Remove the constant offset from the address and then
1419             result = phase->transform(new AddXNode(result, phase->MakeConX(-(int)offset)));
1420             // remove the scaling of the offset to recover the original index.
1421             if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) {
1422               // Peel the shift off directly but wrap it in a dummy node
1423               // since Ideal can't return existing nodes
1424               result = new RShiftXNode(result->in(1), phase->intcon(0));
1425             } else if (result->is_Add() && result->in(2)->is_Con() &&
1426                        result->in(1)->Opcode() == Op_LShiftX &&
1427                        result->in(1)->in(2) == phase->intcon(shift)) {
1428               // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z)
1429               // but for boxing cache access we know that X<<Z will not overflow
1430               // (there is range check) so we do this optimizatrion by hand here.
1431               Node* add_con = new RShiftXNode(result->in(2), phase->intcon(shift));
1432               result = new AddXNode(result->in(1)->in(1), phase->transform(add_con));
1433             } else {
1434               result = new RShiftXNode(result, phase->intcon(shift));
1435             }
1436 #ifdef _LP64
1437             if (bt != T_LONG) {
1438               result = new ConvL2INode(phase->transform(result));
1439             }
1440 #else
1441             if (bt == T_LONG) {
1442               result = new ConvI2LNode(phase->transform(result));
1443             }
1444 #endif
1445             // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
1446             // Need to preserve unboxing load type if it is unsigned.
1447             switch(this->Opcode()) {
1448               case Op_LoadUB:
1449                 result = new AndINode(phase->transform(result), phase->intcon(0xFF));
1450                 break;
1451               case Op_LoadUS:
1452                 result = new AndINode(phase->transform(result), phase->intcon(0xFFFF));
1453                 break;
1454             }
1455             return result;
1456           }
1457         }
1458       }
1459     }
1460   }
1461   return NULL;
1462 }
1463 
stable_phi(PhiNode * phi,PhaseGVN * phase)1464 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) {
1465   Node* region = phi->in(0);
1466   if (region == NULL) {
1467     return false; // Wait stable graph
1468   }
1469   uint cnt = phi->req();
1470   for (uint i = 1; i < cnt; i++) {
1471     Node* rc = region->in(i);
1472     if (rc == NULL || phase->type(rc) == Type::TOP)
1473       return false; // Wait stable graph
1474     Node* in = phi->in(i);
1475     if (in == NULL || phase->type(in) == Type::TOP)
1476       return false; // Wait stable graph
1477   }
1478   return true;
1479 }
1480 //------------------------------split_through_phi------------------------------
1481 // Split instance or boxed field load through Phi.
split_through_phi(PhaseGVN * phase)1482 Node *LoadNode::split_through_phi(PhaseGVN *phase) {
1483   Node* mem     = in(Memory);
1484   Node* address = in(Address);
1485   const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr();
1486 
1487   assert((t_oop != NULL) &&
1488          (t_oop->is_known_instance_field() ||
1489           t_oop->is_ptr_to_boxed_value()), "invalide conditions");
1490 
1491   Compile* C = phase->C;
1492   intptr_t ignore = 0;
1493   Node*    base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1494   bool base_is_phi = (base != NULL) && base->is_Phi();
1495   bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() &&
1496                            (base != NULL) && (base == address->in(AddPNode::Base)) &&
1497                            phase->type(base)->higher_equal(TypePtr::NOTNULL);
1498 
1499   if (!((mem->is_Phi() || base_is_phi) &&
1500         (load_boxed_values || t_oop->is_known_instance_field()))) {
1501     return NULL; // memory is not Phi
1502   }
1503 
1504   if (mem->is_Phi()) {
1505     if (!stable_phi(mem->as_Phi(), phase)) {
1506       return NULL; // Wait stable graph
1507     }
1508     uint cnt = mem->req();
1509     // Check for loop invariant memory.
1510     if (cnt == 3) {
1511       for (uint i = 1; i < cnt; i++) {
1512         Node* in = mem->in(i);
1513         Node*  m = optimize_memory_chain(in, t_oop, this, phase);
1514         if (m == mem) {
1515           if (i == 1) {
1516             // if the first edge was a loop, check second edge too.
1517             // If both are replaceable - we are in an infinite loop
1518             Node *n = optimize_memory_chain(mem->in(2), t_oop, this, phase);
1519             if (n == mem) {
1520               break;
1521             }
1522           }
1523           set_req(Memory, mem->in(cnt - i));
1524           return this; // made change
1525         }
1526       }
1527     }
1528   }
1529   if (base_is_phi) {
1530     if (!stable_phi(base->as_Phi(), phase)) {
1531       return NULL; // Wait stable graph
1532     }
1533     uint cnt = base->req();
1534     // Check for loop invariant memory.
1535     if (cnt == 3) {
1536       for (uint i = 1; i < cnt; i++) {
1537         if (base->in(i) == base) {
1538           return NULL; // Wait stable graph
1539         }
1540       }
1541     }
1542   }
1543 
1544   // Split through Phi (see original code in loopopts.cpp).
1545   assert(C->have_alias_type(t_oop), "instance should have alias type");
1546 
1547   // Do nothing here if Identity will find a value
1548   // (to avoid infinite chain of value phis generation).
1549   if (this != Identity(phase)) {
1550     return NULL;
1551   }
1552 
1553   // Select Region to split through.
1554   Node* region;
1555   if (!base_is_phi) {
1556     assert(mem->is_Phi(), "sanity");
1557     region = mem->in(0);
1558     // Skip if the region dominates some control edge of the address.
1559     if (!MemNode::all_controls_dominate(address, region))
1560       return NULL;
1561   } else if (!mem->is_Phi()) {
1562     assert(base_is_phi, "sanity");
1563     region = base->in(0);
1564     // Skip if the region dominates some control edge of the memory.
1565     if (!MemNode::all_controls_dominate(mem, region))
1566       return NULL;
1567   } else if (base->in(0) != mem->in(0)) {
1568     assert(base_is_phi && mem->is_Phi(), "sanity");
1569     if (MemNode::all_controls_dominate(mem, base->in(0))) {
1570       region = base->in(0);
1571     } else if (MemNode::all_controls_dominate(address, mem->in(0))) {
1572       region = mem->in(0);
1573     } else {
1574       return NULL; // complex graph
1575     }
1576   } else {
1577     assert(base->in(0) == mem->in(0), "sanity");
1578     region = mem->in(0);
1579   }
1580 
1581   const Type* this_type = this->bottom_type();
1582   int this_index  = C->get_alias_index(t_oop);
1583   int this_offset = t_oop->offset();
1584   int this_iid    = t_oop->instance_id();
1585   if (!t_oop->is_known_instance() && load_boxed_values) {
1586     // Use _idx of address base for boxed values.
1587     this_iid = base->_idx;
1588   }
1589   PhaseIterGVN* igvn = phase->is_IterGVN();
1590   Node* phi = new PhiNode(region, this_type, NULL, mem->_idx, this_iid, this_index, this_offset);
1591   for (uint i = 1; i < region->req(); i++) {
1592     Node* x;
1593     Node* the_clone = NULL;
1594     Node* in = region->in(i);
1595     if (region->is_CountedLoop() && region->as_Loop()->is_strip_mined() && i == LoopNode::EntryControl &&
1596         in != NULL && in->is_OuterStripMinedLoop()) {
1597       // No node should go in the outer strip mined loop
1598       in = in->in(LoopNode::EntryControl);
1599     }
1600     if (in == NULL || in == C->top()) {
1601       x = C->top();      // Dead path?  Use a dead data op
1602     } else {
1603       x = this->clone();        // Else clone up the data op
1604       the_clone = x;            // Remember for possible deletion.
1605       // Alter data node to use pre-phi inputs
1606       if (this->in(0) == region) {
1607         x->set_req(0, in);
1608       } else {
1609         x->set_req(0, NULL);
1610       }
1611       if (mem->is_Phi() && (mem->in(0) == region)) {
1612         x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone.
1613       }
1614       if (address->is_Phi() && address->in(0) == region) {
1615         x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone
1616       }
1617       if (base_is_phi && (base->in(0) == region)) {
1618         Node* base_x = base->in(i); // Clone address for loads from boxed objects.
1619         Node* adr_x = phase->transform(new AddPNode(base_x,base_x,address->in(AddPNode::Offset)));
1620         x->set_req(Address, adr_x);
1621       }
1622     }
1623     // Check for a 'win' on some paths
1624     const Type *t = x->Value(igvn);
1625 
1626     bool singleton = t->singleton();
1627 
1628     // See comments in PhaseIdealLoop::split_thru_phi().
1629     if (singleton && t == Type::TOP) {
1630       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
1631     }
1632 
1633     if (singleton) {
1634       x = igvn->makecon(t);
1635     } else {
1636       // We now call Identity to try to simplify the cloned node.
1637       // Note that some Identity methods call phase->type(this).
1638       // Make sure that the type array is big enough for
1639       // our new node, even though we may throw the node away.
1640       // (This tweaking with igvn only works because x is a new node.)
1641       igvn->set_type(x, t);
1642       // If x is a TypeNode, capture any more-precise type permanently into Node
1643       // otherwise it will be not updated during igvn->transform since
1644       // igvn->type(x) is set to x->Value() already.
1645       x->raise_bottom_type(t);
1646       Node* y = x->Identity(igvn);
1647       if (y != x) {
1648         x = y;
1649       } else {
1650         y = igvn->hash_find_insert(x);
1651         if (y) {
1652           x = y;
1653         } else {
1654           // Else x is a new node we are keeping
1655           // We do not need register_new_node_with_optimizer
1656           // because set_type has already been called.
1657           igvn->_worklist.push(x);
1658         }
1659       }
1660     }
1661     if (x != the_clone && the_clone != NULL) {
1662       igvn->remove_dead_node(the_clone);
1663     }
1664     phi->set_req(i, x);
1665   }
1666   // Record Phi
1667   igvn->register_new_node_with_optimizer(phi);
1668   return phi;
1669 }
1670 
is_new_object_mark_load(PhaseGVN * phase) const1671 AllocateNode* LoadNode::is_new_object_mark_load(PhaseGVN *phase) const {
1672   if (Opcode() == Op_LoadX) {
1673     Node* address = in(MemNode::Address);
1674     AllocateNode* alloc = AllocateNode::Ideal_allocation(address, phase);
1675     Node* mem = in(MemNode::Memory);
1676     if (alloc != NULL && mem->is_Proj() &&
1677         mem->in(0) != NULL &&
1678         mem->in(0) == alloc->initialization() &&
1679         alloc->initialization()->proj_out_or_null(0) != NULL) {
1680       return alloc;
1681     }
1682   }
1683   return NULL;
1684 }
1685 
1686 
1687 //------------------------------Ideal------------------------------------------
1688 // If the load is from Field memory and the pointer is non-null, it might be possible to
1689 // zero out the control input.
1690 // If the offset is constant and the base is an object allocation,
1691 // try to hook me up to the exact initializing store.
Ideal(PhaseGVN * phase,bool can_reshape)1692 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1693   Node* p = MemNode::Ideal_common(phase, can_reshape);
1694   if (p)  return (p == NodeSentinel) ? NULL : p;
1695 
1696   Node* ctrl    = in(MemNode::Control);
1697   Node* address = in(MemNode::Address);
1698   bool progress = false;
1699 
1700   bool addr_mark = ((phase->type(address)->isa_oopptr() || phase->type(address)->isa_narrowoop()) &&
1701          phase->type(address)->is_ptr()->offset() == oopDesc::mark_offset_in_bytes());
1702 
1703   // Skip up past a SafePoint control.  Cannot do this for Stores because
1704   // pointer stores & cardmarks must stay on the same side of a SafePoint.
1705   if( ctrl != NULL && ctrl->Opcode() == Op_SafePoint &&
1706       phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw  &&
1707       !addr_mark &&
1708       (depends_only_on_test() || has_unknown_control_dependency())) {
1709     ctrl = ctrl->in(0);
1710     set_req(MemNode::Control,ctrl);
1711     progress = true;
1712   }
1713 
1714   intptr_t ignore = 0;
1715   Node*    base   = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1716   if (base != NULL
1717       && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) {
1718     // Check for useless control edge in some common special cases
1719     if (in(MemNode::Control) != NULL
1720         && can_remove_control()
1721         && phase->type(base)->higher_equal(TypePtr::NOTNULL)
1722         && all_controls_dominate(base, phase->C->start())) {
1723       // A method-invariant, non-null address (constant or 'this' argument).
1724       set_req(MemNode::Control, NULL);
1725       progress = true;
1726     }
1727   }
1728 
1729   Node* mem = in(MemNode::Memory);
1730   const TypePtr *addr_t = phase->type(address)->isa_ptr();
1731 
1732   if (can_reshape && (addr_t != NULL)) {
1733     // try to optimize our memory input
1734     Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase);
1735     if (opt_mem != mem) {
1736       set_req(MemNode::Memory, opt_mem);
1737       if (phase->type( opt_mem ) == Type::TOP) return NULL;
1738       return this;
1739     }
1740     const TypeOopPtr *t_oop = addr_t->isa_oopptr();
1741     if ((t_oop != NULL) &&
1742         (t_oop->is_known_instance_field() ||
1743          t_oop->is_ptr_to_boxed_value())) {
1744       PhaseIterGVN *igvn = phase->is_IterGVN();
1745       if (igvn != NULL && igvn->_worklist.member(opt_mem)) {
1746         // Delay this transformation until memory Phi is processed.
1747         igvn->_worklist.push(this);
1748         return NULL;
1749       }
1750       // Split instance field load through Phi.
1751       Node* result = split_through_phi(phase);
1752       if (result != NULL) return result;
1753 
1754       if (t_oop->is_ptr_to_boxed_value()) {
1755         Node* result = eliminate_autobox(phase);
1756         if (result != NULL) return result;
1757       }
1758     }
1759   }
1760 
1761   // Is there a dominating load that loads the same value?  Leave
1762   // anything that is not a load of a field/array element (like
1763   // barriers etc.) alone
1764   if (in(0) != NULL && !adr_type()->isa_rawptr() && can_reshape) {
1765     for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
1766       Node *use = mem->fast_out(i);
1767       if (use != this &&
1768           use->Opcode() == Opcode() &&
1769           use->in(0) != NULL &&
1770           use->in(0) != in(0) &&
1771           use->in(Address) == in(Address)) {
1772         Node* ctl = in(0);
1773         for (int i = 0; i < 10 && ctl != NULL; i++) {
1774           ctl = IfNode::up_one_dom(ctl);
1775           if (ctl == use->in(0)) {
1776             set_req(0, use->in(0));
1777             return this;
1778           }
1779         }
1780       }
1781     }
1782   }
1783 
1784   // Check for prior store with a different base or offset; make Load
1785   // independent.  Skip through any number of them.  Bail out if the stores
1786   // are in an endless dead cycle and report no progress.  This is a key
1787   // transform for Reflection.  However, if after skipping through the Stores
1788   // we can't then fold up against a prior store do NOT do the transform as
1789   // this amounts to using the 'Oracle' model of aliasing.  It leaves the same
1790   // array memory alive twice: once for the hoisted Load and again after the
1791   // bypassed Store.  This situation only works if EVERYBODY who does
1792   // anti-dependence work knows how to bypass.  I.e. we need all
1793   // anti-dependence checks to ask the same Oracle.  Right now, that Oracle is
1794   // the alias index stuff.  So instead, peek through Stores and IFF we can
1795   // fold up, do so.
1796   Node* prev_mem = find_previous_store(phase);
1797   if (prev_mem != NULL) {
1798     Node* value = can_see_arraycopy_value(prev_mem, phase);
1799     if (value != NULL) {
1800       return value;
1801     }
1802   }
1803   // Steps (a), (b):  Walk past independent stores to find an exact match.
1804   if (prev_mem != NULL && prev_mem != in(MemNode::Memory)) {
1805     // (c) See if we can fold up on the spot, but don't fold up here.
1806     // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or
1807     // just return a prior value, which is done by Identity calls.
1808     if (can_see_stored_value(prev_mem, phase)) {
1809       // Make ready for step (d):
1810       set_req(MemNode::Memory, prev_mem);
1811       return this;
1812     }
1813   }
1814 
1815   AllocateNode* alloc = is_new_object_mark_load(phase);
1816   if (alloc != NULL && alloc->Opcode() == Op_Allocate && UseBiasedLocking) {
1817     InitializeNode* init = alloc->initialization();
1818     Node* control = init->proj_out(0);
1819     return alloc->make_ideal_mark(phase, address, control, mem);
1820   }
1821 
1822   return progress ? this : NULL;
1823 }
1824 
1825 // Helper to recognize certain Klass fields which are invariant across
1826 // some group of array types (e.g., int[] or all T[] where T < Object).
1827 const Type*
load_array_final_field(const TypeKlassPtr * tkls,ciKlass * klass) const1828 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
1829                                  ciKlass* klass) const {
1830   if (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) {
1831     // The field is Klass::_modifier_flags.  Return its (constant) value.
1832     // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
1833     assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
1834     return TypeInt::make(klass->modifier_flags());
1835   }
1836   if (tkls->offset() == in_bytes(Klass::access_flags_offset())) {
1837     // The field is Klass::_access_flags.  Return its (constant) value.
1838     // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
1839     assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
1840     return TypeInt::make(klass->access_flags());
1841   }
1842   if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
1843     // The field is Klass::_layout_helper.  Return its constant value if known.
1844     assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
1845     return TypeInt::make(klass->layout_helper());
1846   }
1847 
1848   // No match.
1849   return NULL;
1850 }
1851 
1852 //------------------------------Value-----------------------------------------
Value(PhaseGVN * phase) const1853 const Type* LoadNode::Value(PhaseGVN* phase) const {
1854   // Either input is TOP ==> the result is TOP
1855   Node* mem = in(MemNode::Memory);
1856   const Type *t1 = phase->type(mem);
1857   if (t1 == Type::TOP)  return Type::TOP;
1858   Node* adr = in(MemNode::Address);
1859   const TypePtr* tp = phase->type(adr)->isa_ptr();
1860   if (tp == NULL || tp->empty())  return Type::TOP;
1861   int off = tp->offset();
1862   assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
1863   Compile* C = phase->C;
1864 
1865   // Try to guess loaded type from pointer type
1866   if (tp->isa_aryptr()) {
1867     const TypeAryPtr* ary = tp->is_aryptr();
1868     const Type* t = ary->elem();
1869 
1870     // Determine whether the reference is beyond the header or not, by comparing
1871     // the offset against the offset of the start of the array's data.
1872     // Different array types begin at slightly different offsets (12 vs. 16).
1873     // We choose T_BYTE as an example base type that is least restrictive
1874     // as to alignment, which will therefore produce the smallest
1875     // possible base offset.
1876     const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1877     const bool off_beyond_header = (off >= min_base_off);
1878 
1879     // Try to constant-fold a stable array element.
1880     if (FoldStableValues && !is_mismatched_access() && ary->is_stable()) {
1881       // Make sure the reference is not into the header and the offset is constant
1882       ciObject* aobj = ary->const_oop();
1883       if (aobj != NULL && off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
1884         int stable_dimension = (ary->stable_dimension() > 0 ? ary->stable_dimension() - 1 : 0);
1885         const Type* con_type = Type::make_constant_from_array_element(aobj->as_array(), off,
1886                                                                       stable_dimension,
1887                                                                       memory_type(), is_unsigned());
1888         if (con_type != NULL) {
1889           return con_type;
1890         }
1891       }
1892     }
1893 
1894     // Don't do this for integer types. There is only potential profit if
1895     // the element type t is lower than _type; that is, for int types, if _type is
1896     // more restrictive than t.  This only happens here if one is short and the other
1897     // char (both 16 bits), and in those cases we've made an intentional decision
1898     // to use one kind of load over the other. See AndINode::Ideal and 4965907.
1899     // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
1900     //
1901     // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
1902     // where the _gvn.type of the AddP is wider than 8.  This occurs when an earlier
1903     // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
1904     // subsumed by p1.  If p1 is on the worklist but has not yet been re-transformed,
1905     // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
1906     // In fact, that could have been the original type of p1, and p1 could have
1907     // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
1908     // expression (LShiftL quux 3) independently optimized to the constant 8.
1909     if ((t->isa_int() == NULL) && (t->isa_long() == NULL)
1910         && (_type->isa_vect() == NULL)
1911         && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
1912       // t might actually be lower than _type, if _type is a unique
1913       // concrete subclass of abstract class t.
1914       if (off_beyond_header || off == Type::OffsetBot) {  // is the offset beyond the header?
1915         const Type* jt = t->join_speculative(_type);
1916         // In any case, do not allow the join, per se, to empty out the type.
1917         if (jt->empty() && !t->empty()) {
1918           // This can happen if a interface-typed array narrows to a class type.
1919           jt = _type;
1920         }
1921 #ifdef ASSERT
1922         if (phase->C->eliminate_boxing() && adr->is_AddP()) {
1923           // The pointers in the autobox arrays are always non-null
1924           Node* base = adr->in(AddPNode::Base);
1925           if ((base != NULL) && base->is_DecodeN()) {
1926             // Get LoadN node which loads IntegerCache.cache field
1927             base = base->in(1);
1928           }
1929           if ((base != NULL) && base->is_Con()) {
1930             const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
1931             if ((base_type != NULL) && base_type->is_autobox_cache()) {
1932               // It could be narrow oop
1933               assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
1934             }
1935           }
1936         }
1937 #endif
1938         return jt;
1939       }
1940     }
1941   } else if (tp->base() == Type::InstPtr) {
1942     assert( off != Type::OffsetBot ||
1943             // arrays can be cast to Objects
1944             tp->is_oopptr()->klass()->is_java_lang_Object() ||
1945             // unsafe field access may not have a constant offset
1946             C->has_unsafe_access(),
1947             "Field accesses must be precise" );
1948     // For oop loads, we expect the _type to be precise.
1949 
1950     // Optimize loads from constant fields.
1951     const TypeInstPtr* tinst = tp->is_instptr();
1952     ciObject* const_oop = tinst->const_oop();
1953     if (!is_mismatched_access() && off != Type::OffsetBot && const_oop != NULL && const_oop->is_instance()) {
1954       const Type* con_type = Type::make_constant_from_field(const_oop->as_instance(), off, is_unsigned(), memory_type());
1955       if (con_type != NULL) {
1956         return con_type;
1957       }
1958     }
1959   } else if (tp->base() == Type::KlassPtr) {
1960     assert( off != Type::OffsetBot ||
1961             // arrays can be cast to Objects
1962             tp->is_klassptr()->klass()->is_java_lang_Object() ||
1963             // also allow array-loading from the primary supertype
1964             // array during subtype checks
1965             Opcode() == Op_LoadKlass,
1966             "Field accesses must be precise" );
1967     // For klass/static loads, we expect the _type to be precise
1968   } else if (tp->base() == Type::RawPtr && adr->is_Load() && off == 0) {
1969     /* With mirrors being an indirect in the Klass*
1970      * the VM is now using two loads. LoadKlass(LoadP(LoadP(Klass, mirror_offset), zero_offset))
1971      * The LoadP from the Klass has a RawPtr type (see LibraryCallKit::load_mirror_from_klass).
1972      *
1973      * So check the type and klass of the node before the LoadP.
1974      */
1975     Node* adr2 = adr->in(MemNode::Address);
1976     const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
1977     if (tkls != NULL && !StressReflectiveCode) {
1978       ciKlass* klass = tkls->klass();
1979       if (klass->is_loaded() && tkls->klass_is_exact() && tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
1980         assert(adr->Opcode() == Op_LoadP, "must load an oop from _java_mirror");
1981         assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
1982         return TypeInstPtr::make(klass->java_mirror());
1983       }
1984     }
1985   }
1986 
1987   const TypeKlassPtr *tkls = tp->isa_klassptr();
1988   if (tkls != NULL && !StressReflectiveCode) {
1989     ciKlass* klass = tkls->klass();
1990     if (klass->is_loaded() && tkls->klass_is_exact()) {
1991       // We are loading a field from a Klass metaobject whose identity
1992       // is known at compile time (the type is "exact" or "precise").
1993       // Check for fields we know are maintained as constants by the VM.
1994       if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
1995         // The field is Klass::_super_check_offset.  Return its (constant) value.
1996         // (Folds up type checking code.)
1997         assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
1998         return TypeInt::make(klass->super_check_offset());
1999       }
2000       // Compute index into primary_supers array
2001       juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
2002       // Check for overflowing; use unsigned compare to handle the negative case.
2003       if( depth < ciKlass::primary_super_limit() ) {
2004         // The field is an element of Klass::_primary_supers.  Return its (constant) value.
2005         // (Folds up type checking code.)
2006         assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
2007         ciKlass *ss = klass->super_of_depth(depth);
2008         return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
2009       }
2010       const Type* aift = load_array_final_field(tkls, klass);
2011       if (aift != NULL)  return aift;
2012     }
2013 
2014     // We can still check if we are loading from the primary_supers array at a
2015     // shallow enough depth.  Even though the klass is not exact, entries less
2016     // than or equal to its super depth are correct.
2017     if (klass->is_loaded() ) {
2018       ciType *inner = klass;
2019       while( inner->is_obj_array_klass() )
2020         inner = inner->as_obj_array_klass()->base_element_type();
2021       if( inner->is_instance_klass() &&
2022           !inner->as_instance_klass()->flags().is_interface() ) {
2023         // Compute index into primary_supers array
2024         juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
2025         // Check for overflowing; use unsigned compare to handle the negative case.
2026         if( depth < ciKlass::primary_super_limit() &&
2027             depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
2028           // The field is an element of Klass::_primary_supers.  Return its (constant) value.
2029           // (Folds up type checking code.)
2030           assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
2031           ciKlass *ss = klass->super_of_depth(depth);
2032           return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
2033         }
2034       }
2035     }
2036 
2037     // If the type is enough to determine that the thing is not an array,
2038     // we can give the layout_helper a positive interval type.
2039     // This will help short-circuit some reflective code.
2040     if (tkls->offset() == in_bytes(Klass::layout_helper_offset())
2041         && !klass->is_array_klass() // not directly typed as an array
2042         && !klass->is_interface()  // specifically not Serializable & Cloneable
2043         && !klass->is_java_lang_Object()   // not the supertype of all T[]
2044         ) {
2045       // Note:  When interfaces are reliable, we can narrow the interface
2046       // test to (klass != Serializable && klass != Cloneable).
2047       assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
2048       jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
2049       // The key property of this type is that it folds up tests
2050       // for array-ness, since it proves that the layout_helper is positive.
2051       // Thus, a generic value like the basic object layout helper works fine.
2052       return TypeInt::make(min_size, max_jint, Type::WidenMin);
2053     }
2054   }
2055 
2056   // If we are loading from a freshly-allocated object, produce a zero,
2057   // if the load is provably beyond the header of the object.
2058   // (Also allow a variable load from a fresh array to produce zero.)
2059   const TypeOopPtr *tinst = tp->isa_oopptr();
2060   bool is_instance = (tinst != NULL) && tinst->is_known_instance_field();
2061   bool is_boxed_value = (tinst != NULL) && tinst->is_ptr_to_boxed_value();
2062   if (ReduceFieldZeroing || is_instance || is_boxed_value) {
2063     Node* value = can_see_stored_value(mem,phase);
2064     if (value != NULL && value->is_Con()) {
2065       assert(value->bottom_type()->higher_equal(_type),"sanity");
2066       return value->bottom_type();
2067     }
2068   }
2069 
2070   bool is_vect = (_type->isa_vect() != NULL);
2071   if (is_instance && !is_vect) {
2072     // If we have an instance type and our memory input is the
2073     // programs's initial memory state, there is no matching store,
2074     // so just return a zero of the appropriate type -
2075     // except if it is vectorized - then we have no zero constant.
2076     Node *mem = in(MemNode::Memory);
2077     if (mem->is_Parm() && mem->in(0)->is_Start()) {
2078       assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
2079       return Type::get_zero_type(_type->basic_type());
2080     }
2081   }
2082 
2083   Node* alloc = is_new_object_mark_load(phase);
2084   if (alloc != NULL && !(alloc->Opcode() == Op_Allocate && UseBiasedLocking)) {
2085     return TypeX::make(markWord::prototype().value());
2086   }
2087 
2088   return _type;
2089 }
2090 
2091 //------------------------------match_edge-------------------------------------
2092 // Do we Match on this edge index or not?  Match only the address.
match_edge(uint idx) const2093 uint LoadNode::match_edge(uint idx) const {
2094   return idx == MemNode::Address;
2095 }
2096 
2097 //--------------------------LoadBNode::Ideal--------------------------------------
2098 //
2099 //  If the previous store is to the same address as this load,
2100 //  and the value stored was larger than a byte, replace this load
2101 //  with the value stored truncated to a byte.  If no truncation is
2102 //  needed, the replacement is done in LoadNode::Identity().
2103 //
Ideal(PhaseGVN * phase,bool can_reshape)2104 Node *LoadBNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2105   Node* mem = in(MemNode::Memory);
2106   Node* value = can_see_stored_value(mem,phase);
2107   if( value && !phase->type(value)->higher_equal( _type ) ) {
2108     Node *result = phase->transform( new LShiftINode(value, phase->intcon(24)) );
2109     return new RShiftINode(result, phase->intcon(24));
2110   }
2111   // Identity call will handle the case where truncation is not needed.
2112   return LoadNode::Ideal(phase, can_reshape);
2113 }
2114 
Value(PhaseGVN * phase) const2115 const Type* LoadBNode::Value(PhaseGVN* phase) const {
2116   Node* mem = in(MemNode::Memory);
2117   Node* value = can_see_stored_value(mem,phase);
2118   if (value != NULL && value->is_Con() &&
2119       !value->bottom_type()->higher_equal(_type)) {
2120     // If the input to the store does not fit with the load's result type,
2121     // it must be truncated. We can't delay until Ideal call since
2122     // a singleton Value is needed for split_thru_phi optimization.
2123     int con = value->get_int();
2124     return TypeInt::make((con << 24) >> 24);
2125   }
2126   return LoadNode::Value(phase);
2127 }
2128 
2129 //--------------------------LoadUBNode::Ideal-------------------------------------
2130 //
2131 //  If the previous store is to the same address as this load,
2132 //  and the value stored was larger than a byte, replace this load
2133 //  with the value stored truncated to a byte.  If no truncation is
2134 //  needed, the replacement is done in LoadNode::Identity().
2135 //
Ideal(PhaseGVN * phase,bool can_reshape)2136 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2137   Node* mem = in(MemNode::Memory);
2138   Node* value = can_see_stored_value(mem, phase);
2139   if (value && !phase->type(value)->higher_equal(_type))
2140     return new AndINode(value, phase->intcon(0xFF));
2141   // Identity call will handle the case where truncation is not needed.
2142   return LoadNode::Ideal(phase, can_reshape);
2143 }
2144 
Value(PhaseGVN * phase) const2145 const Type* LoadUBNode::Value(PhaseGVN* phase) const {
2146   Node* mem = in(MemNode::Memory);
2147   Node* value = can_see_stored_value(mem,phase);
2148   if (value != NULL && value->is_Con() &&
2149       !value->bottom_type()->higher_equal(_type)) {
2150     // If the input to the store does not fit with the load's result type,
2151     // it must be truncated. We can't delay until Ideal call since
2152     // a singleton Value is needed for split_thru_phi optimization.
2153     int con = value->get_int();
2154     return TypeInt::make(con & 0xFF);
2155   }
2156   return LoadNode::Value(phase);
2157 }
2158 
2159 //--------------------------LoadUSNode::Ideal-------------------------------------
2160 //
2161 //  If the previous store is to the same address as this load,
2162 //  and the value stored was larger than a char, replace this load
2163 //  with the value stored truncated to a char.  If no truncation is
2164 //  needed, the replacement is done in LoadNode::Identity().
2165 //
Ideal(PhaseGVN * phase,bool can_reshape)2166 Node *LoadUSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2167   Node* mem = in(MemNode::Memory);
2168   Node* value = can_see_stored_value(mem,phase);
2169   if( value && !phase->type(value)->higher_equal( _type ) )
2170     return new AndINode(value,phase->intcon(0xFFFF));
2171   // Identity call will handle the case where truncation is not needed.
2172   return LoadNode::Ideal(phase, can_reshape);
2173 }
2174 
Value(PhaseGVN * phase) const2175 const Type* LoadUSNode::Value(PhaseGVN* phase) const {
2176   Node* mem = in(MemNode::Memory);
2177   Node* value = can_see_stored_value(mem,phase);
2178   if (value != NULL && value->is_Con() &&
2179       !value->bottom_type()->higher_equal(_type)) {
2180     // If the input to the store does not fit with the load's result type,
2181     // it must be truncated. We can't delay until Ideal call since
2182     // a singleton Value is needed for split_thru_phi optimization.
2183     int con = value->get_int();
2184     return TypeInt::make(con & 0xFFFF);
2185   }
2186   return LoadNode::Value(phase);
2187 }
2188 
2189 //--------------------------LoadSNode::Ideal--------------------------------------
2190 //
2191 //  If the previous store is to the same address as this load,
2192 //  and the value stored was larger than a short, replace this load
2193 //  with the value stored truncated to a short.  If no truncation is
2194 //  needed, the replacement is done in LoadNode::Identity().
2195 //
Ideal(PhaseGVN * phase,bool can_reshape)2196 Node *LoadSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2197   Node* mem = in(MemNode::Memory);
2198   Node* value = can_see_stored_value(mem,phase);
2199   if( value && !phase->type(value)->higher_equal( _type ) ) {
2200     Node *result = phase->transform( new LShiftINode(value, phase->intcon(16)) );
2201     return new RShiftINode(result, phase->intcon(16));
2202   }
2203   // Identity call will handle the case where truncation is not needed.
2204   return LoadNode::Ideal(phase, can_reshape);
2205 }
2206 
Value(PhaseGVN * phase) const2207 const Type* LoadSNode::Value(PhaseGVN* phase) const {
2208   Node* mem = in(MemNode::Memory);
2209   Node* value = can_see_stored_value(mem,phase);
2210   if (value != NULL && value->is_Con() &&
2211       !value->bottom_type()->higher_equal(_type)) {
2212     // If the input to the store does not fit with the load's result type,
2213     // it must be truncated. We can't delay until Ideal call since
2214     // a singleton Value is needed for split_thru_phi optimization.
2215     int con = value->get_int();
2216     return TypeInt::make((con << 16) >> 16);
2217   }
2218   return LoadNode::Value(phase);
2219 }
2220 
2221 //=============================================================================
2222 //----------------------------LoadKlassNode::make------------------------------
2223 // Polymorphic factory method:
make(PhaseGVN & gvn,Node * ctl,Node * mem,Node * adr,const TypePtr * at,const TypeKlassPtr * tk)2224 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) {
2225   // sanity check the alias category against the created node type
2226   const TypePtr *adr_type = adr->bottom_type()->isa_ptr();
2227   assert(adr_type != NULL, "expecting TypeKlassPtr");
2228 #ifdef _LP64
2229   if (adr_type->is_ptr_to_narrowklass()) {
2230     assert(UseCompressedClassPointers, "no compressed klasses");
2231     Node* load_klass = gvn.transform(new LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
2232     return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
2233   }
2234 #endif
2235   assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
2236   return new LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered);
2237 }
2238 
2239 //------------------------------Value------------------------------------------
Value(PhaseGVN * phase) const2240 const Type* LoadKlassNode::Value(PhaseGVN* phase) const {
2241   return klass_value_common(phase);
2242 }
2243 
2244 // In most cases, LoadKlassNode does not have the control input set. If the control
2245 // input is set, it must not be removed (by LoadNode::Ideal()).
can_remove_control() const2246 bool LoadKlassNode::can_remove_control() const {
2247   return false;
2248 }
2249 
klass_value_common(PhaseGVN * phase) const2250 const Type* LoadNode::klass_value_common(PhaseGVN* phase) const {
2251   // Either input is TOP ==> the result is TOP
2252   const Type *t1 = phase->type( in(MemNode::Memory) );
2253   if (t1 == Type::TOP)  return Type::TOP;
2254   Node *adr = in(MemNode::Address);
2255   const Type *t2 = phase->type( adr );
2256   if (t2 == Type::TOP)  return Type::TOP;
2257   const TypePtr *tp = t2->is_ptr();
2258   if (TypePtr::above_centerline(tp->ptr()) ||
2259       tp->ptr() == TypePtr::Null)  return Type::TOP;
2260 
2261   // Return a more precise klass, if possible
2262   const TypeInstPtr *tinst = tp->isa_instptr();
2263   if (tinst != NULL) {
2264     ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
2265     int offset = tinst->offset();
2266     if (ik == phase->C->env()->Class_klass()
2267         && (offset == java_lang_Class::klass_offset() ||
2268             offset == java_lang_Class::array_klass_offset())) {
2269       // We are loading a special hidden field from a Class mirror object,
2270       // the field which points to the VM's Klass metaobject.
2271       ciType* t = tinst->java_mirror_type();
2272       // java_mirror_type returns non-null for compile-time Class constants.
2273       if (t != NULL) {
2274         // constant oop => constant klass
2275         if (offset == java_lang_Class::array_klass_offset()) {
2276           if (t->is_void()) {
2277             // We cannot create a void array.  Since void is a primitive type return null
2278             // klass.  Users of this result need to do a null check on the returned klass.
2279             return TypePtr::NULL_PTR;
2280           }
2281           return TypeKlassPtr::make(ciArrayKlass::make(t));
2282         }
2283         if (!t->is_klass()) {
2284           // a primitive Class (e.g., int.class) has NULL for a klass field
2285           return TypePtr::NULL_PTR;
2286         }
2287         // (Folds up the 1st indirection in aClassConstant.getModifiers().)
2288         return TypeKlassPtr::make(t->as_klass());
2289       }
2290       // non-constant mirror, so we can't tell what's going on
2291     }
2292     if( !ik->is_loaded() )
2293       return _type;             // Bail out if not loaded
2294     if (offset == oopDesc::klass_offset_in_bytes()) {
2295       if (tinst->klass_is_exact()) {
2296         return TypeKlassPtr::make(ik);
2297       }
2298       // See if we can become precise: no subklasses and no interface
2299       // (Note:  We need to support verified interfaces.)
2300       if (!ik->is_interface() && !ik->has_subklass()) {
2301         // Add a dependence; if any subclass added we need to recompile
2302         if (!ik->is_final()) {
2303           // %%% should use stronger assert_unique_concrete_subtype instead
2304           phase->C->dependencies()->assert_leaf_type(ik);
2305         }
2306         // Return precise klass
2307         return TypeKlassPtr::make(ik);
2308       }
2309 
2310       // Return root of possible klass
2311       return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
2312     }
2313   }
2314 
2315   // Check for loading klass from an array
2316   const TypeAryPtr *tary = tp->isa_aryptr();
2317   if( tary != NULL ) {
2318     ciKlass *tary_klass = tary->klass();
2319     if (tary_klass != NULL   // can be NULL when at BOTTOM or TOP
2320         && tary->offset() == oopDesc::klass_offset_in_bytes()) {
2321       if (tary->klass_is_exact()) {
2322         return TypeKlassPtr::make(tary_klass);
2323       }
2324       ciArrayKlass *ak = tary->klass()->as_array_klass();
2325       // If the klass is an object array, we defer the question to the
2326       // array component klass.
2327       if( ak->is_obj_array_klass() ) {
2328         assert( ak->is_loaded(), "" );
2329         ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
2330         if( base_k->is_loaded() && base_k->is_instance_klass() ) {
2331           ciInstanceKlass* ik = base_k->as_instance_klass();
2332           // See if we can become precise: no subklasses and no interface
2333           if (!ik->is_interface() && !ik->has_subklass()) {
2334             // Add a dependence; if any subclass added we need to recompile
2335             if (!ik->is_final()) {
2336               phase->C->dependencies()->assert_leaf_type(ik);
2337             }
2338             // Return precise array klass
2339             return TypeKlassPtr::make(ak);
2340           }
2341         }
2342         return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
2343       } else {                  // Found a type-array?
2344         assert( ak->is_type_array_klass(), "" );
2345         return TypeKlassPtr::make(ak); // These are always precise
2346       }
2347     }
2348   }
2349 
2350   // Check for loading klass from an array klass
2351   const TypeKlassPtr *tkls = tp->isa_klassptr();
2352   if (tkls != NULL && !StressReflectiveCode) {
2353     ciKlass* klass = tkls->klass();
2354     if( !klass->is_loaded() )
2355       return _type;             // Bail out if not loaded
2356     if( klass->is_obj_array_klass() &&
2357         tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
2358       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
2359       // // Always returning precise element type is incorrect,
2360       // // e.g., element type could be object and array may contain strings
2361       // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
2362 
2363       // The array's TypeKlassPtr was declared 'precise' or 'not precise'
2364       // according to the element type's subclassing.
2365       return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
2366     }
2367     if( klass->is_instance_klass() && tkls->klass_is_exact() &&
2368         tkls->offset() == in_bytes(Klass::super_offset())) {
2369       ciKlass* sup = klass->as_instance_klass()->super();
2370       // The field is Klass::_super.  Return its (constant) value.
2371       // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
2372       return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
2373     }
2374   }
2375 
2376   // Bailout case
2377   return LoadNode::Value(phase);
2378 }
2379 
2380 //------------------------------Identity---------------------------------------
2381 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
2382 // Also feed through the klass in Allocate(...klass...)._klass.
Identity(PhaseGVN * phase)2383 Node* LoadKlassNode::Identity(PhaseGVN* phase) {
2384   return klass_identity_common(phase);
2385 }
2386 
klass_identity_common(PhaseGVN * phase)2387 Node* LoadNode::klass_identity_common(PhaseGVN* phase) {
2388   Node* x = LoadNode::Identity(phase);
2389   if (x != this)  return x;
2390 
2391   // Take apart the address into an oop and and offset.
2392   // Return 'this' if we cannot.
2393   Node*    adr    = in(MemNode::Address);
2394   intptr_t offset = 0;
2395   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2396   if (base == NULL)     return this;
2397   const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
2398   if (toop == NULL)     return this;
2399 
2400   // Step over potential GC barrier for OopHandle resolve
2401   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2402   if (bs->is_gc_barrier_node(base)) {
2403     base = bs->step_over_gc_barrier(base);
2404   }
2405 
2406   // We can fetch the klass directly through an AllocateNode.
2407   // This works even if the klass is not constant (clone or newArray).
2408   if (offset == oopDesc::klass_offset_in_bytes()) {
2409     Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
2410     if (allocated_klass != NULL) {
2411       return allocated_klass;
2412     }
2413   }
2414 
2415   // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
2416   // See inline_native_Class_query for occurrences of these patterns.
2417   // Java Example:  x.getClass().isAssignableFrom(y)
2418   //
2419   // This improves reflective code, often making the Class
2420   // mirror go completely dead.  (Current exception:  Class
2421   // mirrors may appear in debug info, but we could clean them out by
2422   // introducing a new debug info operator for Klass.java_mirror).
2423 
2424   if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
2425       && offset == java_lang_Class::klass_offset()) {
2426     if (base->is_Load()) {
2427       Node* base2 = base->in(MemNode::Address);
2428       if (base2->is_Load()) { /* direct load of a load which is the OopHandle */
2429         Node* adr2 = base2->in(MemNode::Address);
2430         const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2431         if (tkls != NULL && !tkls->empty()
2432             && (tkls->klass()->is_instance_klass() ||
2433               tkls->klass()->is_array_klass())
2434             && adr2->is_AddP()
2435            ) {
2436           int mirror_field = in_bytes(Klass::java_mirror_offset());
2437           if (tkls->offset() == mirror_field) {
2438             return adr2->in(AddPNode::Base);
2439           }
2440         }
2441       }
2442     }
2443   }
2444 
2445   return this;
2446 }
2447 
2448 
2449 //------------------------------Value------------------------------------------
Value(PhaseGVN * phase) const2450 const Type* LoadNKlassNode::Value(PhaseGVN* phase) const {
2451   const Type *t = klass_value_common(phase);
2452   if (t == Type::TOP)
2453     return t;
2454 
2455   return t->make_narrowklass();
2456 }
2457 
2458 //------------------------------Identity---------------------------------------
2459 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
2460 // Also feed through the klass in Allocate(...klass...)._klass.
Identity(PhaseGVN * phase)2461 Node* LoadNKlassNode::Identity(PhaseGVN* phase) {
2462   Node *x = klass_identity_common(phase);
2463 
2464   const Type *t = phase->type( x );
2465   if( t == Type::TOP ) return x;
2466   if( t->isa_narrowklass()) return x;
2467   assert (!t->isa_narrowoop(), "no narrow oop here");
2468 
2469   return phase->transform(new EncodePKlassNode(x, t->make_narrowklass()));
2470 }
2471 
2472 //------------------------------Value-----------------------------------------
Value(PhaseGVN * phase) const2473 const Type* LoadRangeNode::Value(PhaseGVN* phase) const {
2474   // Either input is TOP ==> the result is TOP
2475   const Type *t1 = phase->type( in(MemNode::Memory) );
2476   if( t1 == Type::TOP ) return Type::TOP;
2477   Node *adr = in(MemNode::Address);
2478   const Type *t2 = phase->type( adr );
2479   if( t2 == Type::TOP ) return Type::TOP;
2480   const TypePtr *tp = t2->is_ptr();
2481   if (TypePtr::above_centerline(tp->ptr()))  return Type::TOP;
2482   const TypeAryPtr *tap = tp->isa_aryptr();
2483   if( !tap ) return _type;
2484   return tap->size();
2485 }
2486 
2487 //-------------------------------Ideal---------------------------------------
2488 // Feed through the length in AllocateArray(...length...)._length.
Ideal(PhaseGVN * phase,bool can_reshape)2489 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2490   Node* p = MemNode::Ideal_common(phase, can_reshape);
2491   if (p)  return (p == NodeSentinel) ? NULL : p;
2492 
2493   // Take apart the address into an oop and and offset.
2494   // Return 'this' if we cannot.
2495   Node*    adr    = in(MemNode::Address);
2496   intptr_t offset = 0;
2497   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase,  offset);
2498   if (base == NULL)     return NULL;
2499   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2500   if (tary == NULL)     return NULL;
2501 
2502   // We can fetch the length directly through an AllocateArrayNode.
2503   // This works even if the length is not constant (clone or newArray).
2504   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2505     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2506     if (alloc != NULL) {
2507       Node* allocated_length = alloc->Ideal_length();
2508       Node* len = alloc->make_ideal_length(tary, phase);
2509       if (allocated_length != len) {
2510         // New CastII improves on this.
2511         return len;
2512       }
2513     }
2514   }
2515 
2516   return NULL;
2517 }
2518 
2519 //------------------------------Identity---------------------------------------
2520 // Feed through the length in AllocateArray(...length...)._length.
Identity(PhaseGVN * phase)2521 Node* LoadRangeNode::Identity(PhaseGVN* phase) {
2522   Node* x = LoadINode::Identity(phase);
2523   if (x != this)  return x;
2524 
2525   // Take apart the address into an oop and and offset.
2526   // Return 'this' if we cannot.
2527   Node*    adr    = in(MemNode::Address);
2528   intptr_t offset = 0;
2529   Node*    base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2530   if (base == NULL)     return this;
2531   const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2532   if (tary == NULL)     return this;
2533 
2534   // We can fetch the length directly through an AllocateArrayNode.
2535   // This works even if the length is not constant (clone or newArray).
2536   if (offset == arrayOopDesc::length_offset_in_bytes()) {
2537     AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2538     if (alloc != NULL) {
2539       Node* allocated_length = alloc->Ideal_length();
2540       // Do not allow make_ideal_length to allocate a CastII node.
2541       Node* len = alloc->make_ideal_length(tary, phase, false);
2542       if (allocated_length == len) {
2543         // Return allocated_length only if it would not be improved by a CastII.
2544         return allocated_length;
2545       }
2546     }
2547   }
2548 
2549   return this;
2550 
2551 }
2552 
2553 //=============================================================================
2554 //---------------------------StoreNode::make-----------------------------------
2555 // Polymorphic factory method:
make(PhaseGVN & gvn,Node * ctl,Node * mem,Node * adr,const TypePtr * adr_type,Node * val,BasicType bt,MemOrd mo)2556 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo) {
2557   assert((mo == unordered || mo == release), "unexpected");
2558   Compile* C = gvn.C;
2559   assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
2560          ctl != NULL, "raw memory operations should have control edge");
2561 
2562   switch (bt) {
2563   case T_BOOLEAN: val = gvn.transform(new AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case
2564   case T_BYTE:    return new StoreBNode(ctl, mem, adr, adr_type, val, mo);
2565   case T_INT:     return new StoreINode(ctl, mem, adr, adr_type, val, mo);
2566   case T_CHAR:
2567   case T_SHORT:   return new StoreCNode(ctl, mem, adr, adr_type, val, mo);
2568   case T_LONG:    return new StoreLNode(ctl, mem, adr, adr_type, val, mo);
2569   case T_FLOAT:   return new StoreFNode(ctl, mem, adr, adr_type, val, mo);
2570   case T_DOUBLE:  return new StoreDNode(ctl, mem, adr, adr_type, val, mo);
2571   case T_METADATA:
2572   case T_ADDRESS:
2573   case T_OBJECT:
2574 #ifdef _LP64
2575     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2576       val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop()));
2577       return new StoreNNode(ctl, mem, adr, adr_type, val, mo);
2578     } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
2579                (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
2580                 adr->bottom_type()->isa_rawptr())) {
2581       val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
2582       return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
2583     }
2584 #endif
2585     {
2586       return new StorePNode(ctl, mem, adr, adr_type, val, mo);
2587     }
2588   default:
2589     ShouldNotReachHere();
2590     return (StoreNode*)NULL;
2591   }
2592 }
2593 
make_atomic(Node * ctl,Node * mem,Node * adr,const TypePtr * adr_type,Node * val,MemOrd mo)2594 StoreLNode* StoreLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2595   bool require_atomic = true;
2596   return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2597 }
2598 
make_atomic(Node * ctl,Node * mem,Node * adr,const TypePtr * adr_type,Node * val,MemOrd mo)2599 StoreDNode* StoreDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
2600   bool require_atomic = true;
2601   return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
2602 }
2603 
2604 
2605 //--------------------------bottom_type----------------------------------------
bottom_type() const2606 const Type *StoreNode::bottom_type() const {
2607   return Type::MEMORY;
2608 }
2609 
2610 //------------------------------hash-------------------------------------------
hash() const2611 uint StoreNode::hash() const {
2612   // unroll addition of interesting fields
2613   //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
2614 
2615   // Since they are not commoned, do not hash them:
2616   return NO_HASH;
2617 }
2618 
2619 //------------------------------Ideal------------------------------------------
2620 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
2621 // When a store immediately follows a relevant allocation/initialization,
2622 // try to capture it into the initialization, or hoist it above.
Ideal(PhaseGVN * phase,bool can_reshape)2623 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2624   Node* p = MemNode::Ideal_common(phase, can_reshape);
2625   if (p)  return (p == NodeSentinel) ? NULL : p;
2626 
2627   Node* mem     = in(MemNode::Memory);
2628   Node* address = in(MemNode::Address);
2629   Node* value   = in(MemNode::ValueIn);
2630   // Back-to-back stores to same address?  Fold em up.  Generally
2631   // unsafe if I have intervening uses...  Also disallowed for StoreCM
2632   // since they must follow each StoreP operation.  Redundant StoreCMs
2633   // are eliminated just before matching in final_graph_reshape.
2634   {
2635     Node* st = mem;
2636     // If Store 'st' has more than one use, we cannot fold 'st' away.
2637     // For example, 'st' might be the final state at a conditional
2638     // return.  Or, 'st' might be used by some node which is live at
2639     // the same time 'st' is live, which might be unschedulable.  So,
2640     // require exactly ONE user until such time as we clone 'mem' for
2641     // each of 'mem's uses (thus making the exactly-1-user-rule hold
2642     // true).
2643     while (st->is_Store() && st->outcnt() == 1 && st->Opcode() != Op_StoreCM) {
2644       // Looking at a dead closed cycle of memory?
2645       assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
2646       assert(Opcode() == st->Opcode() ||
2647              st->Opcode() == Op_StoreVector ||
2648              Opcode() == Op_StoreVector ||
2649              st->Opcode() == Op_StoreVectorScatter ||
2650              Opcode() == Op_StoreVectorScatter ||
2651              phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw ||
2652              (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode
2653              (Opcode() == Op_StoreI && st->Opcode() == Op_StoreL) || // initialization by arraycopy
2654              (is_mismatched_access() || st->as_Store()->is_mismatched_access()),
2655              "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]);
2656 
2657       if (st->in(MemNode::Address)->eqv_uncast(address) &&
2658           st->as_Store()->memory_size() <= this->memory_size()) {
2659         Node* use = st->raw_out(0);
2660         if (phase->is_IterGVN()) {
2661           phase->is_IterGVN()->rehash_node_delayed(use);
2662         }
2663         if (can_reshape) {
2664           use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase->is_IterGVN());
2665         } else {
2666           // It's OK to do this in the parser, since DU info is always accurate,
2667           // and the parser always refers to nodes via SafePointNode maps.
2668           use->set_req(MemNode::Memory, st->in(MemNode::Memory));
2669         }
2670         return this;
2671       }
2672       st = st->in(MemNode::Memory);
2673     }
2674   }
2675 
2676 
2677   // Capture an unaliased, unconditional, simple store into an initializer.
2678   // Or, if it is independent of the allocation, hoist it above the allocation.
2679   if (ReduceFieldZeroing && /*can_reshape &&*/
2680       mem->is_Proj() && mem->in(0)->is_Initialize()) {
2681     InitializeNode* init = mem->in(0)->as_Initialize();
2682     intptr_t offset = init->can_capture_store(this, phase, can_reshape);
2683     if (offset > 0) {
2684       Node* moved = init->capture_store(this, offset, phase, can_reshape);
2685       // If the InitializeNode captured me, it made a raw copy of me,
2686       // and I need to disappear.
2687       if (moved != NULL) {
2688         // %%% hack to ensure that Ideal returns a new node:
2689         mem = MergeMemNode::make(mem);
2690         return mem;             // fold me away
2691       }
2692     }
2693   }
2694 
2695   // Fold reinterpret cast into memory operation:
2696   //    StoreX mem (MoveY2X v) => StoreY mem v
2697   if (value->is_Move()) {
2698     const Type* vt = value->in(1)->bottom_type();
2699     if (has_reinterpret_variant(vt)) {
2700       if (phase->C->post_loop_opts_phase()) {
2701         return convert_to_reinterpret_store(*phase, value->in(1), vt);
2702       } else {
2703         phase->C->record_for_post_loop_opts_igvn(this); // attempt the transformation once loop opts are over
2704       }
2705     }
2706   }
2707 
2708   return NULL;                  // No further progress
2709 }
2710 
2711 //------------------------------Value-----------------------------------------
Value(PhaseGVN * phase) const2712 const Type* StoreNode::Value(PhaseGVN* phase) const {
2713   // Either input is TOP ==> the result is TOP
2714   const Type *t1 = phase->type( in(MemNode::Memory) );
2715   if( t1 == Type::TOP ) return Type::TOP;
2716   const Type *t2 = phase->type( in(MemNode::Address) );
2717   if( t2 == Type::TOP ) return Type::TOP;
2718   const Type *t3 = phase->type( in(MemNode::ValueIn) );
2719   if( t3 == Type::TOP ) return Type::TOP;
2720   return Type::MEMORY;
2721 }
2722 
2723 //------------------------------Identity---------------------------------------
2724 // Remove redundant stores:
2725 //   Store(m, p, Load(m, p)) changes to m.
2726 //   Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
Identity(PhaseGVN * phase)2727 Node* StoreNode::Identity(PhaseGVN* phase) {
2728   Node* mem = in(MemNode::Memory);
2729   Node* adr = in(MemNode::Address);
2730   Node* val = in(MemNode::ValueIn);
2731 
2732   Node* result = this;
2733 
2734   // Load then Store?  Then the Store is useless
2735   if (val->is_Load() &&
2736       val->in(MemNode::Address)->eqv_uncast(adr) &&
2737       val->in(MemNode::Memory )->eqv_uncast(mem) &&
2738       val->as_Load()->store_Opcode() == Opcode()) {
2739     result = mem;
2740   }
2741 
2742   // Two stores in a row of the same value?
2743   if (result == this &&
2744       mem->is_Store() &&
2745       mem->in(MemNode::Address)->eqv_uncast(adr) &&
2746       mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
2747       mem->Opcode() == Opcode()) {
2748     result = mem;
2749   }
2750 
2751   // Store of zero anywhere into a freshly-allocated object?
2752   // Then the store is useless.
2753   // (It must already have been captured by the InitializeNode.)
2754   if (result == this &&
2755       ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
2756     // a newly allocated object is already all-zeroes everywhere
2757     if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
2758       result = mem;
2759     }
2760 
2761     if (result == this) {
2762       // the store may also apply to zero-bits in an earlier object
2763       Node* prev_mem = find_previous_store(phase);
2764       // Steps (a), (b):  Walk past independent stores to find an exact match.
2765       if (prev_mem != NULL) {
2766         Node* prev_val = can_see_stored_value(prev_mem, phase);
2767         if (prev_val != NULL && prev_val == val) {
2768           // prev_val and val might differ by a cast; it would be good
2769           // to keep the more informative of the two.
2770           result = mem;
2771         }
2772       }
2773     }
2774   }
2775 
2776   PhaseIterGVN* igvn = phase->is_IterGVN();
2777   if (result != this && igvn != NULL) {
2778     MemBarNode* trailing = trailing_membar();
2779     if (trailing != NULL) {
2780 #ifdef ASSERT
2781       const TypeOopPtr* t_oop = phase->type(in(Address))->isa_oopptr();
2782       assert(t_oop == NULL || t_oop->is_known_instance_field(), "only for non escaping objects");
2783 #endif
2784       trailing->remove(igvn);
2785     }
2786   }
2787 
2788   return result;
2789 }
2790 
2791 //------------------------------match_edge-------------------------------------
2792 // Do we Match on this edge index or not?  Match only memory & value
match_edge(uint idx) const2793 uint StoreNode::match_edge(uint idx) const {
2794   return idx == MemNode::Address || idx == MemNode::ValueIn;
2795 }
2796 
2797 //------------------------------cmp--------------------------------------------
2798 // Do not common stores up together.  They generally have to be split
2799 // back up anyways, so do not bother.
cmp(const Node & n) const2800 bool StoreNode::cmp( const Node &n ) const {
2801   return (&n == this);          // Always fail except on self
2802 }
2803 
2804 //------------------------------Ideal_masked_input-----------------------------
2805 // Check for a useless mask before a partial-word store
2806 // (StoreB ... (AndI valIn conIa) )
2807 // If (conIa & mask == mask) this simplifies to
2808 // (StoreB ... (valIn) )
Ideal_masked_input(PhaseGVN * phase,uint mask)2809 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
2810   Node *val = in(MemNode::ValueIn);
2811   if( val->Opcode() == Op_AndI ) {
2812     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2813     if( t && t->is_con() && (t->get_con() & mask) == mask ) {
2814       set_req(MemNode::ValueIn, val->in(1));
2815       return this;
2816     }
2817   }
2818   return NULL;
2819 }
2820 
2821 
2822 //------------------------------Ideal_sign_extended_input----------------------
2823 // Check for useless sign-extension before a partial-word store
2824 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
2825 // If (conIL == conIR && conIR <= num_bits)  this simplifies to
2826 // (StoreB ... (valIn) )
Ideal_sign_extended_input(PhaseGVN * phase,int num_bits)2827 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
2828   Node *val = in(MemNode::ValueIn);
2829   if( val->Opcode() == Op_RShiftI ) {
2830     const TypeInt *t = phase->type( val->in(2) )->isa_int();
2831     if( t && t->is_con() && (t->get_con() <= num_bits) ) {
2832       Node *shl = val->in(1);
2833       if( shl->Opcode() == Op_LShiftI ) {
2834         const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
2835         if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
2836           set_req(MemNode::ValueIn, shl->in(1));
2837           return this;
2838         }
2839       }
2840     }
2841   }
2842   return NULL;
2843 }
2844 
2845 //------------------------------value_never_loaded-----------------------------------
2846 // Determine whether there are any possible loads of the value stored.
2847 // For simplicity, we actually check if there are any loads from the
2848 // address stored to, not just for loads of the value stored by this node.
2849 //
value_never_loaded(PhaseTransform * phase) const2850 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
2851   Node *adr = in(Address);
2852   const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
2853   if (adr_oop == NULL)
2854     return false;
2855   if (!adr_oop->is_known_instance_field())
2856     return false; // if not a distinct instance, there may be aliases of the address
2857   for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
2858     Node *use = adr->fast_out(i);
2859     if (use->is_Load() || use->is_LoadStore()) {
2860       return false;
2861     }
2862   }
2863   return true;
2864 }
2865 
trailing_membar() const2866 MemBarNode* StoreNode::trailing_membar() const {
2867   if (is_release()) {
2868     MemBarNode* trailing_mb = NULL;
2869     for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
2870       Node* u = fast_out(i);
2871       if (u->is_MemBar()) {
2872         if (u->as_MemBar()->trailing_store()) {
2873           assert(u->Opcode() == Op_MemBarVolatile, "");
2874           assert(trailing_mb == NULL, "only one");
2875           trailing_mb = u->as_MemBar();
2876 #ifdef ASSERT
2877           Node* leading = u->as_MemBar()->leading_membar();
2878           assert(leading->Opcode() == Op_MemBarRelease, "incorrect membar");
2879           assert(leading->as_MemBar()->leading_store(), "incorrect membar pair");
2880           assert(leading->as_MemBar()->trailing_membar() == u, "incorrect membar pair");
2881 #endif
2882         } else {
2883           assert(u->as_MemBar()->standalone(), "");
2884         }
2885       }
2886     }
2887     return trailing_mb;
2888   }
2889   return NULL;
2890 }
2891 
2892 
2893 //=============================================================================
2894 //------------------------------Ideal------------------------------------------
2895 // If the store is from an AND mask that leaves the low bits untouched, then
2896 // we can skip the AND operation.  If the store is from a sign-extension
2897 // (a left shift, then right shift) we can skip both.
Ideal(PhaseGVN * phase,bool can_reshape)2898 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
2899   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
2900   if( progress != NULL ) return progress;
2901 
2902   progress = StoreNode::Ideal_sign_extended_input(phase, 24);
2903   if( progress != NULL ) return progress;
2904 
2905   // Finally check the default case
2906   return StoreNode::Ideal(phase, can_reshape);
2907 }
2908 
2909 //=============================================================================
2910 //------------------------------Ideal------------------------------------------
2911 // If the store is from an AND mask that leaves the low bits untouched, then
2912 // we can skip the AND operation
Ideal(PhaseGVN * phase,bool can_reshape)2913 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
2914   Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
2915   if( progress != NULL ) return progress;
2916 
2917   progress = StoreNode::Ideal_sign_extended_input(phase, 16);
2918   if( progress != NULL ) return progress;
2919 
2920   // Finally check the default case
2921   return StoreNode::Ideal(phase, can_reshape);
2922 }
2923 
2924 //=============================================================================
2925 //------------------------------Identity---------------------------------------
Identity(PhaseGVN * phase)2926 Node* StoreCMNode::Identity(PhaseGVN* phase) {
2927   // No need to card mark when storing a null ptr
2928   Node* my_store = in(MemNode::OopStore);
2929   if (my_store->is_Store()) {
2930     const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
2931     if( t1 == TypePtr::NULL_PTR ) {
2932       return in(MemNode::Memory);
2933     }
2934   }
2935   return this;
2936 }
2937 
2938 //=============================================================================
2939 //------------------------------Ideal---------------------------------------
Ideal(PhaseGVN * phase,bool can_reshape)2940 Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
2941   Node* progress = StoreNode::Ideal(phase, can_reshape);
2942   if (progress != NULL) return progress;
2943 
2944   Node* my_store = in(MemNode::OopStore);
2945   if (my_store->is_MergeMem()) {
2946     Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
2947     set_req(MemNode::OopStore, mem);
2948     return this;
2949   }
2950 
2951   return NULL;
2952 }
2953 
2954 //------------------------------Value-----------------------------------------
Value(PhaseGVN * phase) const2955 const Type* StoreCMNode::Value(PhaseGVN* phase) const {
2956   // Either input is TOP ==> the result is TOP
2957   const Type *t = phase->type( in(MemNode::Memory) );
2958   if( t == Type::TOP ) return Type::TOP;
2959   t = phase->type( in(MemNode::Address) );
2960   if( t == Type::TOP ) return Type::TOP;
2961   t = phase->type( in(MemNode::ValueIn) );
2962   if( t == Type::TOP ) return Type::TOP;
2963   // If extra input is TOP ==> the result is TOP
2964   t = phase->type( in(MemNode::OopStore) );
2965   if( t == Type::TOP ) return Type::TOP;
2966 
2967   return StoreNode::Value( phase );
2968 }
2969 
2970 
2971 //=============================================================================
2972 //----------------------------------SCMemProjNode------------------------------
Value(PhaseGVN * phase) const2973 const Type* SCMemProjNode::Value(PhaseGVN* phase) const
2974 {
2975   return bottom_type();
2976 }
2977 
2978 //=============================================================================
2979 //----------------------------------LoadStoreNode------------------------------
LoadStoreNode(Node * c,Node * mem,Node * adr,Node * val,const TypePtr * at,const Type * rt,uint required)2980 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
2981   : Node(required),
2982     _type(rt),
2983     _adr_type(at),
2984     _barrier_data(0)
2985 {
2986   init_req(MemNode::Control, c  );
2987   init_req(MemNode::Memory , mem);
2988   init_req(MemNode::Address, adr);
2989   init_req(MemNode::ValueIn, val);
2990   init_class_id(Class_LoadStore);
2991 }
2992 
ideal_reg() const2993 uint LoadStoreNode::ideal_reg() const {
2994   return _type->ideal_reg();
2995 }
2996 
result_not_used() const2997 bool LoadStoreNode::result_not_used() const {
2998   for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
2999     Node *x = fast_out(i);
3000     if (x->Opcode() == Op_SCMemProj) continue;
3001     return false;
3002   }
3003   return true;
3004 }
3005 
trailing_membar() const3006 MemBarNode* LoadStoreNode::trailing_membar() const {
3007   MemBarNode* trailing = NULL;
3008   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
3009     Node* u = fast_out(i);
3010     if (u->is_MemBar()) {
3011       if (u->as_MemBar()->trailing_load_store()) {
3012         assert(u->Opcode() == Op_MemBarAcquire, "");
3013         assert(trailing == NULL, "only one");
3014         trailing = u->as_MemBar();
3015 #ifdef ASSERT
3016         Node* leading = trailing->leading_membar();
3017         assert(support_IRIW_for_not_multiple_copy_atomic_cpu || leading->Opcode() == Op_MemBarRelease, "incorrect membar");
3018         assert(leading->as_MemBar()->leading_load_store(), "incorrect membar pair");
3019         assert(leading->as_MemBar()->trailing_membar() == trailing, "incorrect membar pair");
3020 #endif
3021       } else {
3022         assert(u->as_MemBar()->standalone(), "wrong barrier kind");
3023       }
3024     }
3025   }
3026 
3027   return trailing;
3028 }
3029 
size_of() const3030 uint LoadStoreNode::size_of() const { return sizeof(*this); }
3031 
3032 //=============================================================================
3033 //----------------------------------LoadStoreConditionalNode--------------------
LoadStoreConditionalNode(Node * c,Node * mem,Node * adr,Node * val,Node * ex)3034 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, NULL, TypeInt::BOOL, 5) {
3035   init_req(ExpectedIn, ex );
3036 }
3037 
3038 //=============================================================================
3039 //-------------------------------adr_type--------------------------------------
adr_type() const3040 const TypePtr* ClearArrayNode::adr_type() const {
3041   Node *adr = in(3);
3042   if (adr == NULL)  return NULL; // node is dead
3043   return MemNode::calculate_adr_type(adr->bottom_type());
3044 }
3045 
3046 //------------------------------match_edge-------------------------------------
3047 // Do we Match on this edge index or not?  Do not match memory
match_edge(uint idx) const3048 uint ClearArrayNode::match_edge(uint idx) const {
3049   return idx > 1;
3050 }
3051 
3052 //------------------------------Identity---------------------------------------
3053 // Clearing a zero length array does nothing
Identity(PhaseGVN * phase)3054 Node* ClearArrayNode::Identity(PhaseGVN* phase) {
3055   return phase->type(in(2))->higher_equal(TypeX::ZERO)  ? in(1) : this;
3056 }
3057 
3058 //------------------------------Idealize---------------------------------------
3059 // Clearing a short array is faster with stores
Ideal(PhaseGVN * phase,bool can_reshape)3060 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3061   // Already know this is a large node, do not try to ideal it
3062   if (!IdealizeClearArrayNode || _is_large) return NULL;
3063 
3064   const int unit = BytesPerLong;
3065   const TypeX* t = phase->type(in(2))->isa_intptr_t();
3066   if (!t)  return NULL;
3067   if (!t->is_con())  return NULL;
3068   intptr_t raw_count = t->get_con();
3069   intptr_t size = raw_count;
3070   if (!Matcher::init_array_count_is_in_bytes) size *= unit;
3071   // Clearing nothing uses the Identity call.
3072   // Negative clears are possible on dead ClearArrays
3073   // (see jck test stmt114.stmt11402.val).
3074   if (size <= 0 || size % unit != 0)  return NULL;
3075   intptr_t count = size / unit;
3076   // Length too long; communicate this to matchers and assemblers.
3077   // Assemblers are responsible to produce fast hardware clears for it.
3078   if (size > InitArrayShortSize) {
3079     return new ClearArrayNode(in(0), in(1), in(2), in(3), true);
3080   }
3081   Node *mem = in(1);
3082   if( phase->type(mem)==Type::TOP ) return NULL;
3083   Node *adr = in(3);
3084   const Type* at = phase->type(adr);
3085   if( at==Type::TOP ) return NULL;
3086   const TypePtr* atp = at->isa_ptr();
3087   // adjust atp to be the correct array element address type
3088   if (atp == NULL)  atp = TypePtr::BOTTOM;
3089   else              atp = atp->add_offset(Type::OffsetBot);
3090   // Get base for derived pointer purposes
3091   if( adr->Opcode() != Op_AddP ) Unimplemented();
3092   Node *base = adr->in(1);
3093 
3094   Node *zero = phase->makecon(TypeLong::ZERO);
3095   Node *off  = phase->MakeConX(BytesPerLong);
3096   mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
3097   count--;
3098   while( count-- ) {
3099     mem = phase->transform(mem);
3100     adr = phase->transform(new AddPNode(base,adr,off));
3101     mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
3102   }
3103   return mem;
3104 }
3105 
3106 //----------------------------step_through----------------------------------
3107 // Return allocation input memory edge if it is different instance
3108 // or itself if it is the one we are looking for.
step_through(Node ** np,uint instance_id,PhaseTransform * phase)3109 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseTransform* phase) {
3110   Node* n = *np;
3111   assert(n->is_ClearArray(), "sanity");
3112   intptr_t offset;
3113   AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
3114   // This method is called only before Allocate nodes are expanded
3115   // during macro nodes expansion. Before that ClearArray nodes are
3116   // only generated in PhaseMacroExpand::generate_arraycopy() (before
3117   // Allocate nodes are expanded) which follows allocations.
3118   assert(alloc != NULL, "should have allocation");
3119   if (alloc->_idx == instance_id) {
3120     // Can not bypass initialization of the instance we are looking for.
3121     return false;
3122   }
3123   // Otherwise skip it.
3124   InitializeNode* init = alloc->initialization();
3125   if (init != NULL)
3126     *np = init->in(TypeFunc::Memory);
3127   else
3128     *np = alloc->in(TypeFunc::Memory);
3129   return true;
3130 }
3131 
3132 //----------------------------clear_memory-------------------------------------
3133 // Generate code to initialize object storage to zero.
clear_memory(Node * ctl,Node * mem,Node * dest,intptr_t start_offset,Node * end_offset,PhaseGVN * phase)3134 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3135                                    intptr_t start_offset,
3136                                    Node* end_offset,
3137                                    PhaseGVN* phase) {
3138   intptr_t offset = start_offset;
3139 
3140   int unit = BytesPerLong;
3141   if ((offset % unit) != 0) {
3142     Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset));
3143     adr = phase->transform(adr);
3144     const TypePtr* atp = TypeRawPtr::BOTTOM;
3145     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
3146     mem = phase->transform(mem);
3147     offset += BytesPerInt;
3148   }
3149   assert((offset % unit) == 0, "");
3150 
3151   // Initialize the remaining stuff, if any, with a ClearArray.
3152   return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
3153 }
3154 
clear_memory(Node * ctl,Node * mem,Node * dest,Node * start_offset,Node * end_offset,PhaseGVN * phase)3155 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3156                                    Node* start_offset,
3157                                    Node* end_offset,
3158                                    PhaseGVN* phase) {
3159   if (start_offset == end_offset) {
3160     // nothing to do
3161     return mem;
3162   }
3163 
3164   int unit = BytesPerLong;
3165   Node* zbase = start_offset;
3166   Node* zend  = end_offset;
3167 
3168   // Scale to the unit required by the CPU:
3169   if (!Matcher::init_array_count_is_in_bytes) {
3170     Node* shift = phase->intcon(exact_log2(unit));
3171     zbase = phase->transform(new URShiftXNode(zbase, shift) );
3172     zend  = phase->transform(new URShiftXNode(zend,  shift) );
3173   }
3174 
3175   // Bulk clear double-words
3176   Node* zsize = phase->transform(new SubXNode(zend, zbase) );
3177   Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) );
3178   mem = new ClearArrayNode(ctl, mem, zsize, adr, false);
3179   return phase->transform(mem);
3180 }
3181 
clear_memory(Node * ctl,Node * mem,Node * dest,intptr_t start_offset,intptr_t end_offset,PhaseGVN * phase)3182 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
3183                                    intptr_t start_offset,
3184                                    intptr_t end_offset,
3185                                    PhaseGVN* phase) {
3186   if (start_offset == end_offset) {
3187     // nothing to do
3188     return mem;
3189   }
3190 
3191   assert((end_offset % BytesPerInt) == 0, "odd end offset");
3192   intptr_t done_offset = end_offset;
3193   if ((done_offset % BytesPerLong) != 0) {
3194     done_offset -= BytesPerInt;
3195   }
3196   if (done_offset > start_offset) {
3197     mem = clear_memory(ctl, mem, dest,
3198                        start_offset, phase->MakeConX(done_offset), phase);
3199   }
3200   if (done_offset < end_offset) { // emit the final 32-bit store
3201     Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset));
3202     adr = phase->transform(adr);
3203     const TypePtr* atp = TypeRawPtr::BOTTOM;
3204     mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
3205     mem = phase->transform(mem);
3206     done_offset += BytesPerInt;
3207   }
3208   assert(done_offset == end_offset, "");
3209   return mem;
3210 }
3211 
3212 //=============================================================================
MemBarNode(Compile * C,int alias_idx,Node * precedent)3213 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
3214   : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
3215     _adr_type(C->get_adr_type(alias_idx)), _kind(Standalone)
3216 #ifdef ASSERT
3217   , _pair_idx(0)
3218 #endif
3219 {
3220   init_class_id(Class_MemBar);
3221   Node* top = C->top();
3222   init_req(TypeFunc::I_O,top);
3223   init_req(TypeFunc::FramePtr,top);
3224   init_req(TypeFunc::ReturnAdr,top);
3225   if (precedent != NULL)
3226     init_req(TypeFunc::Parms, precedent);
3227 }
3228 
3229 //------------------------------cmp--------------------------------------------
hash() const3230 uint MemBarNode::hash() const { return NO_HASH; }
cmp(const Node & n) const3231 bool MemBarNode::cmp( const Node &n ) const {
3232   return (&n == this);          // Always fail except on self
3233 }
3234 
3235 //------------------------------make-------------------------------------------
make(Compile * C,int opcode,int atp,Node * pn)3236 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
3237   switch (opcode) {
3238   case Op_MemBarAcquire:     return new MemBarAcquireNode(C, atp, pn);
3239   case Op_LoadFence:         return new LoadFenceNode(C, atp, pn);
3240   case Op_MemBarRelease:     return new MemBarReleaseNode(C, atp, pn);
3241   case Op_StoreFence:        return new StoreFenceNode(C, atp, pn);
3242   case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn);
3243   case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn);
3244   case Op_MemBarVolatile:    return new MemBarVolatileNode(C, atp, pn);
3245   case Op_MemBarCPUOrder:    return new MemBarCPUOrderNode(C, atp, pn);
3246   case Op_OnSpinWait:        return new OnSpinWaitNode(C, atp, pn);
3247   case Op_Initialize:        return new InitializeNode(C, atp, pn);
3248   case Op_MemBarStoreStore:  return new MemBarStoreStoreNode(C, atp, pn);
3249   default: ShouldNotReachHere(); return NULL;
3250   }
3251 }
3252 
remove(PhaseIterGVN * igvn)3253 void MemBarNode::remove(PhaseIterGVN *igvn) {
3254   if (outcnt() != 2) {
3255     return;
3256   }
3257   if (trailing_store() || trailing_load_store()) {
3258     MemBarNode* leading = leading_membar();
3259     if (leading != NULL) {
3260       assert(leading->trailing_membar() == this, "inconsistent leading/trailing membars");
3261       leading->remove(igvn);
3262     }
3263   }
3264   igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
3265   igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
3266 }
3267 
3268 //------------------------------Ideal------------------------------------------
3269 // Return a node which is more "ideal" than the current node.  Strip out
3270 // control copies
Ideal(PhaseGVN * phase,bool can_reshape)3271 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3272   if (remove_dead_region(phase, can_reshape)) return this;
3273   // Don't bother trying to transform a dead node
3274   if (in(0) && in(0)->is_top()) {
3275     return NULL;
3276   }
3277 
3278   bool progress = false;
3279   // Eliminate volatile MemBars for scalar replaced objects.
3280   if (can_reshape && req() == (Precedent+1)) {
3281     bool eliminate = false;
3282     int opc = Opcode();
3283     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
3284       // Volatile field loads and stores.
3285       Node* my_mem = in(MemBarNode::Precedent);
3286       // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
3287       if ((my_mem != NULL) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
3288         // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
3289         // replace this Precedent (decodeN) with the Load instead.
3290         if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1))  {
3291           Node* load_node = my_mem->in(1);
3292           set_req(MemBarNode::Precedent, load_node);
3293           phase->is_IterGVN()->_worklist.push(my_mem);
3294           my_mem = load_node;
3295         } else {
3296           assert(my_mem->unique_out() == this, "sanity");
3297           del_req(Precedent);
3298           phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
3299           my_mem = NULL;
3300         }
3301         progress = true;
3302       }
3303       if (my_mem != NULL && my_mem->is_Mem()) {
3304         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
3305         // Check for scalar replaced object reference.
3306         if( t_oop != NULL && t_oop->is_known_instance_field() &&
3307             t_oop->offset() != Type::OffsetBot &&
3308             t_oop->offset() != Type::OffsetTop) {
3309           eliminate = true;
3310         }
3311       }
3312     } else if (opc == Op_MemBarRelease) {
3313       // Final field stores.
3314       Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent), phase);
3315       if ((alloc != NULL) && alloc->is_Allocate() &&
3316           alloc->as_Allocate()->does_not_escape_thread()) {
3317         // The allocated object does not escape.
3318         eliminate = true;
3319       }
3320     }
3321     if (eliminate) {
3322       // Replace MemBar projections by its inputs.
3323       PhaseIterGVN* igvn = phase->is_IterGVN();
3324       remove(igvn);
3325       // Must return either the original node (now dead) or a new node
3326       // (Do not return a top here, since that would break the uniqueness of top.)
3327       return new ConINode(TypeInt::ZERO);
3328     }
3329   }
3330   return progress ? this : NULL;
3331 }
3332 
3333 //------------------------------Value------------------------------------------
Value(PhaseGVN * phase) const3334 const Type* MemBarNode::Value(PhaseGVN* phase) const {
3335   if( !in(0) ) return Type::TOP;
3336   if( phase->type(in(0)) == Type::TOP )
3337     return Type::TOP;
3338   return TypeTuple::MEMBAR;
3339 }
3340 
3341 //------------------------------match------------------------------------------
3342 // Construct projections for memory.
match(const ProjNode * proj,const Matcher * m)3343 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
3344   switch (proj->_con) {
3345   case TypeFunc::Control:
3346   case TypeFunc::Memory:
3347     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
3348   }
3349   ShouldNotReachHere();
3350   return NULL;
3351 }
3352 
set_store_pair(MemBarNode * leading,MemBarNode * trailing)3353 void MemBarNode::set_store_pair(MemBarNode* leading, MemBarNode* trailing) {
3354   trailing->_kind = TrailingStore;
3355   leading->_kind = LeadingStore;
3356 #ifdef ASSERT
3357   trailing->_pair_idx = leading->_idx;
3358   leading->_pair_idx = leading->_idx;
3359 #endif
3360 }
3361 
set_load_store_pair(MemBarNode * leading,MemBarNode * trailing)3362 void MemBarNode::set_load_store_pair(MemBarNode* leading, MemBarNode* trailing) {
3363   trailing->_kind = TrailingLoadStore;
3364   leading->_kind = LeadingLoadStore;
3365 #ifdef ASSERT
3366   trailing->_pair_idx = leading->_idx;
3367   leading->_pair_idx = leading->_idx;
3368 #endif
3369 }
3370 
trailing_membar() const3371 MemBarNode* MemBarNode::trailing_membar() const {
3372   ResourceMark rm;
3373   Node* trailing = (Node*)this;
3374   VectorSet seen;
3375   Node_Stack multis(0);
3376   do {
3377     Node* c = trailing;
3378     uint i = 0;
3379     do {
3380       trailing = NULL;
3381       for (; i < c->outcnt(); i++) {
3382         Node* next = c->raw_out(i);
3383         if (next != c && next->is_CFG()) {
3384           if (c->is_MultiBranch()) {
3385             if (multis.node() == c) {
3386               multis.set_index(i+1);
3387             } else {
3388               multis.push(c, i+1);
3389             }
3390           }
3391           trailing = next;
3392           break;
3393         }
3394       }
3395       if (trailing != NULL && !seen.test_set(trailing->_idx)) {
3396         break;
3397       }
3398       while (multis.size() > 0) {
3399         c = multis.node();
3400         i = multis.index();
3401         if (i < c->req()) {
3402           break;
3403         }
3404         multis.pop();
3405       }
3406     } while (multis.size() > 0);
3407   } while (!trailing->is_MemBar() || !trailing->as_MemBar()->trailing());
3408 
3409   MemBarNode* mb = trailing->as_MemBar();
3410   assert((mb->_kind == TrailingStore && _kind == LeadingStore) ||
3411          (mb->_kind == TrailingLoadStore && _kind == LeadingLoadStore), "bad trailing membar");
3412   assert(mb->_pair_idx == _pair_idx, "bad trailing membar");
3413   return mb;
3414 }
3415 
leading_membar() const3416 MemBarNode* MemBarNode::leading_membar() const {
3417   ResourceMark rm;
3418   VectorSet seen;
3419   Node_Stack regions(0);
3420   Node* leading = in(0);
3421   while (leading != NULL && (!leading->is_MemBar() || !leading->as_MemBar()->leading())) {
3422     while (leading == NULL || leading->is_top() || seen.test_set(leading->_idx)) {
3423       leading = NULL;
3424       while (regions.size() > 0 && leading == NULL) {
3425         Node* r = regions.node();
3426         uint i = regions.index();
3427         if (i < r->req()) {
3428           leading = r->in(i);
3429           regions.set_index(i+1);
3430         } else {
3431           regions.pop();
3432         }
3433       }
3434       if (leading == NULL) {
3435         assert(regions.size() == 0, "all paths should have been tried");
3436         return NULL;
3437       }
3438     }
3439     if (leading->is_Region()) {
3440       regions.push(leading, 2);
3441       leading = leading->in(1);
3442     } else {
3443       leading = leading->in(0);
3444     }
3445   }
3446 #ifdef ASSERT
3447   Unique_Node_List wq;
3448   wq.push((Node*)this);
3449   uint found = 0;
3450   for (uint i = 0; i < wq.size(); i++) {
3451     Node* n = wq.at(i);
3452     if (n->is_Region()) {
3453       for (uint j = 1; j < n->req(); j++) {
3454         Node* in = n->in(j);
3455         if (in != NULL && !in->is_top()) {
3456           wq.push(in);
3457         }
3458       }
3459     } else {
3460       if (n->is_MemBar() && n->as_MemBar()->leading()) {
3461         assert(n == leading, "consistency check failed");
3462         found++;
3463       } else {
3464         Node* in = n->in(0);
3465         if (in != NULL && !in->is_top()) {
3466           wq.push(in);
3467         }
3468       }
3469     }
3470   }
3471   assert(found == 1 || (found == 0 && leading == NULL), "consistency check failed");
3472 #endif
3473   if (leading == NULL) {
3474     return NULL;
3475   }
3476   MemBarNode* mb = leading->as_MemBar();
3477   assert((mb->_kind == LeadingStore && _kind == TrailingStore) ||
3478          (mb->_kind == LeadingLoadStore && _kind == TrailingLoadStore), "bad leading membar");
3479   assert(mb->_pair_idx == _pair_idx, "bad leading membar");
3480   return mb;
3481 }
3482 
3483 //===========================InitializeNode====================================
3484 // SUMMARY:
3485 // This node acts as a memory barrier on raw memory, after some raw stores.
3486 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
3487 // The Initialize can 'capture' suitably constrained stores as raw inits.
3488 // It can coalesce related raw stores into larger units (called 'tiles').
3489 // It can avoid zeroing new storage for memory units which have raw inits.
3490 // At macro-expansion, it is marked 'complete', and does not optimize further.
3491 //
3492 // EXAMPLE:
3493 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
3494 //   ctl = incoming control; mem* = incoming memory
3495 // (Note:  A star * on a memory edge denotes I/O and other standard edges.)
3496 // First allocate uninitialized memory and fill in the header:
3497 //   alloc = (Allocate ctl mem* 16 #short[].klass ...)
3498 //   ctl := alloc.Control; mem* := alloc.Memory*
3499 //   rawmem = alloc.Memory; rawoop = alloc.RawAddress
3500 // Then initialize to zero the non-header parts of the raw memory block:
3501 //   init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
3502 //   ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
3503 // After the initialize node executes, the object is ready for service:
3504 //   oop := (CheckCastPP init.Control alloc.RawAddress #short[])
3505 // Suppose its body is immediately initialized as {1,2}:
3506 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3507 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3508 //   mem.SLICE(#short[*]) := store2
3509 //
3510 // DETAILS:
3511 // An InitializeNode collects and isolates object initialization after
3512 // an AllocateNode and before the next possible safepoint.  As a
3513 // memory barrier (MemBarNode), it keeps critical stores from drifting
3514 // down past any safepoint or any publication of the allocation.
3515 // Before this barrier, a newly-allocated object may have uninitialized bits.
3516 // After this barrier, it may be treated as a real oop, and GC is allowed.
3517 //
3518 // The semantics of the InitializeNode include an implicit zeroing of
3519 // the new object from object header to the end of the object.
3520 // (The object header and end are determined by the AllocateNode.)
3521 //
3522 // Certain stores may be added as direct inputs to the InitializeNode.
3523 // These stores must update raw memory, and they must be to addresses
3524 // derived from the raw address produced by AllocateNode, and with
3525 // a constant offset.  They must be ordered by increasing offset.
3526 // The first one is at in(RawStores), the last at in(req()-1).
3527 // Unlike most memory operations, they are not linked in a chain,
3528 // but are displayed in parallel as users of the rawmem output of
3529 // the allocation.
3530 //
3531 // (See comments in InitializeNode::capture_store, which continue
3532 // the example given above.)
3533 //
3534 // When the associated Allocate is macro-expanded, the InitializeNode
3535 // may be rewritten to optimize collected stores.  A ClearArrayNode
3536 // may also be created at that point to represent any required zeroing.
3537 // The InitializeNode is then marked 'complete', prohibiting further
3538 // capturing of nearby memory operations.
3539 //
3540 // During macro-expansion, all captured initializations which store
3541 // constant values of 32 bits or smaller are coalesced (if advantageous)
3542 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
3543 // initialized in fewer memory operations.  Memory words which are
3544 // covered by neither tiles nor non-constant stores are pre-zeroed
3545 // by explicit stores of zero.  (The code shape happens to do all
3546 // zeroing first, then all other stores, with both sequences occurring
3547 // in order of ascending offsets.)
3548 //
3549 // Alternatively, code may be inserted between an AllocateNode and its
3550 // InitializeNode, to perform arbitrary initialization of the new object.
3551 // E.g., the object copying intrinsics insert complex data transfers here.
3552 // The initialization must then be marked as 'complete' disable the
3553 // built-in zeroing semantics and the collection of initializing stores.
3554 //
3555 // While an InitializeNode is incomplete, reads from the memory state
3556 // produced by it are optimizable if they match the control edge and
3557 // new oop address associated with the allocation/initialization.
3558 // They return a stored value (if the offset matches) or else zero.
3559 // A write to the memory state, if it matches control and address,
3560 // and if it is to a constant offset, may be 'captured' by the
3561 // InitializeNode.  It is cloned as a raw memory operation and rewired
3562 // inside the initialization, to the raw oop produced by the allocation.
3563 // Operations on addresses which are provably distinct (e.g., to
3564 // other AllocateNodes) are allowed to bypass the initialization.
3565 //
3566 // The effect of all this is to consolidate object initialization
3567 // (both arrays and non-arrays, both piecewise and bulk) into a
3568 // single location, where it can be optimized as a unit.
3569 //
3570 // Only stores with an offset less than TrackedInitializationLimit words
3571 // will be considered for capture by an InitializeNode.  This puts a
3572 // reasonable limit on the complexity of optimized initializations.
3573 
3574 //---------------------------InitializeNode------------------------------------
InitializeNode(Compile * C,int adr_type,Node * rawoop)3575 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
3576   : MemBarNode(C, adr_type, rawoop),
3577     _is_complete(Incomplete), _does_not_escape(false)
3578 {
3579   init_class_id(Class_Initialize);
3580 
3581   assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
3582   assert(in(RawAddress) == rawoop, "proper init");
3583   // Note:  allocation() can be NULL, for secondary initialization barriers
3584 }
3585 
3586 // Since this node is not matched, it will be processed by the
3587 // register allocator.  Declare that there are no constraints
3588 // on the allocation of the RawAddress edge.
in_RegMask(uint idx) const3589 const RegMask &InitializeNode::in_RegMask(uint idx) const {
3590   // This edge should be set to top, by the set_complete.  But be conservative.
3591   if (idx == InitializeNode::RawAddress)
3592     return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
3593   return RegMask::Empty;
3594 }
3595 
memory(uint alias_idx)3596 Node* InitializeNode::memory(uint alias_idx) {
3597   Node* mem = in(Memory);
3598   if (mem->is_MergeMem()) {
3599     return mem->as_MergeMem()->memory_at(alias_idx);
3600   } else {
3601     // incoming raw memory is not split
3602     return mem;
3603   }
3604 }
3605 
is_non_zero()3606 bool InitializeNode::is_non_zero() {
3607   if (is_complete())  return false;
3608   remove_extra_zeroes();
3609   return (req() > RawStores);
3610 }
3611 
set_complete(PhaseGVN * phase)3612 void InitializeNode::set_complete(PhaseGVN* phase) {
3613   assert(!is_complete(), "caller responsibility");
3614   _is_complete = Complete;
3615 
3616   // After this node is complete, it contains a bunch of
3617   // raw-memory initializations.  There is no need for
3618   // it to have anything to do with non-raw memory effects.
3619   // Therefore, tell all non-raw users to re-optimize themselves,
3620   // after skipping the memory effects of this initialization.
3621   PhaseIterGVN* igvn = phase->is_IterGVN();
3622   if (igvn)  igvn->add_users_to_worklist(this);
3623 }
3624 
3625 // convenience function
3626 // return false if the init contains any stores already
maybe_set_complete(PhaseGVN * phase)3627 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
3628   InitializeNode* init = initialization();
3629   if (init == NULL || init->is_complete())  return false;
3630   init->remove_extra_zeroes();
3631   // for now, if this allocation has already collected any inits, bail:
3632   if (init->is_non_zero())  return false;
3633   init->set_complete(phase);
3634   return true;
3635 }
3636 
remove_extra_zeroes()3637 void InitializeNode::remove_extra_zeroes() {
3638   if (req() == RawStores)  return;
3639   Node* zmem = zero_memory();
3640   uint fill = RawStores;
3641   for (uint i = fill; i < req(); i++) {
3642     Node* n = in(i);
3643     if (n->is_top() || n == zmem)  continue;  // skip
3644     if (fill < i)  set_req(fill, n);          // compact
3645     ++fill;
3646   }
3647   // delete any empty spaces created:
3648   while (fill < req()) {
3649     del_req(fill);
3650   }
3651 }
3652 
3653 // Helper for remembering which stores go with which offsets.
get_store_offset(Node * st,PhaseTransform * phase)3654 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
3655   if (!st->is_Store())  return -1;  // can happen to dead code via subsume_node
3656   intptr_t offset = -1;
3657   Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
3658                                                phase, offset);
3659   if (base == NULL)     return -1;  // something is dead,
3660   if (offset < 0)       return -1;  //        dead, dead
3661   return offset;
3662 }
3663 
3664 // Helper for proving that an initialization expression is
3665 // "simple enough" to be folded into an object initialization.
3666 // Attempts to prove that a store's initial value 'n' can be captured
3667 // within the initialization without creating a vicious cycle, such as:
3668 //     { Foo p = new Foo(); p.next = p; }
3669 // True for constants and parameters and small combinations thereof.
detect_init_independence(Node * value,PhaseGVN * phase)3670 bool InitializeNode::detect_init_independence(Node* value, PhaseGVN* phase) {
3671   ResourceMark rm;
3672   Unique_Node_List worklist;
3673   worklist.push(value);
3674 
3675   uint complexity_limit = 20;
3676   for (uint j = 0; j < worklist.size(); j++) {
3677     if (j >= complexity_limit) {
3678       return false;  // Bail out if processed too many nodes
3679     }
3680 
3681     Node* n = worklist.at(j);
3682     if (n == NULL)      continue;   // (can this really happen?)
3683     if (n->is_Proj())   n = n->in(0);
3684     if (n == this)      return false;  // found a cycle
3685     if (n->is_Con())    continue;
3686     if (n->is_Start())  continue;   // params, etc., are OK
3687     if (n->is_Root())   continue;   // even better
3688 
3689     // There cannot be any dependency if 'n' is a CFG node that dominates the current allocation
3690     if (n->is_CFG() && phase->is_dominator(n, allocation())) {
3691       continue;
3692     }
3693 
3694     Node* ctl = n->in(0);
3695     if (ctl != NULL && !ctl->is_top()) {
3696       if (ctl->is_Proj())  ctl = ctl->in(0);
3697       if (ctl == this)  return false;
3698 
3699       // If we already know that the enclosing memory op is pinned right after
3700       // the init, then any control flow that the store has picked up
3701       // must have preceded the init, or else be equal to the init.
3702       // Even after loop optimizations (which might change control edges)
3703       // a store is never pinned *before* the availability of its inputs.
3704       if (!MemNode::all_controls_dominate(n, this))
3705         return false;                  // failed to prove a good control
3706     }
3707 
3708     // Check data edges for possible dependencies on 'this'.
3709     for (uint i = 1; i < n->req(); i++) {
3710       Node* m = n->in(i);
3711       if (m == NULL || m == n || m->is_top())  continue;
3712 
3713       // Only process data inputs once
3714       worklist.push(m);
3715     }
3716   }
3717 
3718   return true;
3719 }
3720 
3721 // Here are all the checks a Store must pass before it can be moved into
3722 // an initialization.  Returns zero if a check fails.
3723 // On success, returns the (constant) offset to which the store applies,
3724 // within the initialized memory.
can_capture_store(StoreNode * st,PhaseGVN * phase,bool can_reshape)3725 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseGVN* phase, bool can_reshape) {
3726   const int FAIL = 0;
3727   if (st->req() != MemNode::ValueIn + 1)
3728     return FAIL;                // an inscrutable StoreNode (card mark?)
3729   Node* ctl = st->in(MemNode::Control);
3730   if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
3731     return FAIL;                // must be unconditional after the initialization
3732   Node* mem = st->in(MemNode::Memory);
3733   if (!(mem->is_Proj() && mem->in(0) == this))
3734     return FAIL;                // must not be preceded by other stores
3735   Node* adr = st->in(MemNode::Address);
3736   intptr_t offset;
3737   AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
3738   if (alloc == NULL)
3739     return FAIL;                // inscrutable address
3740   if (alloc != allocation())
3741     return FAIL;                // wrong allocation!  (store needs to float up)
3742   int size_in_bytes = st->memory_size();
3743   if ((size_in_bytes != 0) && (offset % size_in_bytes) != 0) {
3744     return FAIL;                // mismatched access
3745   }
3746   Node* val = st->in(MemNode::ValueIn);
3747 
3748   if (!detect_init_independence(val, phase))
3749     return FAIL;                // stored value must be 'simple enough'
3750 
3751   // The Store can be captured only if nothing after the allocation
3752   // and before the Store is using the memory location that the store
3753   // overwrites.
3754   bool failed = false;
3755   // If is_complete_with_arraycopy() is true the shape of the graph is
3756   // well defined and is safe so no need for extra checks.
3757   if (!is_complete_with_arraycopy()) {
3758     // We are going to look at each use of the memory state following
3759     // the allocation to make sure nothing reads the memory that the
3760     // Store writes.
3761     const TypePtr* t_adr = phase->type(adr)->isa_ptr();
3762     int alias_idx = phase->C->get_alias_index(t_adr);
3763     ResourceMark rm;
3764     Unique_Node_List mems;
3765     mems.push(mem);
3766     Node* unique_merge = NULL;
3767     for (uint next = 0; next < mems.size(); ++next) {
3768       Node *m  = mems.at(next);
3769       for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
3770         Node *n = m->fast_out(j);
3771         if (n->outcnt() == 0) {
3772           continue;
3773         }
3774         if (n == st) {
3775           continue;
3776         } else if (n->in(0) != NULL && n->in(0) != ctl) {
3777           // If the control of this use is different from the control
3778           // of the Store which is right after the InitializeNode then
3779           // this node cannot be between the InitializeNode and the
3780           // Store.
3781           continue;
3782         } else if (n->is_MergeMem()) {
3783           if (n->as_MergeMem()->memory_at(alias_idx) == m) {
3784             // We can hit a MergeMemNode (that will likely go away
3785             // later) that is a direct use of the memory state
3786             // following the InitializeNode on the same slice as the
3787             // store node that we'd like to capture. We need to check
3788             // the uses of the MergeMemNode.
3789             mems.push(n);
3790           }
3791         } else if (n->is_Mem()) {
3792           Node* other_adr = n->in(MemNode::Address);
3793           if (other_adr == adr) {
3794             failed = true;
3795             break;
3796           } else {
3797             const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
3798             if (other_t_adr != NULL) {
3799               int other_alias_idx = phase->C->get_alias_index(other_t_adr);
3800               if (other_alias_idx == alias_idx) {
3801                 // A load from the same memory slice as the store right
3802                 // after the InitializeNode. We check the control of the
3803                 // object/array that is loaded from. If it's the same as
3804                 // the store control then we cannot capture the store.
3805                 assert(!n->is_Store(), "2 stores to same slice on same control?");
3806                 Node* base = other_adr;
3807                 assert(base->is_AddP(), "should be addp but is %s", base->Name());
3808                 base = base->in(AddPNode::Base);
3809                 if (base != NULL) {
3810                   base = base->uncast();
3811                   if (base->is_Proj() && base->in(0) == alloc) {
3812                     failed = true;
3813                     break;
3814                   }
3815                 }
3816               }
3817             }
3818           }
3819         } else {
3820           failed = true;
3821           break;
3822         }
3823       }
3824     }
3825   }
3826   if (failed) {
3827     if (!can_reshape) {
3828       // We decided we couldn't capture the store during parsing. We
3829       // should try again during the next IGVN once the graph is
3830       // cleaner.
3831       phase->C->record_for_igvn(st);
3832     }
3833     return FAIL;
3834   }
3835 
3836   return offset;                // success
3837 }
3838 
3839 // Find the captured store in(i) which corresponds to the range
3840 // [start..start+size) in the initialized object.
3841 // If there is one, return its index i.  If there isn't, return the
3842 // negative of the index where it should be inserted.
3843 // Return 0 if the queried range overlaps an initialization boundary
3844 // or if dead code is encountered.
3845 // If size_in_bytes is zero, do not bother with overlap checks.
captured_store_insertion_point(intptr_t start,int size_in_bytes,PhaseTransform * phase)3846 int InitializeNode::captured_store_insertion_point(intptr_t start,
3847                                                    int size_in_bytes,
3848                                                    PhaseTransform* phase) {
3849   const int FAIL = 0, MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize);
3850 
3851   if (is_complete())
3852     return FAIL;                // arraycopy got here first; punt
3853 
3854   assert(allocation() != NULL, "must be present");
3855 
3856   // no negatives, no header fields:
3857   if (start < (intptr_t) allocation()->minimum_header_size())  return FAIL;
3858 
3859   // after a certain size, we bail out on tracking all the stores:
3860   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3861   if (start >= ti_limit)  return FAIL;
3862 
3863   for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
3864     if (i >= limit)  return -(int)i; // not found; here is where to put it
3865 
3866     Node*    st     = in(i);
3867     intptr_t st_off = get_store_offset(st, phase);
3868     if (st_off < 0) {
3869       if (st != zero_memory()) {
3870         return FAIL;            // bail out if there is dead garbage
3871       }
3872     } else if (st_off > start) {
3873       // ...we are done, since stores are ordered
3874       if (st_off < start + size_in_bytes) {
3875         return FAIL;            // the next store overlaps
3876       }
3877       return -(int)i;           // not found; here is where to put it
3878     } else if (st_off < start) {
3879       assert(st->as_Store()->memory_size() <= MAX_STORE, "");
3880       if (size_in_bytes != 0 &&
3881           start < st_off + MAX_STORE &&
3882           start < st_off + st->as_Store()->memory_size()) {
3883         return FAIL;            // the previous store overlaps
3884       }
3885     } else {
3886       if (size_in_bytes != 0 &&
3887           st->as_Store()->memory_size() != size_in_bytes) {
3888         return FAIL;            // mismatched store size
3889       }
3890       return i;
3891     }
3892 
3893     ++i;
3894   }
3895 }
3896 
3897 // Look for a captured store which initializes at the offset 'start'
3898 // with the given size.  If there is no such store, and no other
3899 // initialization interferes, then return zero_memory (the memory
3900 // projection of the AllocateNode).
find_captured_store(intptr_t start,int size_in_bytes,PhaseTransform * phase)3901 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
3902                                           PhaseTransform* phase) {
3903   assert(stores_are_sane(phase), "");
3904   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3905   if (i == 0) {
3906     return NULL;                // something is dead
3907   } else if (i < 0) {
3908     return zero_memory();       // just primordial zero bits here
3909   } else {
3910     Node* st = in(i);           // here is the store at this position
3911     assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
3912     return st;
3913   }
3914 }
3915 
3916 // Create, as a raw pointer, an address within my new object at 'offset'.
make_raw_address(intptr_t offset,PhaseTransform * phase)3917 Node* InitializeNode::make_raw_address(intptr_t offset,
3918                                        PhaseTransform* phase) {
3919   Node* addr = in(RawAddress);
3920   if (offset != 0) {
3921     Compile* C = phase->C;
3922     addr = phase->transform( new AddPNode(C->top(), addr,
3923                                                  phase->MakeConX(offset)) );
3924   }
3925   return addr;
3926 }
3927 
3928 // Clone the given store, converting it into a raw store
3929 // initializing a field or element of my new object.
3930 // Caller is responsible for retiring the original store,
3931 // with subsume_node or the like.
3932 //
3933 // From the example above InitializeNode::InitializeNode,
3934 // here are the old stores to be captured:
3935 //   store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3936 //   store2 = (StoreC init.Control store1      (+ oop 14) 2)
3937 //
3938 // Here is the changed code; note the extra edges on init:
3939 //   alloc = (Allocate ...)
3940 //   rawoop = alloc.RawAddress
3941 //   rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
3942 //   rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
3943 //   init = (Initialize alloc.Control alloc.Memory rawoop
3944 //                      rawstore1 rawstore2)
3945 //
capture_store(StoreNode * st,intptr_t start,PhaseGVN * phase,bool can_reshape)3946 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
3947                                     PhaseGVN* phase, bool can_reshape) {
3948   assert(stores_are_sane(phase), "");
3949 
3950   if (start < 0)  return NULL;
3951   assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
3952 
3953   Compile* C = phase->C;
3954   int size_in_bytes = st->memory_size();
3955   int i = captured_store_insertion_point(start, size_in_bytes, phase);
3956   if (i == 0)  return NULL;     // bail out
3957   Node* prev_mem = NULL;        // raw memory for the captured store
3958   if (i > 0) {
3959     prev_mem = in(i);           // there is a pre-existing store under this one
3960     set_req(i, C->top());       // temporarily disconnect it
3961     // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
3962   } else {
3963     i = -i;                     // no pre-existing store
3964     prev_mem = zero_memory();   // a slice of the newly allocated object
3965     if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
3966       set_req(--i, C->top());   // reuse this edge; it has been folded away
3967     else
3968       ins_req(i, C->top());     // build a new edge
3969   }
3970   Node* new_st = st->clone();
3971   new_st->set_req(MemNode::Control, in(Control));
3972   new_st->set_req(MemNode::Memory,  prev_mem);
3973   new_st->set_req(MemNode::Address, make_raw_address(start, phase));
3974   new_st = phase->transform(new_st);
3975 
3976   // At this point, new_st might have swallowed a pre-existing store
3977   // at the same offset, or perhaps new_st might have disappeared,
3978   // if it redundantly stored the same value (or zero to fresh memory).
3979 
3980   // In any case, wire it in:
3981   PhaseIterGVN* igvn = phase->is_IterGVN();
3982   if (igvn) {
3983     igvn->rehash_node_delayed(this);
3984   }
3985   set_req(i, new_st);
3986 
3987   // The caller may now kill the old guy.
3988   DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
3989   assert(check_st == new_st || check_st == NULL, "must be findable");
3990   assert(!is_complete(), "");
3991   return new_st;
3992 }
3993 
store_constant(jlong * tiles,int num_tiles,intptr_t st_off,int st_size,jlong con)3994 static bool store_constant(jlong* tiles, int num_tiles,
3995                            intptr_t st_off, int st_size,
3996                            jlong con) {
3997   if ((st_off & (st_size-1)) != 0)
3998     return false;               // strange store offset (assume size==2**N)
3999   address addr = (address)tiles + st_off;
4000   assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
4001   switch (st_size) {
4002   case sizeof(jbyte):  *(jbyte*) addr = (jbyte) con; break;
4003   case sizeof(jchar):  *(jchar*) addr = (jchar) con; break;
4004   case sizeof(jint):   *(jint*)  addr = (jint)  con; break;
4005   case sizeof(jlong):  *(jlong*) addr = (jlong) con; break;
4006   default: return false;        // strange store size (detect size!=2**N here)
4007   }
4008   return true;                  // return success to caller
4009 }
4010 
4011 // Coalesce subword constants into int constants and possibly
4012 // into long constants.  The goal, if the CPU permits,
4013 // is to initialize the object with a small number of 64-bit tiles.
4014 // Also, convert floating-point constants to bit patterns.
4015 // Non-constants are not relevant to this pass.
4016 //
4017 // In terms of the running example on InitializeNode::InitializeNode
4018 // and InitializeNode::capture_store, here is the transformation
4019 // of rawstore1 and rawstore2 into rawstore12:
4020 //   alloc = (Allocate ...)
4021 //   rawoop = alloc.RawAddress
4022 //   tile12 = 0x00010002
4023 //   rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
4024 //   init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
4025 //
4026 void
coalesce_subword_stores(intptr_t header_size,Node * size_in_bytes,PhaseGVN * phase)4027 InitializeNode::coalesce_subword_stores(intptr_t header_size,
4028                                         Node* size_in_bytes,
4029                                         PhaseGVN* phase) {
4030   Compile* C = phase->C;
4031 
4032   assert(stores_are_sane(phase), "");
4033   // Note:  After this pass, they are not completely sane,
4034   // since there may be some overlaps.
4035 
4036   int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
4037 
4038   intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
4039   intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
4040   size_limit = MIN2(size_limit, ti_limit);
4041   size_limit = align_up(size_limit, BytesPerLong);
4042   int num_tiles = size_limit / BytesPerLong;
4043 
4044   // allocate space for the tile map:
4045   const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
4046   jlong  tiles_buf[small_len];
4047   Node*  nodes_buf[small_len];
4048   jlong  inits_buf[small_len];
4049   jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
4050                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
4051   Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
4052                   : NEW_RESOURCE_ARRAY(Node*, num_tiles));
4053   jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
4054                   : NEW_RESOURCE_ARRAY(jlong, num_tiles));
4055   // tiles: exact bitwise model of all primitive constants
4056   // nodes: last constant-storing node subsumed into the tiles model
4057   // inits: which bytes (in each tile) are touched by any initializations
4058 
4059   //// Pass A: Fill in the tile model with any relevant stores.
4060 
4061   Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
4062   Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
4063   Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
4064   Node* zmem = zero_memory(); // initially zero memory state
4065   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
4066     Node* st = in(i);
4067     intptr_t st_off = get_store_offset(st, phase);
4068 
4069     // Figure out the store's offset and constant value:
4070     if (st_off < header_size)             continue; //skip (ignore header)
4071     if (st->in(MemNode::Memory) != zmem)  continue; //skip (odd store chain)
4072     int st_size = st->as_Store()->memory_size();
4073     if (st_off + st_size > size_limit)    break;
4074 
4075     // Record which bytes are touched, whether by constant or not.
4076     if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
4077       continue;                 // skip (strange store size)
4078 
4079     const Type* val = phase->type(st->in(MemNode::ValueIn));
4080     if (!val->singleton())                continue; //skip (non-con store)
4081     BasicType type = val->basic_type();
4082 
4083     jlong con = 0;
4084     switch (type) {
4085     case T_INT:    con = val->is_int()->get_con();  break;
4086     case T_LONG:   con = val->is_long()->get_con(); break;
4087     case T_FLOAT:  con = jint_cast(val->getf());    break;
4088     case T_DOUBLE: con = jlong_cast(val->getd());   break;
4089     default:                              continue; //skip (odd store type)
4090     }
4091 
4092     if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
4093         st->Opcode() == Op_StoreL) {
4094       continue;                 // This StoreL is already optimal.
4095     }
4096 
4097     // Store down the constant.
4098     store_constant(tiles, num_tiles, st_off, st_size, con);
4099 
4100     intptr_t j = st_off >> LogBytesPerLong;
4101 
4102     if (type == T_INT && st_size == BytesPerInt
4103         && (st_off & BytesPerInt) == BytesPerInt) {
4104       jlong lcon = tiles[j];
4105       if (!Matcher::isSimpleConstant64(lcon) &&
4106           st->Opcode() == Op_StoreI) {
4107         // This StoreI is already optimal by itself.
4108         jint* intcon = (jint*) &tiles[j];
4109         intcon[1] = 0;  // undo the store_constant()
4110 
4111         // If the previous store is also optimal by itself, back up and
4112         // undo the action of the previous loop iteration... if we can.
4113         // But if we can't, just let the previous half take care of itself.
4114         st = nodes[j];
4115         st_off -= BytesPerInt;
4116         con = intcon[0];
4117         if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
4118           assert(st_off >= header_size, "still ignoring header");
4119           assert(get_store_offset(st, phase) == st_off, "must be");
4120           assert(in(i-1) == zmem, "must be");
4121           DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
4122           assert(con == tcon->is_int()->get_con(), "must be");
4123           // Undo the effects of the previous loop trip, which swallowed st:
4124           intcon[0] = 0;        // undo store_constant()
4125           set_req(i-1, st);     // undo set_req(i, zmem)
4126           nodes[j] = NULL;      // undo nodes[j] = st
4127           --old_subword;        // undo ++old_subword
4128         }
4129         continue;               // This StoreI is already optimal.
4130       }
4131     }
4132 
4133     // This store is not needed.
4134     set_req(i, zmem);
4135     nodes[j] = st;              // record for the moment
4136     if (st_size < BytesPerLong) // something has changed
4137           ++old_subword;        // includes int/float, but who's counting...
4138     else  ++old_long;
4139   }
4140 
4141   if ((old_subword + old_long) == 0)
4142     return;                     // nothing more to do
4143 
4144   //// Pass B: Convert any non-zero tiles into optimal constant stores.
4145   // Be sure to insert them before overlapping non-constant stores.
4146   // (E.g., byte[] x = { 1,2,y,4 }  =>  x[int 0] = 0x01020004, x[2]=y.)
4147   for (int j = 0; j < num_tiles; j++) {
4148     jlong con  = tiles[j];
4149     jlong init = inits[j];
4150     if (con == 0)  continue;
4151     jint con0,  con1;           // split the constant, address-wise
4152     jint init0, init1;          // split the init map, address-wise
4153     { union { jlong con; jint intcon[2]; } u;
4154       u.con = con;
4155       con0  = u.intcon[0];
4156       con1  = u.intcon[1];
4157       u.con = init;
4158       init0 = u.intcon[0];
4159       init1 = u.intcon[1];
4160     }
4161 
4162     Node* old = nodes[j];
4163     assert(old != NULL, "need the prior store");
4164     intptr_t offset = (j * BytesPerLong);
4165 
4166     bool split = !Matcher::isSimpleConstant64(con);
4167 
4168     if (offset < header_size) {
4169       assert(offset + BytesPerInt >= header_size, "second int counts");
4170       assert(*(jint*)&tiles[j] == 0, "junk in header");
4171       split = true;             // only the second word counts
4172       // Example:  int a[] = { 42 ... }
4173     } else if (con0 == 0 && init0 == -1) {
4174       split = true;             // first word is covered by full inits
4175       // Example:  int a[] = { ... foo(), 42 ... }
4176     } else if (con1 == 0 && init1 == -1) {
4177       split = true;             // second word is covered by full inits
4178       // Example:  int a[] = { ... 42, foo() ... }
4179     }
4180 
4181     // Here's a case where init0 is neither 0 nor -1:
4182     //   byte a[] = { ... 0,0,foo(),0,  0,0,0,42 ... }
4183     // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
4184     // In this case the tile is not split; it is (jlong)42.
4185     // The big tile is stored down, and then the foo() value is inserted.
4186     // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
4187 
4188     Node* ctl = old->in(MemNode::Control);
4189     Node* adr = make_raw_address(offset, phase);
4190     const TypePtr* atp = TypeRawPtr::BOTTOM;
4191 
4192     // One or two coalesced stores to plop down.
4193     Node*    st[2];
4194     intptr_t off[2];
4195     int  nst = 0;
4196     if (!split) {
4197       ++new_long;
4198       off[nst] = offset;
4199       st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4200                                   phase->longcon(con), T_LONG, MemNode::unordered);
4201     } else {
4202       // Omit either if it is a zero.
4203       if (con0 != 0) {
4204         ++new_int;
4205         off[nst]  = offset;
4206         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4207                                     phase->intcon(con0), T_INT, MemNode::unordered);
4208       }
4209       if (con1 != 0) {
4210         ++new_int;
4211         offset += BytesPerInt;
4212         adr = make_raw_address(offset, phase);
4213         off[nst]  = offset;
4214         st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
4215                                     phase->intcon(con1), T_INT, MemNode::unordered);
4216       }
4217     }
4218 
4219     // Insert second store first, then the first before the second.
4220     // Insert each one just before any overlapping non-constant stores.
4221     while (nst > 0) {
4222       Node* st1 = st[--nst];
4223       C->copy_node_notes_to(st1, old);
4224       st1 = phase->transform(st1);
4225       offset = off[nst];
4226       assert(offset >= header_size, "do not smash header");
4227       int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
4228       guarantee(ins_idx != 0, "must re-insert constant store");
4229       if (ins_idx < 0)  ins_idx = -ins_idx;  // never overlap
4230       if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
4231         set_req(--ins_idx, st1);
4232       else
4233         ins_req(ins_idx, st1);
4234     }
4235   }
4236 
4237   if (PrintCompilation && WizardMode)
4238     tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
4239                   old_subword, old_long, new_int, new_long);
4240   if (C->log() != NULL)
4241     C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
4242                    old_subword, old_long, new_int, new_long);
4243 
4244   // Clean up any remaining occurrences of zmem:
4245   remove_extra_zeroes();
4246 }
4247 
4248 // Explore forward from in(start) to find the first fully initialized
4249 // word, and return its offset.  Skip groups of subword stores which
4250 // together initialize full words.  If in(start) is itself part of a
4251 // fully initialized word, return the offset of in(start).  If there
4252 // are no following full-word stores, or if something is fishy, return
4253 // a negative value.
find_next_fullword_store(uint start,PhaseGVN * phase)4254 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
4255   int       int_map = 0;
4256   intptr_t  int_map_off = 0;
4257   const int FULL_MAP = right_n_bits(BytesPerInt);  // the int_map we hope for
4258 
4259   for (uint i = start, limit = req(); i < limit; i++) {
4260     Node* st = in(i);
4261 
4262     intptr_t st_off = get_store_offset(st, phase);
4263     if (st_off < 0)  break;  // return conservative answer
4264 
4265     int st_size = st->as_Store()->memory_size();
4266     if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
4267       return st_off;            // we found a complete word init
4268     }
4269 
4270     // update the map:
4271 
4272     intptr_t this_int_off = align_down(st_off, BytesPerInt);
4273     if (this_int_off != int_map_off) {
4274       // reset the map:
4275       int_map = 0;
4276       int_map_off = this_int_off;
4277     }
4278 
4279     int subword_off = st_off - this_int_off;
4280     int_map |= right_n_bits(st_size) << subword_off;
4281     if ((int_map & FULL_MAP) == FULL_MAP) {
4282       return this_int_off;      // we found a complete word init
4283     }
4284 
4285     // Did this store hit or cross the word boundary?
4286     intptr_t next_int_off = align_down(st_off + st_size, BytesPerInt);
4287     if (next_int_off == this_int_off + BytesPerInt) {
4288       // We passed the current int, without fully initializing it.
4289       int_map_off = next_int_off;
4290       int_map >>= BytesPerInt;
4291     } else if (next_int_off > this_int_off + BytesPerInt) {
4292       // We passed the current and next int.
4293       return this_int_off + BytesPerInt;
4294     }
4295   }
4296 
4297   return -1;
4298 }
4299 
4300 
4301 // Called when the associated AllocateNode is expanded into CFG.
4302 // At this point, we may perform additional optimizations.
4303 // Linearize the stores by ascending offset, to make memory
4304 // activity as coherent as possible.
complete_stores(Node * rawctl,Node * rawmem,Node * rawptr,intptr_t header_size,Node * size_in_bytes,PhaseIterGVN * phase)4305 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
4306                                       intptr_t header_size,
4307                                       Node* size_in_bytes,
4308                                       PhaseIterGVN* phase) {
4309   assert(!is_complete(), "not already complete");
4310   assert(stores_are_sane(phase), "");
4311   assert(allocation() != NULL, "must be present");
4312 
4313   remove_extra_zeroes();
4314 
4315   if (ReduceFieldZeroing || ReduceBulkZeroing)
4316     // reduce instruction count for common initialization patterns
4317     coalesce_subword_stores(header_size, size_in_bytes, phase);
4318 
4319   Node* zmem = zero_memory();   // initially zero memory state
4320   Node* inits = zmem;           // accumulating a linearized chain of inits
4321   #ifdef ASSERT
4322   intptr_t first_offset = allocation()->minimum_header_size();
4323   intptr_t last_init_off = first_offset;  // previous init offset
4324   intptr_t last_init_end = first_offset;  // previous init offset+size
4325   intptr_t last_tile_end = first_offset;  // previous tile offset+size
4326   #endif
4327   intptr_t zeroes_done = header_size;
4328 
4329   bool do_zeroing = true;       // we might give up if inits are very sparse
4330   int  big_init_gaps = 0;       // how many large gaps have we seen?
4331 
4332   if (UseTLAB && ZeroTLAB)  do_zeroing = false;
4333   if (!ReduceFieldZeroing && !ReduceBulkZeroing)  do_zeroing = false;
4334 
4335   for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
4336     Node* st = in(i);
4337     intptr_t st_off = get_store_offset(st, phase);
4338     if (st_off < 0)
4339       break;                    // unknown junk in the inits
4340     if (st->in(MemNode::Memory) != zmem)
4341       break;                    // complicated store chains somehow in list
4342 
4343     int st_size = st->as_Store()->memory_size();
4344     intptr_t next_init_off = st_off + st_size;
4345 
4346     if (do_zeroing && zeroes_done < next_init_off) {
4347       // See if this store needs a zero before it or under it.
4348       intptr_t zeroes_needed = st_off;
4349 
4350       if (st_size < BytesPerInt) {
4351         // Look for subword stores which only partially initialize words.
4352         // If we find some, we must lay down some word-level zeroes first,
4353         // underneath the subword stores.
4354         //
4355         // Examples:
4356         //   byte[] a = { p,q,r,s }  =>  a[0]=p,a[1]=q,a[2]=r,a[3]=s
4357         //   byte[] a = { x,y,0,0 }  =>  a[0..3] = 0, a[0]=x,a[1]=y
4358         //   byte[] a = { 0,0,z,0 }  =>  a[0..3] = 0, a[2]=z
4359         //
4360         // Note:  coalesce_subword_stores may have already done this,
4361         // if it was prompted by constant non-zero subword initializers.
4362         // But this case can still arise with non-constant stores.
4363 
4364         intptr_t next_full_store = find_next_fullword_store(i, phase);
4365 
4366         // In the examples above:
4367         //   in(i)          p   q   r   s     x   y     z
4368         //   st_off        12  13  14  15    12  13    14
4369         //   st_size        1   1   1   1     1   1     1
4370         //   next_full_s.  12  16  16  16    16  16    16
4371         //   z's_done      12  16  16  16    12  16    12
4372         //   z's_needed    12  16  16  16    16  16    16
4373         //   zsize          0   0   0   0     4   0     4
4374         if (next_full_store < 0) {
4375           // Conservative tack:  Zero to end of current word.
4376           zeroes_needed = align_up(zeroes_needed, BytesPerInt);
4377         } else {
4378           // Zero to beginning of next fully initialized word.
4379           // Or, don't zero at all, if we are already in that word.
4380           assert(next_full_store >= zeroes_needed, "must go forward");
4381           assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
4382           zeroes_needed = next_full_store;
4383         }
4384       }
4385 
4386       if (zeroes_needed > zeroes_done) {
4387         intptr_t zsize = zeroes_needed - zeroes_done;
4388         // Do some incremental zeroing on rawmem, in parallel with inits.
4389         zeroes_done = align_down(zeroes_done, BytesPerInt);
4390         rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
4391                                               zeroes_done, zeroes_needed,
4392                                               phase);
4393         zeroes_done = zeroes_needed;
4394         if (zsize > InitArrayShortSize && ++big_init_gaps > 2)
4395           do_zeroing = false;   // leave the hole, next time
4396       }
4397     }
4398 
4399     // Collect the store and move on:
4400     phase->replace_input_of(st, MemNode::Memory, inits);
4401     inits = st;                 // put it on the linearized chain
4402     set_req(i, zmem);           // unhook from previous position
4403 
4404     if (zeroes_done == st_off)
4405       zeroes_done = next_init_off;
4406 
4407     assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
4408 
4409     #ifdef ASSERT
4410     // Various order invariants.  Weaker than stores_are_sane because
4411     // a large constant tile can be filled in by smaller non-constant stores.
4412     assert(st_off >= last_init_off, "inits do not reverse");
4413     last_init_off = st_off;
4414     const Type* val = NULL;
4415     if (st_size >= BytesPerInt &&
4416         (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
4417         (int)val->basic_type() < (int)T_OBJECT) {
4418       assert(st_off >= last_tile_end, "tiles do not overlap");
4419       assert(st_off >= last_init_end, "tiles do not overwrite inits");
4420       last_tile_end = MAX2(last_tile_end, next_init_off);
4421     } else {
4422       intptr_t st_tile_end = align_up(next_init_off, BytesPerLong);
4423       assert(st_tile_end >= last_tile_end, "inits stay with tiles");
4424       assert(st_off      >= last_init_end, "inits do not overlap");
4425       last_init_end = next_init_off;  // it's a non-tile
4426     }
4427     #endif //ASSERT
4428   }
4429 
4430   remove_extra_zeroes();        // clear out all the zmems left over
4431   add_req(inits);
4432 
4433   if (!(UseTLAB && ZeroTLAB)) {
4434     // If anything remains to be zeroed, zero it all now.
4435     zeroes_done = align_down(zeroes_done, BytesPerInt);
4436     // if it is the last unused 4 bytes of an instance, forget about it
4437     intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
4438     if (zeroes_done + BytesPerLong >= size_limit) {
4439       AllocateNode* alloc = allocation();
4440       assert(alloc != NULL, "must be present");
4441       if (alloc != NULL && alloc->Opcode() == Op_Allocate) {
4442         Node* klass_node = alloc->in(AllocateNode::KlassNode);
4443         ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
4444         if (zeroes_done == k->layout_helper())
4445           zeroes_done = size_limit;
4446       }
4447     }
4448     if (zeroes_done < size_limit) {
4449       rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
4450                                             zeroes_done, size_in_bytes, phase);
4451     }
4452   }
4453 
4454   set_complete(phase);
4455   return rawmem;
4456 }
4457 
4458 
4459 #ifdef ASSERT
stores_are_sane(PhaseTransform * phase)4460 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
4461   if (is_complete())
4462     return true;                // stores could be anything at this point
4463   assert(allocation() != NULL, "must be present");
4464   intptr_t last_off = allocation()->minimum_header_size();
4465   for (uint i = InitializeNode::RawStores; i < req(); i++) {
4466     Node* st = in(i);
4467     intptr_t st_off = get_store_offset(st, phase);
4468     if (st_off < 0)  continue;  // ignore dead garbage
4469     if (last_off > st_off) {
4470       tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
4471       this->dump(2);
4472       assert(false, "ascending store offsets");
4473       return false;
4474     }
4475     last_off = st_off + st->as_Store()->memory_size();
4476   }
4477   return true;
4478 }
4479 #endif //ASSERT
4480 
4481 
4482 
4483 
4484 //============================MergeMemNode=====================================
4485 //
4486 // SEMANTICS OF MEMORY MERGES:  A MergeMem is a memory state assembled from several
4487 // contributing store or call operations.  Each contributor provides the memory
4488 // state for a particular "alias type" (see Compile::alias_type).  For example,
4489 // if a MergeMem has an input X for alias category #6, then any memory reference
4490 // to alias category #6 may use X as its memory state input, as an exact equivalent
4491 // to using the MergeMem as a whole.
4492 //   Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
4493 //
4494 // (Here, the <N> notation gives the index of the relevant adr_type.)
4495 //
4496 // In one special case (and more cases in the future), alias categories overlap.
4497 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
4498 // states.  Therefore, if a MergeMem has only one contributing input W for Bot,
4499 // it is exactly equivalent to that state W:
4500 //   MergeMem(<Bot>: W) <==> W
4501 //
4502 // Usually, the merge has more than one input.  In that case, where inputs
4503 // overlap (i.e., one is Bot), the narrower alias type determines the memory
4504 // state for that type, and the wider alias type (Bot) fills in everywhere else:
4505 //   Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
4506 //   Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
4507 //
4508 // A merge can take a "wide" memory state as one of its narrow inputs.
4509 // This simply means that the merge observes out only the relevant parts of
4510 // the wide input.  That is, wide memory states arriving at narrow merge inputs
4511 // are implicitly "filtered" or "sliced" as necessary.  (This is rare.)
4512 //
4513 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
4514 // and that memory slices "leak through":
4515 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
4516 //
4517 // But, in such a cascade, repeated memory slices can "block the leak":
4518 //   MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
4519 //
4520 // In the last example, Y is not part of the combined memory state of the
4521 // outermost MergeMem.  The system must, of course, prevent unschedulable
4522 // memory states from arising, so you can be sure that the state Y is somehow
4523 // a precursor to state Y'.
4524 //
4525 //
4526 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
4527 // of each MergeMemNode array are exactly the numerical alias indexes, including
4528 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw.  The functions
4529 // Compile::alias_type (and kin) produce and manage these indexes.
4530 //
4531 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
4532 // (Note that this provides quick access to the top node inside MergeMem methods,
4533 // without the need to reach out via TLS to Compile::current.)
4534 //
4535 // As a consequence of what was just described, a MergeMem that represents a full
4536 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
4537 // containing all alias categories.
4538 //
4539 // MergeMem nodes never (?) have control inputs, so in(0) is NULL.
4540 //
4541 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
4542 // a memory state for the alias type <N>, or else the top node, meaning that
4543 // there is no particular input for that alias type.  Note that the length of
4544 // a MergeMem is variable, and may be extended at any time to accommodate new
4545 // memory states at larger alias indexes.  When merges grow, they are of course
4546 // filled with "top" in the unused in() positions.
4547 //
4548 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
4549 // (Top was chosen because it works smoothly with passes like GCM.)
4550 //
4551 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM.  (It is
4552 // the type of random VM bits like TLS references.)  Since it is always the
4553 // first non-Bot memory slice, some low-level loops use it to initialize an
4554 // index variable:  for (i = AliasIdxRaw; i < req(); i++).
4555 //
4556 //
4557 // ACCESSORS:  There is a special accessor MergeMemNode::base_memory which returns
4558 // the distinguished "wide" state.  The accessor MergeMemNode::memory_at(N) returns
4559 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
4560 // it returns the base memory.  To prevent bugs, memory_at does not accept <Top>
4561 // or <Bot> indexes.  The iterator MergeMemStream provides robust iteration over
4562 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
4563 //
4564 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
4565 // really that different from the other memory inputs.  An abbreviation called
4566 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
4567 //
4568 //
4569 // PARTIAL MEMORY STATES:  During optimization, MergeMem nodes may arise that represent
4570 // partial memory states.  When a Phi splits through a MergeMem, the copy of the Phi
4571 // that "emerges though" the base memory will be marked as excluding the alias types
4572 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
4573 //
4574 //   Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
4575 //     ==Ideal=>  MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
4576 //
4577 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
4578 // (It is currently unimplemented.)  As you can see, the resulting merge is
4579 // actually a disjoint union of memory states, rather than an overlay.
4580 //
4581 
4582 //------------------------------MergeMemNode-----------------------------------
make_empty_memory()4583 Node* MergeMemNode::make_empty_memory() {
4584   Node* empty_memory = (Node*) Compile::current()->top();
4585   assert(empty_memory->is_top(), "correct sentinel identity");
4586   return empty_memory;
4587 }
4588 
MergeMemNode(Node * new_base)4589 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
4590   init_class_id(Class_MergeMem);
4591   // all inputs are nullified in Node::Node(int)
4592   // set_input(0, NULL);  // no control input
4593 
4594   // Initialize the edges uniformly to top, for starters.
4595   Node* empty_mem = make_empty_memory();
4596   for (uint i = Compile::AliasIdxTop; i < req(); i++) {
4597     init_req(i,empty_mem);
4598   }
4599   assert(empty_memory() == empty_mem, "");
4600 
4601   if( new_base != NULL && new_base->is_MergeMem() ) {
4602     MergeMemNode* mdef = new_base->as_MergeMem();
4603     assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
4604     for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
4605       mms.set_memory(mms.memory2());
4606     }
4607     assert(base_memory() == mdef->base_memory(), "");
4608   } else {
4609     set_base_memory(new_base);
4610   }
4611 }
4612 
4613 // Make a new, untransformed MergeMem with the same base as 'mem'.
4614 // If mem is itself a MergeMem, populate the result with the same edges.
make(Node * mem)4615 MergeMemNode* MergeMemNode::make(Node* mem) {
4616   return new MergeMemNode(mem);
4617 }
4618 
4619 //------------------------------cmp--------------------------------------------
hash() const4620 uint MergeMemNode::hash() const { return NO_HASH; }
cmp(const Node & n) const4621 bool MergeMemNode::cmp( const Node &n ) const {
4622   return (&n == this);          // Always fail except on self
4623 }
4624 
4625 //------------------------------Identity---------------------------------------
Identity(PhaseGVN * phase)4626 Node* MergeMemNode::Identity(PhaseGVN* phase) {
4627   // Identity if this merge point does not record any interesting memory
4628   // disambiguations.
4629   Node* base_mem = base_memory();
4630   Node* empty_mem = empty_memory();
4631   if (base_mem != empty_mem) {  // Memory path is not dead?
4632     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4633       Node* mem = in(i);
4634       if (mem != empty_mem && mem != base_mem) {
4635         return this;            // Many memory splits; no change
4636       }
4637     }
4638   }
4639   return base_mem;              // No memory splits; ID on the one true input
4640 }
4641 
4642 //------------------------------Ideal------------------------------------------
4643 // This method is invoked recursively on chains of MergeMem nodes
Ideal(PhaseGVN * phase,bool can_reshape)4644 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4645   // Remove chain'd MergeMems
4646   //
4647   // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
4648   // relative to the "in(Bot)".  Since we are patching both at the same time,
4649   // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
4650   // but rewrite each "in(i)" relative to the new "in(Bot)".
4651   Node *progress = NULL;
4652 
4653 
4654   Node* old_base = base_memory();
4655   Node* empty_mem = empty_memory();
4656   if (old_base == empty_mem)
4657     return NULL; // Dead memory path.
4658 
4659   MergeMemNode* old_mbase;
4660   if (old_base != NULL && old_base->is_MergeMem())
4661     old_mbase = old_base->as_MergeMem();
4662   else
4663     old_mbase = NULL;
4664   Node* new_base = old_base;
4665 
4666   // simplify stacked MergeMems in base memory
4667   if (old_mbase)  new_base = old_mbase->base_memory();
4668 
4669   // the base memory might contribute new slices beyond my req()
4670   if (old_mbase)  grow_to_match(old_mbase);
4671 
4672   // Look carefully at the base node if it is a phi.
4673   PhiNode* phi_base;
4674   if (new_base != NULL && new_base->is_Phi())
4675     phi_base = new_base->as_Phi();
4676   else
4677     phi_base = NULL;
4678 
4679   Node*    phi_reg = NULL;
4680   uint     phi_len = (uint)-1;
4681   if (phi_base != NULL) {
4682     phi_reg = phi_base->region();
4683     phi_len = phi_base->req();
4684     // see if the phi is unfinished
4685     for (uint i = 1; i < phi_len; i++) {
4686       if (phi_base->in(i) == NULL) {
4687         // incomplete phi; do not look at it yet!
4688         phi_reg = NULL;
4689         phi_len = (uint)-1;
4690         break;
4691       }
4692     }
4693   }
4694 
4695   // Note:  We do not call verify_sparse on entry, because inputs
4696   // can normalize to the base_memory via subsume_node or similar
4697   // mechanisms.  This method repairs that damage.
4698 
4699   assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
4700 
4701   // Look at each slice.
4702   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4703     Node* old_in = in(i);
4704     // calculate the old memory value
4705     Node* old_mem = old_in;
4706     if (old_mem == empty_mem)  old_mem = old_base;
4707     assert(old_mem == memory_at(i), "");
4708 
4709     // maybe update (reslice) the old memory value
4710 
4711     // simplify stacked MergeMems
4712     Node* new_mem = old_mem;
4713     MergeMemNode* old_mmem;
4714     if (old_mem != NULL && old_mem->is_MergeMem())
4715       old_mmem = old_mem->as_MergeMem();
4716     else
4717       old_mmem = NULL;
4718     if (old_mmem == this) {
4719       // This can happen if loops break up and safepoints disappear.
4720       // A merge of BotPtr (default) with a RawPtr memory derived from a
4721       // safepoint can be rewritten to a merge of the same BotPtr with
4722       // the BotPtr phi coming into the loop.  If that phi disappears
4723       // also, we can end up with a self-loop of the mergemem.
4724       // In general, if loops degenerate and memory effects disappear,
4725       // a mergemem can be left looking at itself.  This simply means
4726       // that the mergemem's default should be used, since there is
4727       // no longer any apparent effect on this slice.
4728       // Note: If a memory slice is a MergeMem cycle, it is unreachable
4729       //       from start.  Update the input to TOP.
4730       new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
4731     }
4732     else if (old_mmem != NULL) {
4733       new_mem = old_mmem->memory_at(i);
4734     }
4735     // else preceding memory was not a MergeMem
4736 
4737     // maybe store down a new value
4738     Node* new_in = new_mem;
4739     if (new_in == new_base)  new_in = empty_mem;
4740 
4741     if (new_in != old_in) {
4742       // Warning:  Do not combine this "if" with the previous "if"
4743       // A memory slice might have be be rewritten even if it is semantically
4744       // unchanged, if the base_memory value has changed.
4745       set_req(i, new_in);
4746       progress = this;          // Report progress
4747     }
4748   }
4749 
4750   if (new_base != old_base) {
4751     set_req(Compile::AliasIdxBot, new_base);
4752     // Don't use set_base_memory(new_base), because we need to update du.
4753     assert(base_memory() == new_base, "");
4754     progress = this;
4755   }
4756 
4757   if( base_memory() == this ) {
4758     // a self cycle indicates this memory path is dead
4759     set_req(Compile::AliasIdxBot, empty_mem);
4760   }
4761 
4762   // Resolve external cycles by calling Ideal on a MergeMem base_memory
4763   // Recursion must occur after the self cycle check above
4764   if( base_memory()->is_MergeMem() ) {
4765     MergeMemNode *new_mbase = base_memory()->as_MergeMem();
4766     Node *m = phase->transform(new_mbase);  // Rollup any cycles
4767     if( m != NULL &&
4768         (m->is_top() ||
4769          (m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem)) ) {
4770       // propagate rollup of dead cycle to self
4771       set_req(Compile::AliasIdxBot, empty_mem);
4772     }
4773   }
4774 
4775   if( base_memory() == empty_mem ) {
4776     progress = this;
4777     // Cut inputs during Parse phase only.
4778     // During Optimize phase a dead MergeMem node will be subsumed by Top.
4779     if( !can_reshape ) {
4780       for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4781         if( in(i) != empty_mem ) { set_req(i, empty_mem); }
4782       }
4783     }
4784   }
4785 
4786   if( !progress && base_memory()->is_Phi() && can_reshape ) {
4787     // Check if PhiNode::Ideal's "Split phis through memory merges"
4788     // transform should be attempted. Look for this->phi->this cycle.
4789     uint merge_width = req();
4790     if (merge_width > Compile::AliasIdxRaw) {
4791       PhiNode* phi = base_memory()->as_Phi();
4792       for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
4793         if (phi->in(i) == this) {
4794           phase->is_IterGVN()->_worklist.push(phi);
4795           break;
4796         }
4797       }
4798     }
4799   }
4800 
4801   assert(progress || verify_sparse(), "please, no dups of base");
4802   return progress;
4803 }
4804 
4805 //-------------------------set_base_memory-------------------------------------
set_base_memory(Node * new_base)4806 void MergeMemNode::set_base_memory(Node *new_base) {
4807   Node* empty_mem = empty_memory();
4808   set_req(Compile::AliasIdxBot, new_base);
4809   assert(memory_at(req()) == new_base, "must set default memory");
4810   // Clear out other occurrences of new_base:
4811   if (new_base != empty_mem) {
4812     for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4813       if (in(i) == new_base)  set_req(i, empty_mem);
4814     }
4815   }
4816 }
4817 
4818 //------------------------------out_RegMask------------------------------------
out_RegMask() const4819 const RegMask &MergeMemNode::out_RegMask() const {
4820   return RegMask::Empty;
4821 }
4822 
4823 //------------------------------dump_spec--------------------------------------
4824 #ifndef PRODUCT
dump_spec(outputStream * st) const4825 void MergeMemNode::dump_spec(outputStream *st) const {
4826   st->print(" {");
4827   Node* base_mem = base_memory();
4828   for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
4829     Node* mem = (in(i) != NULL) ? memory_at(i) : base_mem;
4830     if (mem == base_mem) { st->print(" -"); continue; }
4831     st->print( " N%d:", mem->_idx );
4832     Compile::current()->get_adr_type(i)->dump_on(st);
4833   }
4834   st->print(" }");
4835 }
4836 #endif // !PRODUCT
4837 
4838 
4839 #ifdef ASSERT
might_be_same(Node * a,Node * b)4840 static bool might_be_same(Node* a, Node* b) {
4841   if (a == b)  return true;
4842   if (!(a->is_Phi() || b->is_Phi()))  return false;
4843   // phis shift around during optimization
4844   return true;  // pretty stupid...
4845 }
4846 
4847 // verify a narrow slice (either incoming or outgoing)
verify_memory_slice(const MergeMemNode * m,int alias_idx,Node * n)4848 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
4849   if (!VerifyAliases)                return;  // don't bother to verify unless requested
4850   if (VMError::is_error_reported())  return;  // muzzle asserts when debugging an error
4851   if (Node::in_dump())               return;  // muzzle asserts when printing
4852   assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
4853   assert(n != NULL, "");
4854   // Elide intervening MergeMem's
4855   while (n->is_MergeMem()) {
4856     n = n->as_MergeMem()->memory_at(alias_idx);
4857   }
4858   Compile* C = Compile::current();
4859   const TypePtr* n_adr_type = n->adr_type();
4860   if (n == m->empty_memory()) {
4861     // Implicit copy of base_memory()
4862   } else if (n_adr_type != TypePtr::BOTTOM) {
4863     assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
4864     assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
4865   } else {
4866     // A few places like make_runtime_call "know" that VM calls are narrow,
4867     // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
4868     bool expected_wide_mem = false;
4869     if (n == m->base_memory()) {
4870       expected_wide_mem = true;
4871     } else if (alias_idx == Compile::AliasIdxRaw ||
4872                n == m->memory_at(Compile::AliasIdxRaw)) {
4873       expected_wide_mem = true;
4874     } else if (!C->alias_type(alias_idx)->is_rewritable()) {
4875       // memory can "leak through" calls on channels that
4876       // are write-once.  Allow this also.
4877       expected_wide_mem = true;
4878     }
4879     assert(expected_wide_mem, "expected narrow slice replacement");
4880   }
4881 }
4882 #else // !ASSERT
4883 #define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
4884 #endif
4885 
4886 
4887 //-----------------------------memory_at---------------------------------------
memory_at(uint alias_idx) const4888 Node* MergeMemNode::memory_at(uint alias_idx) const {
4889   assert(alias_idx >= Compile::AliasIdxRaw ||
4890          alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
4891          "must avoid base_memory and AliasIdxTop");
4892 
4893   // Otherwise, it is a narrow slice.
4894   Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
4895   Compile *C = Compile::current();
4896   if (is_empty_memory(n)) {
4897     // the array is sparse; empty slots are the "top" node
4898     n = base_memory();
4899     assert(Node::in_dump()
4900            || n == NULL || n->bottom_type() == Type::TOP
4901            || n->adr_type() == NULL // address is TOP
4902            || n->adr_type() == TypePtr::BOTTOM
4903            || n->adr_type() == TypeRawPtr::BOTTOM
4904            || Compile::current()->AliasLevel() == 0,
4905            "must be a wide memory");
4906     // AliasLevel == 0 if we are organizing the memory states manually.
4907     // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
4908   } else {
4909     // make sure the stored slice is sane
4910     #ifdef ASSERT
4911     if (VMError::is_error_reported() || Node::in_dump()) {
4912     } else if (might_be_same(n, base_memory())) {
4913       // Give it a pass:  It is a mostly harmless repetition of the base.
4914       // This can arise normally from node subsumption during optimization.
4915     } else {
4916       verify_memory_slice(this, alias_idx, n);
4917     }
4918     #endif
4919   }
4920   return n;
4921 }
4922 
4923 //---------------------------set_memory_at-------------------------------------
set_memory_at(uint alias_idx,Node * n)4924 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
4925   verify_memory_slice(this, alias_idx, n);
4926   Node* empty_mem = empty_memory();
4927   if (n == base_memory())  n = empty_mem;  // collapse default
4928   uint need_req = alias_idx+1;
4929   if (req() < need_req) {
4930     if (n == empty_mem)  return;  // already the default, so do not grow me
4931     // grow the sparse array
4932     do {
4933       add_req(empty_mem);
4934     } while (req() < need_req);
4935   }
4936   set_req( alias_idx, n );
4937 }
4938 
4939 
4940 
4941 //--------------------------iteration_setup------------------------------------
iteration_setup(const MergeMemNode * other)4942 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
4943   if (other != NULL) {
4944     grow_to_match(other);
4945     // invariant:  the finite support of mm2 is within mm->req()
4946     #ifdef ASSERT
4947     for (uint i = req(); i < other->req(); i++) {
4948       assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
4949     }
4950     #endif
4951   }
4952   // Replace spurious copies of base_memory by top.
4953   Node* base_mem = base_memory();
4954   if (base_mem != NULL && !base_mem->is_top()) {
4955     for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
4956       if (in(i) == base_mem)
4957         set_req(i, empty_memory());
4958     }
4959   }
4960 }
4961 
4962 //---------------------------grow_to_match-------------------------------------
grow_to_match(const MergeMemNode * other)4963 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
4964   Node* empty_mem = empty_memory();
4965   assert(other->is_empty_memory(empty_mem), "consistent sentinels");
4966   // look for the finite support of the other memory
4967   for (uint i = other->req(); --i >= req(); ) {
4968     if (other->in(i) != empty_mem) {
4969       uint new_len = i+1;
4970       while (req() < new_len)  add_req(empty_mem);
4971       break;
4972     }
4973   }
4974 }
4975 
4976 //---------------------------verify_sparse-------------------------------------
4977 #ifndef PRODUCT
verify_sparse() const4978 bool MergeMemNode::verify_sparse() const {
4979   assert(is_empty_memory(make_empty_memory()), "sane sentinel");
4980   Node* base_mem = base_memory();
4981   // The following can happen in degenerate cases, since empty==top.
4982   if (is_empty_memory(base_mem))  return true;
4983   for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4984     assert(in(i) != NULL, "sane slice");
4985     if (in(i) == base_mem)  return false;  // should have been the sentinel value!
4986   }
4987   return true;
4988 }
4989 
match_memory(Node * mem,const MergeMemNode * mm,int idx)4990 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
4991   Node* n;
4992   n = mm->in(idx);
4993   if (mem == n)  return true;  // might be empty_memory()
4994   n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
4995   if (mem == n)  return true;
4996   return false;
4997 }
4998 #endif // !PRODUCT
4999