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