1 /*
2 * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2024, Alibaba Group Holding Limited. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 *
24 */
25
26 #include "classfile/javaClasses.hpp"
27 #include "compiler/compileLog.hpp"
28 #include "gc/shared/barrierSet.hpp"
29 #include "gc/shared/c2/barrierSetC2.hpp"
30 #include "gc/shared/tlab_globals.hpp"
31 #include "memory/allocation.inline.hpp"
32 #include "memory/resourceArea.hpp"
33 #include "oops/objArrayKlass.hpp"
34 #include "opto/addnode.hpp"
35 #include "opto/arraycopynode.hpp"
36 #include "opto/cfgnode.hpp"
37 #include "opto/compile.hpp"
38 #include "opto/connode.hpp"
39 #include "opto/convertnode.hpp"
40 #include "opto/loopnode.hpp"
41 #include "opto/machnode.hpp"
42 #include "opto/matcher.hpp"
43 #include "opto/memnode.hpp"
44 #include "opto/mempointer.hpp"
45 #include "opto/mulnode.hpp"
46 #include "opto/narrowptrnode.hpp"
47 #include "opto/opcodes.hpp"
48 #include "opto/phaseX.hpp"
49 #include "opto/regalloc.hpp"
50 #include "opto/regmask.hpp"
51 #include "opto/rootnode.hpp"
52 #include "opto/traceMergeStoresTag.hpp"
53 #include "opto/vectornode.hpp"
54 #include "utilities/align.hpp"
55 #include "utilities/copy.hpp"
56 #include "utilities/globalDefinitions.hpp"
57 #include "utilities/macros.hpp"
58 #include "utilities/powerOfTwo.hpp"
59 #include "utilities/vmError.hpp"
60
61 // Portions of code courtesy of Clifford Click
62
63 // Optimization - Graph Style
64
65 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
66
67 //=============================================================================
68 uint MemNode::size_of() const { return sizeof(*this); }
69
70 const TypePtr *MemNode::adr_type() const {
71 Node* adr = in(Address);
72 if (adr == nullptr) return nullptr; // node is dead
73 const TypePtr* cross_check = nullptr;
74 DEBUG_ONLY(cross_check = _adr_type);
75 return calculate_adr_type(adr->bottom_type(), cross_check);
76 }
77
78 bool MemNode::check_if_adr_maybe_raw(Node* adr) {
79 if (adr != nullptr) {
80 if (adr->bottom_type()->base() == Type::RawPtr || adr->bottom_type()->base() == Type::AnyPtr) {
81 return true;
82 }
83 }
84 return false;
85 }
86
87 #ifndef PRODUCT
88 void MemNode::dump_spec(outputStream *st) const {
89 if (in(Address) == nullptr) return; // node is dead
90 #ifndef ASSERT
91 // fake the missing field
92 const TypePtr* _adr_type = nullptr;
93 if (in(Address) != nullptr)
94 _adr_type = in(Address)->bottom_type()->isa_ptr();
95 #endif
96 dump_adr_type(_adr_type, st);
97
98 Compile* C = Compile::current();
99 if (C->alias_type(_adr_type)->is_volatile()) {
100 st->print(" Volatile!");
101 }
102 if (_unaligned_access) {
103 st->print(" unaligned");
104 }
105 if (_mismatched_access) {
106 st->print(" mismatched");
107 }
108 if (_unsafe_access) {
109 st->print(" unsafe");
110 }
111 }
112
113 void MemNode::dump_adr_type(const TypePtr* adr_type, outputStream* st) {
114 st->print(" @");
115 if (adr_type == nullptr) {
116 st->print("null");
117 } else {
118 adr_type->dump_on(st);
119 Compile* C = Compile::current();
120 Compile::AliasType* atp = nullptr;
121 if (C->have_alias_type(adr_type)) atp = C->alias_type(adr_type);
122 if (atp == nullptr)
123 st->print(", idx=?\?;");
124 else if (atp->index() == Compile::AliasIdxBot)
125 st->print(", idx=Bot;");
126 else if (atp->index() == Compile::AliasIdxTop)
127 st->print(", idx=Top;");
128 else if (atp->index() == Compile::AliasIdxRaw)
129 st->print(", idx=Raw;");
130 else {
131 ciField* field = atp->field();
132 if (field) {
133 st->print(", name=");
134 field->print_name_on(st);
135 }
136 st->print(", idx=%d;", atp->index());
137 }
138 }
139 }
140
141 extern void print_alias_types();
142
143 #endif
144
145 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) {
146 assert((t_oop != nullptr), "sanity");
147 bool is_instance = t_oop->is_known_instance_field();
148 bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() &&
149 (load != nullptr) && load->is_Load() &&
150 (phase->is_IterGVN() != nullptr);
151 if (!(is_instance || is_boxed_value_load))
152 return mchain; // don't try to optimize non-instance types
153 uint instance_id = t_oop->instance_id();
154 Node *start_mem = phase->C->start()->proj_out_or_null(TypeFunc::Memory);
155 Node *prev = nullptr;
156 Node *result = mchain;
157 while (prev != result) {
158 prev = result;
159 if (result == start_mem)
160 break; // hit one of our sentinels
161 // skip over a call which does not affect this memory slice
162 if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
163 Node *proj_in = result->in(0);
164 if (proj_in->is_Allocate() && proj_in->_idx == instance_id) {
165 break; // hit one of our sentinels
166 } else if (proj_in->is_Call()) {
167 // ArrayCopyNodes processed here as well
168 CallNode *call = proj_in->as_Call();
169 if (!call->may_modify(t_oop, phase)) { // returns false for instances
170 result = call->in(TypeFunc::Memory);
171 }
172 } else if (proj_in->is_Initialize()) {
173 AllocateNode* alloc = proj_in->as_Initialize()->allocation();
174 // Stop if this is the initialization for the object instance which
175 // contains this memory slice, otherwise skip over it.
176 if ((alloc == nullptr) || (alloc->_idx == instance_id)) {
177 break;
178 }
179 if (is_instance) {
180 result = proj_in->in(TypeFunc::Memory);
181 } else if (is_boxed_value_load) {
182 Node* klass = alloc->in(AllocateNode::KlassNode);
183 const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr();
184 if (tklass->klass_is_exact() && !tklass->exact_klass()->equals(t_oop->is_instptr()->exact_klass())) {
185 result = proj_in->in(TypeFunc::Memory); // not related allocation
186 }
187 }
188 } else if (proj_in->is_MemBar()) {
189 ArrayCopyNode* ac = nullptr;
190 if (ArrayCopyNode::may_modify(t_oop, proj_in->as_MemBar(), phase, ac)) {
191 break;
192 }
193 result = proj_in->in(TypeFunc::Memory);
194 } else if (proj_in->is_top()) {
195 break; // dead code
196 } else {
197 assert(false, "unexpected projection");
198 }
199 } else if (result->is_ClearArray()) {
200 if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) {
201 // Can not bypass initialization of the instance
202 // we are looking for.
203 break;
204 }
205 // Otherwise skip it (the call updated 'result' value).
206 } else if (result->is_MergeMem()) {
207 result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, nullptr, tty);
208 }
209 }
210 return result;
211 }
212
213 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) {
214 const TypeOopPtr* t_oop = t_adr->isa_oopptr();
215 if (t_oop == nullptr)
216 return mchain; // don't try to optimize non-oop types
217 Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase);
218 bool is_instance = t_oop->is_known_instance_field();
219 PhaseIterGVN *igvn = phase->is_IterGVN();
220 if (is_instance && igvn != nullptr && result->is_Phi()) {
221 PhiNode *mphi = result->as_Phi();
222 assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
223 const TypePtr *t = mphi->adr_type();
224 bool do_split = false;
225 // In the following cases, Load memory input can be further optimized based on
226 // its precise address type
227 if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ) {
228 do_split = true;
229 } else if (t->isa_oopptr() && !t->is_oopptr()->is_known_instance()) {
230 const TypeOopPtr* mem_t =
231 t->is_oopptr()->cast_to_exactness(true)
232 ->is_oopptr()->cast_to_ptr_type(t_oop->ptr())
233 ->is_oopptr()->cast_to_instance_id(t_oop->instance_id());
234 if (t_oop->isa_aryptr()) {
235 mem_t = mem_t->is_aryptr()
236 ->cast_to_stable(t_oop->is_aryptr()->is_stable())
237 ->cast_to_size(t_oop->is_aryptr()->size())
238 ->with_offset(t_oop->is_aryptr()->offset())
239 ->is_aryptr();
240 }
241 do_split = mem_t == t_oop;
242 }
243 if (do_split) {
244 // clone the Phi with our address type
245 result = mphi->split_out_instance(t_adr, igvn);
246 } else {
247 assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
248 }
249 }
250 return result;
251 }
252
253 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
254 uint alias_idx = phase->C->get_alias_index(tp);
255 Node *mem = mmem;
256 #ifdef ASSERT
257 {
258 // Check that current type is consistent with the alias index used during graph construction
259 assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
260 bool consistent = adr_check == nullptr || adr_check->empty() ||
261 phase->C->must_alias(adr_check, alias_idx );
262 // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
263 if( !consistent && adr_check != nullptr && !adr_check->empty() &&
264 tp->isa_aryptr() && tp->offset() == Type::OffsetBot &&
265 adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
266 ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
267 adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
268 adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
269 // don't assert if it is dead code.
270 consistent = true;
271 }
272 if( !consistent ) {
273 st->print("alias_idx==%d, adr_check==", alias_idx);
274 if( adr_check == nullptr ) {
275 st->print("null");
276 } else {
277 adr_check->dump();
278 }
279 st->cr();
280 print_alias_types();
281 assert(consistent, "adr_check must match alias idx");
282 }
283 }
284 #endif
285 // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
286 // means an array I have not precisely typed yet. Do not do any
287 // alias stuff with it any time soon.
288 const TypeOopPtr *toop = tp->isa_oopptr();
289 if (tp->base() != Type::AnyPtr &&
290 !(toop &&
291 toop->isa_instptr() &&
292 toop->is_instptr()->instance_klass()->is_java_lang_Object() &&
293 toop->offset() == Type::OffsetBot)) {
294 // IGVN _delay_transform may be set to true and if that is the case and mmem
295 // is already a registered node then the validation inside transform will
296 // complain.
297 Node* m = mmem;
298 PhaseIterGVN* igvn = phase->is_IterGVN();
299 if (igvn == nullptr || !igvn->delay_transform()) {
300 // compress paths and change unreachable cycles to TOP
301 // If not, we can update the input infinitely along a MergeMem cycle
302 // Equivalent code in PhiNode::Ideal
303 m = phase->transform(mmem);
304 }
305 // If transformed to a MergeMem, get the desired slice
306 // Otherwise the returned node represents memory for every slice
307 mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
308 // Update input if it is progress over what we have now
309 }
310 return mem;
311 }
312
313 //--------------------------Ideal_common---------------------------------------
314 // Look for degenerate control and memory inputs. Bypass MergeMem inputs.
315 // Unhook non-raw memories from complete (macro-expanded) initializations.
316 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
317 // If our control input is a dead region, kill all below the region
318 Node *ctl = in(MemNode::Control);
319 if (ctl && remove_dead_region(phase, can_reshape))
320 return this;
321 ctl = in(MemNode::Control);
322 // Don't bother trying to transform a dead node
323 if (ctl && ctl->is_top()) return NodeSentinel;
324
325 PhaseIterGVN *igvn = phase->is_IterGVN();
326 // Wait if control on the worklist.
327 if (ctl && can_reshape && igvn != nullptr) {
328 Node* bol = nullptr;
329 Node* cmp = nullptr;
330 if (ctl->in(0)->is_If()) {
331 assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity");
332 bol = ctl->in(0)->in(1);
333 if (bol->is_Bool())
334 cmp = ctl->in(0)->in(1)->in(1);
335 }
336 if (igvn->_worklist.member(ctl) ||
337 (bol != nullptr && igvn->_worklist.member(bol)) ||
338 (cmp != nullptr && igvn->_worklist.member(cmp)) ) {
339 // This control path may be dead.
340 // Delay this memory node transformation until the control is processed.
341 igvn->_worklist.push(this);
342 return NodeSentinel; // caller will return null
343 }
344 }
345 // Ignore if memory is dead, or self-loop
346 Node *mem = in(MemNode::Memory);
347 if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return null
348 assert(mem != this, "dead loop in MemNode::Ideal");
349
350 if (can_reshape && igvn != nullptr && igvn->_worklist.member(mem)) {
351 // This memory slice may be dead.
352 // Delay this mem node transformation until the memory is processed.
353 igvn->_worklist.push(this);
354 return NodeSentinel; // caller will return null
355 }
356
357 Node *address = in(MemNode::Address);
358 const Type *t_adr = phase->type(address);
359 if (t_adr == Type::TOP) return NodeSentinel; // caller will return null
360
361 if (can_reshape && is_unsafe_access() && (t_adr == TypePtr::NULL_PTR)) {
362 // Unsafe off-heap access with zero address. Remove access and other control users
363 // to not confuse optimizations and add a HaltNode to fail if this is ever executed.
364 assert(ctl != nullptr, "unsafe accesses should be control dependent");
365 for (DUIterator_Fast imax, i = ctl->fast_outs(imax); i < imax; i++) {
366 Node* u = ctl->fast_out(i);
367 if (u != ctl) {
368 igvn->rehash_node_delayed(u);
369 int nb = u->replace_edge(ctl, phase->C->top(), igvn);
370 --i, imax -= nb;
371 }
372 }
373 Node* frame = igvn->transform(new ParmNode(phase->C->start(), TypeFunc::FramePtr));
374 Node* halt = igvn->transform(new HaltNode(ctl, frame, "unsafe off-heap access with zero address"));
375 phase->C->root()->add_req(halt);
376 return this;
377 }
378
379 if (can_reshape && igvn != nullptr &&
380 (igvn->_worklist.member(address) ||
381 (igvn->_worklist.size() > 0 && t_adr != adr_type())) ) {
382 // The address's base and type may change when the address is processed.
383 // Delay this mem node transformation until the address is processed.
384 igvn->_worklist.push(this);
385 return NodeSentinel; // caller will return null
386 }
387
388 // Do NOT remove or optimize the next lines: ensure a new alias index
389 // is allocated for an oop pointer type before Escape Analysis.
390 // Note: C++ will not remove it since the call has side effect.
391 if (t_adr->isa_oopptr()) {
392 int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
393 }
394
395 Node* base = nullptr;
396 if (address->is_AddP()) {
397 base = address->in(AddPNode::Base);
398 }
399 if (base != nullptr && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
400 !t_adr->isa_rawptr()) {
401 // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
402 // Skip this node optimization if its address has TOP base.
403 return NodeSentinel; // caller will return null
404 }
405
406 // Avoid independent memory operations
407 Node* old_mem = mem;
408
409 // The code which unhooks non-raw memories from complete (macro-expanded)
410 // initializations was removed. After macro-expansion all stores caught
411 // by Initialize node became raw stores and there is no information
412 // which memory slices they modify. So it is unsafe to move any memory
413 // operation above these stores. Also in most cases hooked non-raw memories
414 // were already unhooked by using information from detect_ptr_independence()
415 // and find_previous_store().
416
417 if (mem->is_MergeMem()) {
418 MergeMemNode* mmem = mem->as_MergeMem();
419 const TypePtr *tp = t_adr->is_ptr();
420
421 mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
422 }
423
424 if (mem != old_mem) {
425 set_req_X(MemNode::Memory, mem, phase);
426 if (phase->type(mem) == Type::TOP) return NodeSentinel;
427 return this;
428 }
429
430 // let the subclass continue analyzing...
431 return nullptr;
432 }
433
434 // Helper function for proving some simple control dominations.
435 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
436 // Already assumes that 'dom' is available at 'sub', and that 'sub'
437 // is not a constant (dominated by the method's StartNode).
438 // Used by MemNode::find_previous_store to prove that the
439 // control input of a memory operation predates (dominates)
440 // an allocation it wants to look past.
441 // Returns 'DomResult::Dominate' if all control inputs of 'dom'
442 // dominate 'sub', 'DomResult::NotDominate' if not,
443 // and 'DomResult::EncounteredDeadCode' if we can't decide due to
444 // dead code, but at the end of IGVN, we know the definite result
445 // once the dead code is cleaned up.
446 Node::DomResult MemNode::maybe_all_controls_dominate(Node* dom, Node* sub, PhaseGVN* phase) {
447 if (dom == nullptr || dom->is_top() || sub == nullptr || sub->is_top()) {
448 return DomResult::EncounteredDeadCode; // Conservative answer for dead code
449 }
450
451 // Check 'dom'. Skip Proj and CatchProj nodes.
452 dom = dom->find_exact_control(dom);
453 if (dom == nullptr || dom->is_top()) {
454 return DomResult::EncounteredDeadCode; // Conservative answer for dead code
455 }
456
457 if (dom == sub) {
458 // For the case when, for example, 'sub' is Initialize and the original
459 // 'dom' is Proj node of the 'sub'.
460 return DomResult::NotDominate;
461 }
462
463 if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub) {
464 return DomResult::Dominate;
465 }
466
467 // 'dom' dominates 'sub' if its control edge and control edges
468 // of all its inputs dominate or equal to sub's control edge.
469
470 // Currently 'sub' is either Allocate, Initialize or Start nodes.
471 // Or Region for the check in LoadNode::Ideal();
472 // 'sub' should have sub->in(0) != nullptr.
473 assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() ||
474 sub->is_Region() || sub->is_Call(), "expecting only these nodes");
475
476 // Get control edge of 'sub'.
477 Node* orig_sub = sub;
478 sub = sub->find_exact_control(sub->in(0));
479 if (sub == nullptr || sub->is_top()) {
480 return DomResult::EncounteredDeadCode; // Conservative answer for dead code
481 }
482
483 assert(sub->is_CFG(), "expecting control");
484
485 if (sub == dom) {
486 return DomResult::Dominate;
487 }
488
489 if (sub->is_Start() || sub->is_Root()) {
490 return DomResult::NotDominate;
491 }
492
493 {
494 // Check all control edges of 'dom'.
495
496 ResourceMark rm;
497 Node_List nlist;
498 Unique_Node_List dom_list;
499
500 dom_list.push(dom);
501 bool only_dominating_controls = false;
502
503 for (uint next = 0; next < dom_list.size(); next++) {
504 Node* n = dom_list.at(next);
505 if (n == orig_sub) {
506 return DomResult::NotDominate; // One of dom's inputs dominated by sub.
507 }
508 if (!n->is_CFG() && n->pinned()) {
509 // Check only own control edge for pinned non-control nodes.
510 n = n->find_exact_control(n->in(0));
511 if (n == nullptr || n->is_top()) {
512 return DomResult::EncounteredDeadCode; // Conservative answer for dead code
513 }
514 assert(n->is_CFG(), "expecting control");
515 dom_list.push(n);
516 } else if (n->is_Con() || n->is_Start() || n->is_Root()) {
517 only_dominating_controls = true;
518 } else if (n->is_CFG()) {
519 DomResult dom_result = n->dominates(sub, nlist);
520 if (dom_result == DomResult::Dominate) {
521 only_dominating_controls = true;
522 } else {
523 return dom_result;
524 }
525 } else {
526 if (n->Value(phase) == Type::TOP) {
527 return DomResult::EncounteredDeadCode;
528 }
529 // First, own control edge.
530 Node* m = n->find_exact_control(n->in(0));
531 if (m != nullptr) {
532 if (m->is_top()) {
533 return DomResult::EncounteredDeadCode; // Conservative answer for dead code
534 }
535 dom_list.push(m);
536 }
537 // Now, the rest of edges.
538 uint cnt = n->req();
539 for (uint i = 1; i < cnt; i++) {
540 m = n->find_exact_control(n->in(i));
541 if (m == nullptr || m->is_top()) {
542 continue;
543 }
544 dom_list.push(m);
545 }
546 }
547 }
548 return only_dominating_controls ? DomResult::Dominate : DomResult::NotDominate;
549 }
550 }
551
552 //---------------------detect_ptr_independence---------------------------------
553 // Used by MemNode::find_previous_store to prove that two base
554 // pointers are never equal.
555 // The pointers are accompanied by their associated allocations,
556 // if any, which have been previously discovered by the caller.
557 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
558 Node* p2, AllocateNode* a2,
559 PhaseGVN* phase) {
560 // Trivial case: Non-overlapping values. Be careful, we can cast a raw pointer to an oop (e.g. in
561 // the allocation pattern) so joining the types only works if both are oops. join may also give
562 // an incorrect result when both pointers are nullable and the result is supposed to be
563 // TypePtr::NULL_PTR, so we exclude that case.
564 const Type* p1_type = p1->bottom_type();
565 const Type* p2_type = p2->bottom_type();
566 if (p1_type != p2_type && p1_type->isa_oopptr() && p2_type->isa_oopptr() &&
567 (!p1_type->maybe_null() || !p2_type->maybe_null()) &&
568 p1_type->join(p2_type)->empty()) {
569 return true;
570 }
571
572 // Attempt to prove that these two pointers cannot be aliased.
573 // They may both manifestly be allocations, and they should differ.
574 // Or, if they are not both allocations, they can be distinct constants.
575 // Otherwise, one is an allocation and the other a pre-existing value.
576 if (a1 == nullptr && a2 == nullptr) { // neither an allocation
577 return (p1 != p2) && p1->is_Con() && p2->is_Con();
578 } else if (a1 != nullptr && a2 != nullptr) { // both allocations
579 return (a1 != a2);
580 } else if (a1 != nullptr) { // one allocation a1
581 // (Note: p2->is_Con implies p2->in(0)->is_Root, which dominates.)
582 return all_controls_dominate(p2->uncast(), a1, phase);
583 } else { //(a2 != null) // one allocation a2
584 return all_controls_dominate(p1->uncast(), a2, phase);
585 }
586 return false;
587 }
588
589 // Find an arraycopy ac that produces the memory state represented by parameter mem.
590 // Return ac if
591 // (a) can_see_stored_value=true and ac must have set the value for this load or if
592 // (b) can_see_stored_value=false and ac could have set the value for this load or if
593 // (c) can_see_stored_value=false and ac cannot have set the value for this load.
594 // In case (c) change the parameter mem to the memory input of ac to skip it
595 // when searching stored value.
596 // Otherwise return null.
597 Node* LoadNode::find_previous_arraycopy(PhaseValues* phase, Node* ld_alloc, Node*& mem, bool can_see_stored_value) const {
598 ArrayCopyNode* ac = find_array_copy_clone(ld_alloc, mem);
599 if (ac != nullptr) {
600 Node* ld_addp = in(MemNode::Address);
601 Node* src = ac->in(ArrayCopyNode::Src);
602 const TypeAryPtr* ary_t = phase->type(src)->isa_aryptr();
603
604 // This is a load from a cloned array. The corresponding arraycopy ac must
605 // have set the value for the load and we can return ac but only if the load
606 // is known to be within bounds. This is checked below.
607 if (ary_t != nullptr && ld_addp->is_AddP()) {
608 Node* ld_offs = ld_addp->in(AddPNode::Offset);
609 BasicType ary_elem = ary_t->elem()->array_element_basic_type();
610 jlong header = arrayOopDesc::base_offset_in_bytes(ary_elem);
611 jlong elemsize = type2aelembytes(ary_elem);
612
613 const TypeX* ld_offs_t = phase->type(ld_offs)->isa_intptr_t();
614 const TypeInt* sizetype = ary_t->size();
615
616 if (ld_offs_t->_lo >= header && ld_offs_t->_hi < (sizetype->_lo * elemsize + header)) {
617 // The load is known to be within bounds. It receives its value from ac.
618 return ac;
619 }
620 // The load is known to be out-of-bounds.
621 }
622 // The load could be out-of-bounds. It must not be hoisted but must remain
623 // dependent on the runtime range check. This is achieved by returning null.
624 } else if (mem->is_Proj() && mem->in(0) != nullptr && mem->in(0)->is_ArrayCopy()) {
625 ArrayCopyNode* ac = mem->in(0)->as_ArrayCopy();
626
627 if (ac->is_arraycopy_validated() ||
628 ac->is_copyof_validated() ||
629 ac->is_copyofrange_validated()) {
630 Node* ld_addp = in(MemNode::Address);
631 if (ld_addp->is_AddP()) {
632 Node* ld_base = ld_addp->in(AddPNode::Address);
633 Node* ld_offs = ld_addp->in(AddPNode::Offset);
634
635 Node* dest = ac->in(ArrayCopyNode::Dest);
636
637 if (dest == ld_base) {
638 const TypeX* ld_offs_t = phase->type(ld_offs)->isa_intptr_t();
639 assert(!ld_offs_t->empty(), "dead reference should be checked already");
640 // Take into account vector or unsafe access size
641 jlong ld_size_in_bytes = (jlong)memory_size();
642 jlong offset_hi = ld_offs_t->_hi + ld_size_in_bytes - 1;
643 offset_hi = MIN2(offset_hi, (jlong)(TypeX::MAX->_hi)); // Take care for overflow in 32-bit VM
644 if (ac->modifies(ld_offs_t->_lo, (intptr_t)offset_hi, phase, can_see_stored_value)) {
645 return ac;
646 }
647 if (!can_see_stored_value) {
648 mem = ac->in(TypeFunc::Memory);
649 return ac;
650 }
651 }
652 }
653 }
654 }
655 return nullptr;
656 }
657
658 ArrayCopyNode* MemNode::find_array_copy_clone(Node* ld_alloc, Node* mem) const {
659 if (mem->is_Proj() && mem->in(0) != nullptr && (mem->in(0)->Opcode() == Op_MemBarStoreStore ||
660 mem->in(0)->Opcode() == Op_MemBarCPUOrder)) {
661 if (ld_alloc != nullptr) {
662 // Check if there is an array copy for a clone
663 Node* mb = mem->in(0);
664 ArrayCopyNode* ac = nullptr;
665 if (mb->in(0) != nullptr && mb->in(0)->is_Proj() &&
666 mb->in(0)->in(0) != nullptr && mb->in(0)->in(0)->is_ArrayCopy()) {
667 ac = mb->in(0)->in(0)->as_ArrayCopy();
668 } else {
669 // Step over GC barrier when ReduceInitialCardMarks is disabled
670 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
671 Node* control_proj_ac = bs->step_over_gc_barrier(mb->in(0));
672
673 if (control_proj_ac->is_Proj() && control_proj_ac->in(0)->is_ArrayCopy()) {
674 ac = control_proj_ac->in(0)->as_ArrayCopy();
675 }
676 }
677
678 if (ac != nullptr && ac->is_clonebasic()) {
679 AllocateNode* alloc = AllocateNode::Ideal_allocation(ac->in(ArrayCopyNode::Dest));
680 if (alloc != nullptr && alloc == ld_alloc) {
681 return ac;
682 }
683 }
684 }
685 }
686 return nullptr;
687 }
688
689 // The logic for reordering loads and stores uses four steps:
690 // (a) Walk carefully past stores and initializations which we
691 // can prove are independent of this load.
692 // (b) Observe that the next memory state makes an exact match
693 // with self (load or store), and locate the relevant store.
694 // (c) Ensure that, if we were to wire self directly to the store,
695 // the optimizer would fold it up somehow.
696 // (d) Do the rewiring, and return, depending on some other part of
697 // the optimizer to fold up the load.
698 // This routine handles steps (a) and (b). Steps (c) and (d) are
699 // specific to loads and stores, so they are handled by the callers.
700 // (Currently, only LoadNode::Ideal has steps (c), (d). More later.)
701 //
702 Node* MemNode::find_previous_store(PhaseGVN* phase) {
703 AccessAnalyzer analyzer(phase, this);
704
705 Node* mem = in(MemNode::Memory); // start searching here...
706 int cnt = 50; // Cycle limiter
707 for (;; cnt--) {
708 // While we can dance past unrelated stores...
709 if (phase->type(mem) == Type::TOP) {
710 // Encounter a dead node
711 return phase->C->top();
712 } else if (cnt <= 0) {
713 // Caught in cycle or a complicated dance?
714 return nullptr;
715 } else if (mem->is_Phi()) {
716 return nullptr;
717 }
718
719 AccessAnalyzer::AccessIndependence independence = analyzer.detect_access_independence(mem);
720 if (independence.independent) {
721 // (a) advance through the independent store
722 mem = independence.mem;
723 assert(mem != nullptr, "must not be nullptr");
724 } else {
725 // (b) found the store that this access observes if this is not null
726 // Otherwise, give up if it is null
727 return independence.mem;
728 }
729 }
730
731 return nullptr; // bail out
732 }
733
734 //----------------------calculate_adr_type-------------------------------------
735 // Helper function. Notices when the given type of address hits top or bottom.
736 // Also, asserts a cross-check of the type against the expected address type.
737 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
738 if (t == Type::TOP) return nullptr; // does not touch memory any more?
739 #ifdef ASSERT
740 if (!VerifyAliases || VMError::is_error_reported() || Node::in_dump()) cross_check = nullptr;
741 #endif
742 const TypePtr* tp = t->isa_ptr();
743 if (tp == nullptr) {
744 assert(cross_check == nullptr || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
745 return TypePtr::BOTTOM; // touches lots of memory
746 } else {
747 #ifdef ASSERT
748 // %%%% [phh] We don't check the alias index if cross_check is
749 // TypeRawPtr::BOTTOM. Needs to be investigated.
750 if (cross_check != nullptr &&
751 cross_check != TypePtr::BOTTOM &&
752 cross_check != TypeRawPtr::BOTTOM) {
753 // Recheck the alias index, to see if it has changed (due to a bug).
754 Compile* C = Compile::current();
755 assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
756 "must stay in the original alias category");
757 // The type of the address must be contained in the adr_type,
758 // disregarding "null"-ness.
759 // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
760 const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
761 assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(),
762 "real address must not escape from expected memory type");
763 }
764 #endif
765 return tp;
766 }
767 }
768
769 uint8_t MemNode::barrier_data(const Node* n) {
770 if (n->is_LoadStore()) {
771 return n->as_LoadStore()->barrier_data();
772 } else if (n->is_Mem()) {
773 return n->as_Mem()->barrier_data();
774 }
775 return 0;
776 }
777
778 AccessAnalyzer::AccessAnalyzer(PhaseGVN* phase, MemNode* n)
779 : _phase(phase), _n(n), _memory_size(n->memory_size()), _alias_idx(-1) {
780 Node* adr = _n->in(MemNode::Address);
781 _offset = 0;
782 _base = AddPNode::Ideal_base_and_offset(adr, _phase, _offset);
783 _maybe_raw = MemNode::check_if_adr_maybe_raw(adr);
784 _alloc = AllocateNode::Ideal_allocation(_base);
785 _adr_type = _n->adr_type();
786
787 if (_adr_type != nullptr && _adr_type->base() != TypePtr::AnyPtr) {
788 // Avoid the cases that will upset Compile::get_alias_index
789 _alias_idx = _phase->C->get_alias_index(_adr_type);
790 assert(_alias_idx != Compile::AliasIdxTop, "must not be a dead node");
791 assert(_alias_idx != Compile::AliasIdxBot || !phase->C->do_aliasing(), "must not be a very wide access");
792 }
793 }
794
795 // Decide whether the memory accessed by '_n' and 'other' may overlap. This function may be used
796 // when we want to walk the memory graph to fold a load, or when we want to hoist a load above a
797 // loop when there are no stores that may overlap with the load inside the loop.
798 AccessAnalyzer::AccessIndependence AccessAnalyzer::detect_access_independence(Node* other) const {
799 assert(_phase->type(other) == Type::MEMORY, "must be a memory node %s", other->Name());
800 assert(!other->is_Phi(), "caller must handle Phi");
801
802 if (_adr_type == nullptr) {
803 // This means the access is dead
804 return {false, _phase->C->top()};
805 } else if (_adr_type->base() == TypePtr::AnyPtr) {
806 // An example for this case is an access into the memory address 0 performed using Unsafe
807 assert(_adr_type->ptr() == TypePtr::Null, "MemNode should never access a wide memory");
808 return {false, nullptr};
809 }
810
811 if (_offset == Type::OffsetBot) {
812 // cannot unalias unless there are precise offsets
813 return {false, nullptr};
814 }
815
816 const TypeOopPtr* adr_oop_type = _adr_type->isa_oopptr();
817 Node* prev = other;
818 if (other->is_Store()) {
819 Node* st_adr = other->in(MemNode::Address);
820 intptr_t st_offset = 0;
821 Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, _phase, st_offset);
822 if (st_base == nullptr) {
823 // inscrutable pointer
824 return {false, nullptr};
825 }
826
827 // If the bases are the same and the offsets are the same, it seems that this is the exact
828 // store we are looking for, the caller will check if the type of the store matches using
829 // MemNode::can_see_stored_value
830 if (st_base == _base && st_offset == _offset) {
831 return {false, other};
832 }
833
834 // If it is provable that the memory accessed by 'other' does not overlap the memory accessed
835 // by '_n', we may walk past 'other'.
836 // For raw accesses, 2 accesses are independent if they have the same base and the offsets
837 // say that they do not overlap.
838 // For heap accesses, 2 accesses are independent if either the bases are provably different
839 // at runtime or the offsets say that the accesses do not overlap.
840 if ((_maybe_raw || MemNode::check_if_adr_maybe_raw(st_adr)) && st_base != _base) {
841 // Raw accesses can only be provably independent if they have the same base
842 return {false, nullptr};
843 }
844
845 // If the offsets say that the accesses do not overlap, then it is provable that 'other' and
846 // '_n' do not overlap. For example, a LoadI from Object+8 is independent from a StoreL into
847 // Object+12, no matter what the bases are.
848 if (st_offset != _offset && st_offset != Type::OffsetBot) {
849 const int MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize);
850 assert(other->as_Store()->memory_size() <= MAX_STORE, "");
851 if (st_offset >= _offset + _memory_size ||
852 st_offset <= _offset - MAX_STORE ||
853 st_offset <= _offset - other->as_Store()->memory_size()) {
854 // Success: The offsets are provably independent.
855 // (You may ask, why not just test st_offset != offset and be done?
856 // The answer is that stores of different sizes can co-exist
857 // in the same sequence of RawMem effects. We sometimes initialize
858 // a whole 'tile' of array elements with a single jint or jlong.)
859 return {true, other->in(MemNode::Memory)};
860 }
861 }
862
863 // Same base and overlapping offsets, it seems provable that the accesses overlap, give up
864 if (st_base == _base) {
865 return {false, nullptr};
866 }
867
868 // Try to prove that 2 different base nodes at compile time are different values at runtime
869 bool known_independent = false;
870 if (MemNode::detect_ptr_independence(_base, _alloc, st_base, AllocateNode::Ideal_allocation(st_base), _phase)) {
871 known_independent = true;
872 }
873
874 if (known_independent) {
875 return {true, other->in(MemNode::Memory)};
876 }
877 } else if (other->is_Proj() && other->in(0)->is_Initialize()) {
878 InitializeNode* st_init = other->in(0)->as_Initialize();
879 AllocateNode* st_alloc = st_init->allocation();
880 if (st_alloc == nullptr) {
881 // Something degenerated
882 return {false, nullptr};
883 }
884 bool known_identical = false;
885 bool known_independent = false;
886 if (_alloc == st_alloc) {
887 known_identical = true;
888 } else if (_alloc != nullptr) {
889 known_independent = true;
890 } else if (MemNode::all_controls_dominate(_base->uncast(), st_alloc, _phase)) {
891 known_independent = true;
892 }
893
894 if (known_independent) {
895 // The bases are provably independent: Either they are
896 // manifestly distinct allocations, or else the control
897 // of _base dominates the store's allocation.
898 if (_alias_idx == Compile::AliasIdxRaw) {
899 other = st_alloc->in(TypeFunc::Memory);
900 } else {
901 other = st_init->memory(_alias_idx);
902 }
903 return {true, other};
904 }
905
906 // If we are not looking at a store initializing the same
907 // allocation we are loading from, we lose.
908 if (known_identical) {
909 // From caller, can_see_stored_value will consult find_captured_store.
910 return {false, other};
911 }
912
913 } else if (_n->find_previous_arraycopy(_phase, _alloc, other, false) != nullptr) {
914 // Find an arraycopy that may or may not affect the MemNode
915 return {prev != other, other};
916 } else if (other->is_MergeMem()) {
917 return {true, other->as_MergeMem()->memory_at(_alias_idx)};
918 } else if (adr_oop_type != nullptr && adr_oop_type->is_known_instance_field()) {
919 // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
920 if (other->is_Proj() && other->in(0)->is_Call()) {
921 // ArrayCopyNodes processed here as well.
922 CallNode* call = other->in(0)->as_Call();
923 if (!call->may_modify(adr_oop_type, _phase)) {
924 return {true, call->in(TypeFunc::Memory)};
925 }
926 } else if (other->is_Proj() && other->in(0)->is_MemBar()) {
927 ArrayCopyNode* ac = nullptr;
928 if (!ArrayCopyNode::may_modify(adr_oop_type, other->in(0)->as_MemBar(), _phase, ac)) {
929 return {true, other->in(0)->in(TypeFunc::Memory)};
930 }
931 } else if (other->is_ClearArray()) {
932 if (ClearArrayNode::step_through(&other, (uint)adr_oop_type->instance_id(), _phase)) {
933 // (the call updated 'other' value)
934 return {true, other};
935 } else {
936 // Can not bypass initialization of the instance
937 // we are looking for.
938 return {false, other};
939 }
940 }
941 }
942
943 return {false, nullptr};
944 }
945
946 //=============================================================================
947 // Should LoadNode::Ideal() attempt to remove control edges?
948 bool LoadNode::can_remove_control() const {
949 return !has_pinned_control_dependency();
950 }
951 uint LoadNode::size_of() const { return sizeof(*this); }
952 bool LoadNode::cmp(const Node &n) const {
953 LoadNode& load = (LoadNode &)n;
954 return Type::equals(_type, load._type) &&
955 _control_dependency == load._control_dependency &&
956 _mo == load._mo;
957 }
958 const Type *LoadNode::bottom_type() const { return _type; }
959 uint LoadNode::ideal_reg() const {
960 return _type->ideal_reg();
961 }
962
963 #ifndef PRODUCT
964 void LoadNode::dump_spec(outputStream *st) const {
965 MemNode::dump_spec(st);
966 if( !Verbose && !WizardMode ) {
967 // standard dump does this in Verbose and WizardMode
968 st->print(" #"); _type->dump_on(st);
969 }
970 if (in(0) != nullptr && !depends_only_on_test()) {
971 st->print(" (does not depend only on test, ");
972 if (control_dependency() == UnknownControl) {
973 st->print("unknown control");
974 } else if (control_dependency() == Pinned) {
975 st->print("pinned");
976 } else if (adr_type() == TypeRawPtr::BOTTOM) {
977 st->print("raw access");
978 } else {
979 st->print("unknown reason");
980 }
981 st->print(")");
982 }
983 }
984 #endif
985
986 #ifdef ASSERT
987 //----------------------------is_immutable_value-------------------------------
988 // Helper function to allow a raw load without control edge for some cases
989 bool LoadNode::is_immutable_value(Node* adr) {
990 if (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() &&
991 adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal) {
992
993 jlong offset = adr->in(AddPNode::Offset)->find_intptr_t_con(-1);
994 int offsets[] = {
995 in_bytes(JavaThread::osthread_offset()),
996 in_bytes(JavaThread::threadObj_offset()),
997 in_bytes(JavaThread::vthread_offset()),
998 in_bytes(JavaThread::scopedValueCache_offset()),
999 };
1000
1001 for (size_t i = 0; i < sizeof offsets / sizeof offsets[0]; i++) {
1002 if (offset == offsets[i]) {
1003 return true;
1004 }
1005 }
1006 }
1007
1008 return false;
1009 }
1010 #endif
1011
1012 //----------------------------LoadNode::make-----------------------------------
1013 // Polymorphic factory method:
1014 Node* LoadNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, BasicType bt, MemOrd mo,
1015 ControlDependency control_dependency, bool require_atomic_access, bool unaligned, bool mismatched, bool unsafe, uint8_t barrier_data) {
1016 Compile* C = gvn.C;
1017 assert(adr->is_top() || C->get_alias_index(gvn.type(adr)->is_ptr()) == C->get_alias_index(adr_type), "adr and adr_type must agree");
1018
1019 // sanity check the alias category against the created node type
1020 assert(!(adr_type->isa_oopptr() &&
1021 adr_type->offset() == oopDesc::klass_offset_in_bytes()),
1022 "use LoadKlassNode instead");
1023 assert(!(adr_type->isa_aryptr() &&
1024 adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
1025 "use LoadRangeNode instead");
1026 // Check control edge of raw loads
1027 assert( ctl != nullptr || C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
1028 // oop will be recorded in oop map if load crosses safepoint
1029 rt->isa_oopptr() || is_immutable_value(adr),
1030 "raw memory operations should have control edge");
1031 LoadNode* load = nullptr;
1032 switch (bt) {
1033 case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break;
1034 case T_BYTE: load = new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break;
1035 case T_INT: load = new LoadINode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break;
1036 case T_CHAR: load = new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break;
1037 case T_SHORT: load = new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break;
1038 case T_LONG: load = new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic_access); break;
1039 case T_FLOAT: load = new LoadFNode (ctl, mem, adr, adr_type, rt, mo, control_dependency); break;
1040 case T_DOUBLE: load = new LoadDNode (ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic_access); break;
1041 case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency); break;
1042 case T_OBJECT:
1043 case T_NARROWOOP:
1044 #ifdef _LP64
1045 if (adr->bottom_type()->is_ptr_to_narrowoop()) {
1046 load = new LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency);
1047 } else
1048 #endif
1049 {
1050 assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop");
1051 load = new LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency);
1052 }
1053 break;
1054 default:
1055 ShouldNotReachHere();
1056 break;
1057 }
1058 assert(load != nullptr, "LoadNode should have been created");
1059 if (unaligned) {
1060 load->set_unaligned_access();
1061 }
1062 if (mismatched) {
1063 load->set_mismatched_access();
1064 }
1065 if (unsafe) {
1066 load->set_unsafe_access();
1067 }
1068 load->set_barrier_data(barrier_data);
1069 if (load->Opcode() == Op_LoadN) {
1070 Node* ld = gvn.transform(load);
1071 return new DecodeNNode(ld, ld->bottom_type()->make_ptr());
1072 }
1073
1074 return load;
1075 }
1076
1077 //------------------------------hash-------------------------------------------
1078 uint LoadNode::hash() const {
1079 // unroll addition of interesting fields
1080 return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
1081 }
1082
1083 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) {
1084 if ((atp != nullptr) && (atp->index() >= Compile::AliasIdxRaw)) {
1085 bool non_volatile = (atp->field() != nullptr) && !atp->field()->is_volatile();
1086 bool is_stable_ary = FoldStableValues &&
1087 (tp != nullptr) && (tp->isa_aryptr() != nullptr) &&
1088 tp->isa_aryptr()->is_stable();
1089
1090 return (eliminate_boxing && non_volatile) || is_stable_ary;
1091 }
1092
1093 return false;
1094 }
1095
1096 // Is the value loaded previously stored by an arraycopy? If so return
1097 // a load node that reads from the source array so we may be able to
1098 // optimize out the ArrayCopy node later.
1099 Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseGVN* phase) const {
1100 Node* ld_adr = in(MemNode::Address);
1101 intptr_t ld_off = 0;
1102 AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
1103 Node* ac = find_previous_arraycopy(phase, ld_alloc, st, true);
1104 if (ac != nullptr) {
1105 assert(ac->is_ArrayCopy(), "what kind of node can this be?");
1106
1107 Node* mem = ac->in(TypeFunc::Memory);
1108 Node* ctl = ac->in(0);
1109 Node* src = ac->in(ArrayCopyNode::Src);
1110
1111 if (!ac->as_ArrayCopy()->is_clonebasic() && !phase->type(src)->isa_aryptr()) {
1112 return nullptr;
1113 }
1114
1115 // load depends on the tests that validate the arraycopy
1116 LoadNode* ld = clone_pinned();
1117 Node* addp = in(MemNode::Address)->clone();
1118 if (ac->as_ArrayCopy()->is_clonebasic()) {
1119 assert(ld_alloc != nullptr, "need an alloc");
1120 assert(addp->is_AddP(), "address must be addp");
1121 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1122 assert(bs->step_over_gc_barrier(addp->in(AddPNode::Base)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern");
1123 assert(bs->step_over_gc_barrier(addp->in(AddPNode::Address)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern");
1124 addp->set_req(AddPNode::Base, src);
1125 addp->set_req(AddPNode::Address, src);
1126 } else {
1127 assert(ac->as_ArrayCopy()->is_arraycopy_validated() ||
1128 ac->as_ArrayCopy()->is_copyof_validated() ||
1129 ac->as_ArrayCopy()->is_copyofrange_validated(), "only supported cases");
1130 assert(addp->in(AddPNode::Base) == addp->in(AddPNode::Address), "should be");
1131 addp->set_req(AddPNode::Base, src);
1132 addp->set_req(AddPNode::Address, src);
1133
1134 const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr();
1135 BasicType ary_elem = ary_t->isa_aryptr()->elem()->array_element_basic_type();
1136 if (is_reference_type(ary_elem, true)) ary_elem = T_OBJECT;
1137
1138 uint header = arrayOopDesc::base_offset_in_bytes(ary_elem);
1139 uint shift = exact_log2(type2aelembytes(ary_elem));
1140
1141 Node* diff = phase->transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
1142 #ifdef _LP64
1143 diff = phase->transform(new ConvI2LNode(diff));
1144 #endif
1145 diff = phase->transform(new LShiftXNode(diff, phase->intcon(shift)));
1146
1147 Node* offset = phase->transform(new AddXNode(addp->in(AddPNode::Offset), diff));
1148 addp->set_req(AddPNode::Offset, offset);
1149 }
1150 addp = phase->transform(addp);
1151 #ifdef ASSERT
1152 const TypePtr* adr_type = phase->type(addp)->is_ptr();
1153 ld->_adr_type = adr_type;
1154 #endif
1155 ld->set_req(MemNode::Address, addp);
1156 ld->set_req(0, ctl);
1157 ld->set_req(MemNode::Memory, mem);
1158 return ld;
1159 }
1160 return nullptr;
1161 }
1162
1163 // This routine exists to make sure this set of tests is done the same
1164 // everywhere. We need to make a coordinated change: first LoadNode::Ideal
1165 // will change the graph shape in a way which makes memory alive twice at the
1166 // same time (uses the Oracle model of aliasing), then some
1167 // LoadXNode::Identity will fold things back to the equivalence-class model
1168 // of aliasing.
1169 Node* LoadNode::can_see_stored_value_through_membars(Node* st, PhaseValues* phase) const {
1170 Node* ld_adr = in(MemNode::Address);
1171 const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
1172 Compile::AliasType* atp = (tp != nullptr) ? phase->C->alias_type(tp) : nullptr;
1173
1174 if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) {
1175 uint alias_idx = atp->index();
1176 Node* result = nullptr;
1177 Node* current = st;
1178 // Skip through chains of MemBarNodes checking the MergeMems for new states for the slice of
1179 // this load. Stop once any other kind of node is encountered.
1180 //
1181 // In principle, folding a load is moving it up until it meets a matching store.
1182 //
1183 // store(ptr, v); store(ptr, v); store(ptr, v);
1184 // membar1; -> membar1; -> load(ptr);
1185 // membar2; load(ptr); membar1;
1186 // load(ptr); membar2; membar2;
1187 //
1188 // So, we can decide which kinds of barriers we can walk past. It is not safe to step over
1189 // MemBarCPUOrder, even if the memory is not rewritable, because alias info above them may be
1190 // inaccurate (e.g., due to mixed/mismatched unsafe accesses).
1191 bool is_final_mem = !atp->is_rewritable();
1192 while (current->is_Proj()) {
1193 int opc = current->in(0)->Opcode();
1194 if ((is_final_mem && (opc == Op_MemBarAcquire || opc == Op_MemBarAcquireLock || opc == Op_LoadFence)) ||
1195 opc == Op_MemBarRelease ||
1196 opc == Op_StoreFence ||
1197 opc == Op_MemBarReleaseLock ||
1198 opc == Op_MemBarStoreStore ||
1199 opc == Op_StoreStoreFence) {
1200 Node* mem = current->in(0)->in(TypeFunc::Memory);
1201 if (mem->is_MergeMem()) {
1202 MergeMemNode* merge = mem->as_MergeMem();
1203 Node* new_st = merge->memory_at(alias_idx);
1204 if (new_st == merge->base_memory()) {
1205 // Keep searching
1206 current = new_st;
1207 continue;
1208 }
1209 // Save the new memory state for the slice and fall through
1210 // to exit.
1211 result = new_st;
1212 }
1213 }
1214 break;
1215 }
1216 if (result != nullptr) {
1217 st = result;
1218 }
1219 }
1220
1221 Node* res = can_see_stored_value(st, phase);
1222 assert(res == nullptr || is_java_primitive(value_basic_type()) || res->bottom_type()->higher_equal(type()), "the fold is unsafe");
1223 return res;
1224 }
1225
1226 // If st is a store to the same location as this, return the stored value
1227 Node* MemNode::can_see_stored_value(Node* st, PhaseValues* phase) const {
1228 Node* ld_adr = in(MemNode::Address);
1229 intptr_t ld_off = 0;
1230 Node* ld_base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ld_off);
1231 Node* ld_alloc = AllocateNode::Ideal_allocation(ld_base);
1232 const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
1233
1234 // Loop around twice in the case Load -> Initialize -> Store.
1235 // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
1236 for (int trip = 0; trip <= 1; trip++) {
1237
1238 if (st->is_Store()) {
1239 Node* st_adr = st->in(MemNode::Address);
1240 if (st_adr != ld_adr) {
1241 // Try harder before giving up. Unify base pointers with casts (e.g., raw/non-raw pointers).
1242 intptr_t st_off = 0;
1243 Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_off);
1244 if (ld_base == nullptr) return nullptr;
1245 if (st_base == nullptr) return nullptr;
1246 if (!ld_base->eqv_uncast(st_base, /*keep_deps=*/true)) return nullptr;
1247 if (ld_off != st_off) return nullptr;
1248 if (ld_off == Type::OffsetBot) return nullptr;
1249 // Same base, same offset.
1250 // Possible improvement for arrays: check index value instead of absolute offset.
1251
1252 // At this point we have proven something like this setup:
1253 // B = << base >>
1254 // L = LoadQ(AddP(Check/CastPP(B), #Off))
1255 // S = StoreQ(AddP( B , #Off), V)
1256 // (Actually, we haven't yet proven the Q's are the same.)
1257 // In other words, we are loading from a casted version of
1258 // the same pointer-and-offset that we stored to.
1259 // Casted version may carry a dependency and it is respected.
1260 // Thus, we are able to replace L by V.
1261 }
1262 // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
1263 if (store_Opcode() != st->Opcode()) {
1264 return nullptr;
1265 }
1266 // LoadVector/StoreVector needs additional check to ensure the types match.
1267 if (st->is_StoreVector()) {
1268 if ((Opcode() != Op_LoadVector && Opcode() != Op_StoreVector) || st->Opcode() != Op_StoreVector) {
1269 // Some kind of masked access or gather/scatter
1270 return nullptr;
1271 }
1272
1273 const TypeVect* in_vt = st->as_StoreVector()->vect_type();
1274 const TypeVect* out_vt = is_Load() ? as_LoadVector()->vect_type() : as_StoreVector()->vect_type();
1275 if (in_vt != out_vt) {
1276 return nullptr;
1277 }
1278 }
1279
1280 // Even if we can see the store, we cannot fold the load if the store is not type safe (e.g.
1281 // store a j.l.Object into an array of j.l.String) because folding makes the compiler lose the
1282 // type information that the uses of this node may need. This is only necessary for pointers, we
1283 // can see the stored value of a LoadS even if it is an int because LoadSNode::Ideal will do the
1284 // necessary truncation.
1285 // The same phenomenon is not an issue for StoreNodes because they don't use res.
1286 Node* res = st->in(MemNode::ValueIn);
1287 if (is_Store() || is_java_primitive(value_basic_type()) || res->bottom_type()->higher_equal(bottom_type())) {
1288 return res;
1289 }
1290
1291 // Type-unsafe stores must be due to array polymorphism
1292 const TypePtr* adr_type = this->adr_type();
1293 assert(adr_type == nullptr || adr_type->isa_aryptr() != nullptr, "unexpected type-unsafe store");
1294 return nullptr;
1295 }
1296
1297 // A load from a freshly-created object always returns zero.
1298 // (This can happen after LoadNode::Ideal resets the load's memory input
1299 // to find_captured_store, which returned InitializeNode::zero_memory.)
1300 if (st->is_Proj() && st->in(0)->is_Allocate() &&
1301 (st->in(0) == ld_alloc) &&
1302 (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) {
1303 // return a zero value for the load's basic type
1304 // (This is one of the few places where a generic PhaseTransform
1305 // can create new nodes. Think of it as lazily manifesting
1306 // virtually pre-existing constants.)
1307 if (value_basic_type() != T_VOID) {
1308 if (ReduceBulkZeroing || find_array_copy_clone(ld_alloc, in(MemNode::Memory)) == nullptr) {
1309 // If ReduceBulkZeroing is disabled, we need to check if the allocation does not belong to an
1310 // ArrayCopyNode clone. If it does, then we cannot assume zero since the initialization is done
1311 // by the ArrayCopyNode.
1312 return phase->zerocon(value_basic_type());
1313 }
1314 } else {
1315 // TODO: materialize all-zero vector constant
1316 assert(!isa_Load() || as_Load()->type()->isa_vect(), "");
1317 }
1318 }
1319
1320 // A load from an initialization barrier can match a captured store.
1321 if (st->is_Proj() && st->in(0)->is_Initialize()) {
1322 InitializeNode* init = st->in(0)->as_Initialize();
1323 AllocateNode* alloc = init->allocation();
1324 if ((alloc != nullptr) && (alloc == ld_alloc)) {
1325 // examine a captured store value
1326 st = init->find_captured_store(ld_off, memory_size(), phase);
1327 if (st != nullptr) {
1328 continue; // take one more trip around
1329 }
1330 }
1331 }
1332
1333 // Load boxed value from result of valueOf() call is input parameter.
1334 if (this->is_Load() && ld_adr->is_AddP() &&
1335 (tp != nullptr) && tp->is_ptr_to_boxed_value()) {
1336 intptr_t ignore = 0;
1337 Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore);
1338 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1339 base = bs->step_over_gc_barrier(base);
1340 if (base != nullptr && base->is_Proj() &&
1341 base->as_Proj()->_con == TypeFunc::Parms &&
1342 base->in(0)->is_CallStaticJava() &&
1343 base->in(0)->as_CallStaticJava()->is_boxing_method()) {
1344 return base->in(0)->in(TypeFunc::Parms);
1345 }
1346 }
1347
1348 break;
1349 }
1350
1351 return nullptr;
1352 }
1353
1354 //----------------------is_instance_field_load_with_local_phi------------------
1355 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
1356 if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl &&
1357 in(Address)->is_AddP() ) {
1358 const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr();
1359 // Only instances and boxed values.
1360 if( t_oop != nullptr &&
1361 (t_oop->is_ptr_to_boxed_value() ||
1362 t_oop->is_known_instance_field()) &&
1363 t_oop->offset() != Type::OffsetBot &&
1364 t_oop->offset() != Type::OffsetTop) {
1365 return true;
1366 }
1367 }
1368 return false;
1369 }
1370
1371 //------------------------------Identity---------------------------------------
1372 // Loads are identity if previous store is to same address
1373 Node* LoadNode::Identity(PhaseGVN* phase) {
1374 // If the previous store-maker is the right kind of Store, and the store is
1375 // to the same address, then we are equal to the value stored.
1376 Node* mem = in(Memory);
1377 Node* value = can_see_stored_value_through_membars(mem, phase);
1378 if( value ) {
1379 // byte, short & char stores truncate naturally.
1380 // A load has to load the truncated value which requires
1381 // some sort of masking operation and that requires an
1382 // Ideal call instead of an Identity call.
1383 if (memory_size() < BytesPerInt) {
1384 // If the input to the store does not fit with the load's result type,
1385 // it must be truncated via an Ideal call.
1386 if (!phase->type(value)->higher_equal(phase->type(this)))
1387 return this;
1388 }
1389 // (This works even when value is a Con, but LoadNode::Value
1390 // usually runs first, producing the singleton type of the Con.)
1391 if (!has_pinned_control_dependency() || value->is_Con()) {
1392 return value;
1393 } else {
1394 return this;
1395 }
1396 }
1397
1398 if (has_pinned_control_dependency()) {
1399 return this;
1400 }
1401 // Search for an existing data phi which was generated before for the same
1402 // instance's field to avoid infinite generation of phis in a loop.
1403 Node *region = mem->in(0);
1404 if (is_instance_field_load_with_local_phi(region)) {
1405 const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr();
1406 int this_index = phase->C->get_alias_index(addr_t);
1407 int this_offset = addr_t->offset();
1408 int this_iid = addr_t->instance_id();
1409 if (!addr_t->is_known_instance() &&
1410 addr_t->is_ptr_to_boxed_value()) {
1411 // Use _idx of address base (could be Phi node) for boxed values.
1412 intptr_t ignore = 0;
1413 Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1414 if (base == nullptr) {
1415 return this;
1416 }
1417 this_iid = base->_idx;
1418 }
1419 const Type* this_type = bottom_type();
1420 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1421 Node* phi = region->fast_out(i);
1422 if (phi->is_Phi() && phi != mem &&
1423 phi->as_Phi()->is_same_inst_field(this_type, (int)mem->_idx, this_iid, this_index, this_offset)) {
1424 return phi;
1425 }
1426 }
1427 }
1428
1429 return this;
1430 }
1431
1432 // Construct an equivalent unsigned load.
1433 Node* LoadNode::convert_to_unsigned_load(PhaseGVN& gvn) {
1434 BasicType bt = T_ILLEGAL;
1435 const Type* rt = nullptr;
1436 switch (Opcode()) {
1437 case Op_LoadUB: return this;
1438 case Op_LoadUS: return this;
1439 case Op_LoadB: bt = T_BOOLEAN; rt = TypeInt::UBYTE; break;
1440 case Op_LoadS: bt = T_CHAR; rt = TypeInt::CHAR; break;
1441 default:
1442 assert(false, "no unsigned variant: %s", Name());
1443 return nullptr;
1444 }
1445 const Type* mem_t = gvn.type(in(MemNode::Address));
1446 if (mem_t == Type::TOP) {
1447 return gvn.C->top();
1448 }
1449 return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1450 mem_t->is_ptr(), rt, bt, _mo, _control_dependency,
1451 false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access());
1452 }
1453
1454 // Construct an equivalent signed load.
1455 Node* LoadNode::convert_to_signed_load(PhaseGVN& gvn) {
1456 BasicType bt = T_ILLEGAL;
1457 const Type* rt = nullptr;
1458 switch (Opcode()) {
1459 case Op_LoadUB: bt = T_BYTE; rt = TypeInt::BYTE; break;
1460 case Op_LoadUS: bt = T_SHORT; rt = TypeInt::SHORT; break;
1461 case Op_LoadB: // fall through
1462 case Op_LoadS: // fall through
1463 case Op_LoadI: // fall through
1464 case Op_LoadL: return this;
1465 default:
1466 assert(false, "no signed variant: %s", Name());
1467 return nullptr;
1468 }
1469 const Type* mem_t = gvn.type(in(MemNode::Address));
1470 if (mem_t == Type::TOP) {
1471 return gvn.C->top();
1472 }
1473 return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1474 mem_t->is_ptr(), rt, bt, _mo, _control_dependency,
1475 false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access());
1476 }
1477
1478 bool LoadNode::has_reinterpret_variant(const Type* rt) {
1479 BasicType bt = rt->basic_type();
1480 switch (Opcode()) {
1481 case Op_LoadI: return (bt == T_FLOAT);
1482 case Op_LoadL: return (bt == T_DOUBLE);
1483 case Op_LoadF: return (bt == T_INT);
1484 case Op_LoadD: return (bt == T_LONG);
1485
1486 default: return false;
1487 }
1488 }
1489
1490 Node* LoadNode::convert_to_reinterpret_load(PhaseGVN& gvn, const Type* rt) {
1491 BasicType bt = rt->basic_type();
1492 assert(has_reinterpret_variant(rt), "no reinterpret variant: %s %s", Name(), type2name(bt));
1493 bool is_mismatched = is_mismatched_access();
1494 const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr();
1495 if (raw_type == nullptr) {
1496 is_mismatched = true; // conservatively match all non-raw accesses as mismatched
1497 }
1498 const int op = Opcode();
1499 bool require_atomic_access = (op == Op_LoadL && ((LoadLNode*)this)->require_atomic_access()) ||
1500 (op == Op_LoadD && ((LoadDNode*)this)->require_atomic_access());
1501 const Type* mem_t = gvn.type(in(MemNode::Address));
1502 if (mem_t == Type::TOP) {
1503 return gvn.C->top();
1504 }
1505 return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1506 mem_t->is_ptr(), rt, bt, _mo, _control_dependency,
1507 require_atomic_access, is_unaligned_access(), is_mismatched);
1508 }
1509
1510 bool StoreNode::has_reinterpret_variant(const Type* vt) {
1511 BasicType bt = vt->basic_type();
1512 switch (Opcode()) {
1513 case Op_StoreI: return (bt == T_FLOAT);
1514 case Op_StoreL: return (bt == T_DOUBLE);
1515 case Op_StoreF: return (bt == T_INT);
1516 case Op_StoreD: return (bt == T_LONG);
1517
1518 default: return false;
1519 }
1520 }
1521
1522 Node* StoreNode::convert_to_reinterpret_store(PhaseGVN& gvn, Node* val, const Type* vt) {
1523 BasicType bt = vt->basic_type();
1524 assert(has_reinterpret_variant(vt), "no reinterpret variant: %s %s", Name(), type2name(bt));
1525 const int op = Opcode();
1526 bool require_atomic_access = (op == Op_StoreL && ((StoreLNode*)this)->require_atomic_access()) ||
1527 (op == Op_StoreD && ((StoreDNode*)this)->require_atomic_access());
1528 const Type* mem_t = gvn.type(in(MemNode::Address));
1529 if (mem_t == Type::TOP) {
1530 return gvn.C->top();
1531 }
1532 StoreNode* st = StoreNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
1533 mem_t->is_ptr(), val, bt, _mo, require_atomic_access);
1534
1535 bool is_mismatched = is_mismatched_access();
1536 const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr();
1537 if (raw_type == nullptr) {
1538 is_mismatched = true; // conservatively match all non-raw accesses as mismatched
1539 }
1540 if (is_mismatched) {
1541 st->set_mismatched_access();
1542 }
1543 return st;
1544 }
1545
1546 // We're loading from an object which has autobox behaviour.
1547 // If this object is result of a valueOf call we'll have a phi
1548 // merging a newly allocated object and a load from the cache.
1549 // We want to replace this load with the original incoming
1550 // argument to the valueOf call.
1551 Node* LoadNode::eliminate_autobox(PhaseIterGVN* igvn) {
1552 assert(igvn->C->eliminate_boxing(), "sanity");
1553 intptr_t ignore = 0;
1554 Node* base = AddPNode::Ideal_base_and_offset(in(Address), igvn, ignore);
1555 if ((base == nullptr) || base->is_Phi()) {
1556 // Push the loads from the phi that comes from valueOf up
1557 // through it to allow elimination of the loads and the recovery
1558 // of the original value. It is done in split_through_phi().
1559 return nullptr;
1560 } else if (base->is_Load() ||
1561 (base->is_DecodeN() && base->in(1)->is_Load())) {
1562 // Eliminate the load of boxed value for integer types from the cache
1563 // array by deriving the value from the index into the array.
1564 // Capture the offset of the load and then reverse the computation.
1565
1566 // Get LoadN node which loads a boxing object from 'cache' array.
1567 if (base->is_DecodeN()) {
1568 base = base->in(1);
1569 }
1570 if (!base->in(Address)->is_AddP()) {
1571 return nullptr; // Complex address
1572 }
1573 AddPNode* address = base->in(Address)->as_AddP();
1574 Node* cache_base = address->in(AddPNode::Base);
1575 if ((cache_base != nullptr) && cache_base->is_DecodeN()) {
1576 // Get ConP node which is static 'cache' field.
1577 cache_base = cache_base->in(1);
1578 }
1579 if ((cache_base != nullptr) && cache_base->is_Con()) {
1580 const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr();
1581 if ((base_type != nullptr) && base_type->is_autobox_cache()) {
1582 Node* elements[4];
1583 int shift = exact_log2(type2aelembytes(T_OBJECT));
1584 int count = address->unpack_offsets(elements, ARRAY_SIZE(elements));
1585 if (count > 0 && elements[0]->is_Con() &&
1586 (count == 1 ||
1587 (count == 2 && elements[1]->Opcode() == Op_LShiftX &&
1588 elements[1]->in(2) == igvn->intcon(shift)))) {
1589 ciObjArray* array = base_type->const_oop()->as_obj_array();
1590 // Fetch the box object cache[0] at the base of the array and get its value
1591 ciInstance* box = array->obj_at(0)->as_instance();
1592 ciInstanceKlass* ik = box->klass()->as_instance_klass();
1593 assert(ik->is_box_klass(), "sanity");
1594 assert(ik->nof_nonstatic_fields() == 1, "change following code");
1595 if (ik->nof_nonstatic_fields() == 1) {
1596 // This should be true nonstatic_field_at requires calling
1597 // nof_nonstatic_fields so check it anyway
1598 ciConstant c = box->field_value(ik->nonstatic_field_at(0));
1599 BasicType bt = c.basic_type();
1600 // Only integer types have boxing cache.
1601 assert(bt == T_BOOLEAN || bt == T_CHAR ||
1602 bt == T_BYTE || bt == T_SHORT ||
1603 bt == T_INT || bt == T_LONG, "wrong type = %s", type2name(bt));
1604 jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int();
1605 if (cache_low != (int)cache_low) {
1606 return nullptr; // should not happen since cache is array indexed by value
1607 }
1608 jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift);
1609 if (offset != (int)offset) {
1610 return nullptr; // should not happen since cache is array indexed by value
1611 }
1612 // Add up all the offsets making of the address of the load
1613 Node* result = elements[0];
1614 for (int i = 1; i < count; i++) {
1615 result = igvn->transform(new AddXNode(result, elements[i]));
1616 }
1617 // Remove the constant offset from the address and then
1618 result = igvn->transform(new AddXNode(result, igvn->MakeConX(-(int)offset)));
1619 // remove the scaling of the offset to recover the original index.
1620 if (result->Opcode() == Op_LShiftX && result->in(2) == igvn->intcon(shift)) {
1621 // Peel the shift off directly but wrap it in a dummy node
1622 // since Ideal can't return existing nodes
1623 igvn->_worklist.push(result); // remove dead node later
1624 result = new RShiftXNode(result->in(1), igvn->intcon(0));
1625 } else if (result->is_Add() && result->in(2)->is_Con() &&
1626 result->in(1)->Opcode() == Op_LShiftX &&
1627 result->in(1)->in(2) == igvn->intcon(shift)) {
1628 // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z)
1629 // but for boxing cache access we know that X<<Z will not overflow
1630 // (there is range check) so we do this optimizatrion by hand here.
1631 igvn->_worklist.push(result); // remove dead node later
1632 Node* add_con = new RShiftXNode(result->in(2), igvn->intcon(shift));
1633 result = new AddXNode(result->in(1)->in(1), igvn->transform(add_con));
1634 } else {
1635 result = new RShiftXNode(result, igvn->intcon(shift));
1636 }
1637 #ifdef _LP64
1638 if (bt != T_LONG) {
1639 result = new ConvL2INode(igvn->transform(result));
1640 }
1641 #else
1642 if (bt == T_LONG) {
1643 result = new ConvI2LNode(igvn->transform(result));
1644 }
1645 #endif
1646 // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
1647 // Need to preserve unboxing load type if it is unsigned.
1648 switch(this->Opcode()) {
1649 case Op_LoadUB:
1650 result = new AndINode(igvn->transform(result), igvn->intcon(0xFF));
1651 break;
1652 case Op_LoadUS:
1653 result = new AndINode(igvn->transform(result), igvn->intcon(0xFFFF));
1654 break;
1655 }
1656 return result;
1657 }
1658 }
1659 }
1660 }
1661 }
1662 return nullptr;
1663 }
1664
1665 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) {
1666 Node* region = phi->in(0);
1667 if (region == nullptr) {
1668 return false; // Wait stable graph
1669 }
1670 uint cnt = phi->req();
1671 for (uint i = 1; i < cnt; i++) {
1672 Node* rc = region->in(i);
1673 if (rc == nullptr || phase->type(rc) == Type::TOP)
1674 return false; // Wait stable graph
1675 Node* in = phi->in(i);
1676 if (in == nullptr || phase->type(in) == Type::TOP)
1677 return false; // Wait stable graph
1678 }
1679 return true;
1680 }
1681
1682 //------------------------------split_through_phi------------------------------
1683 // Check whether a call to 'split_through_phi' would split this load through the
1684 // Phi *base*. This method is essentially a copy of the validations performed
1685 // by 'split_through_phi'. The first use of this method was in EA code as part
1686 // of simplification of allocation merges.
1687 // Some differences from original method (split_through_phi):
1688 // - If base->is_CastPP(): base = base->in(1)
1689 bool LoadNode::can_split_through_phi_base(PhaseGVN* phase) {
1690 Node* mem = in(Memory);
1691 Node* address = in(Address);
1692 intptr_t ignore = 0;
1693 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1694
1695 if (base == nullptr) {
1696 return false;
1697 }
1698
1699 if (base->is_CastPP()) {
1700 base = base->in(1);
1701 }
1702
1703 if (req() > 3 || !base->is_Phi()) {
1704 return false;
1705 }
1706
1707 if (!mem->is_Phi()) {
1708 if (!MemNode::all_controls_dominate(mem, base->in(0), phase)) {
1709 return false;
1710 }
1711 } else if (base->in(0) != mem->in(0)) {
1712 if (!MemNode::all_controls_dominate(mem, base->in(0), phase)) {
1713 return false;
1714 }
1715 }
1716
1717 return true;
1718 }
1719
1720 //------------------------------split_through_phi------------------------------
1721 // Split instance or boxed field load through Phi.
1722 Node* LoadNode::split_through_phi(PhaseGVN* phase, bool ignore_missing_instance_id) {
1723 if (req() > 3) {
1724 assert(is_LoadVector() && Opcode() != Op_LoadVector, "load has too many inputs");
1725 // LoadVector subclasses such as LoadVectorMasked have extra inputs that the logic below doesn't take into account
1726 return nullptr;
1727 }
1728 Node* mem = in(Memory);
1729 Node* address = in(Address);
1730 const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr();
1731
1732 assert((t_oop != nullptr) &&
1733 (ignore_missing_instance_id ||
1734 t_oop->is_known_instance_field() ||
1735 t_oop->is_ptr_to_boxed_value()), "invalid conditions");
1736
1737 Compile* C = phase->C;
1738 intptr_t ignore = 0;
1739 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1740 bool base_is_phi = (base != nullptr) && base->is_Phi();
1741 bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() &&
1742 (base != nullptr) && (base == address->in(AddPNode::Base)) &&
1743 phase->type(base)->higher_equal(TypePtr::NOTNULL);
1744
1745 if (!((mem->is_Phi() || base_is_phi) &&
1746 (ignore_missing_instance_id || load_boxed_values || t_oop->is_known_instance_field()))) {
1747 return nullptr; // Neither memory or base are Phi
1748 }
1749
1750 if (mem->is_Phi()) {
1751 if (!stable_phi(mem->as_Phi(), phase)) {
1752 return nullptr; // Wait stable graph
1753 }
1754 uint cnt = mem->req();
1755 // Check for loop invariant memory.
1756 if (cnt == 3) {
1757 for (uint i = 1; i < cnt; i++) {
1758 Node* in = mem->in(i);
1759 Node* m = optimize_memory_chain(in, t_oop, this, phase);
1760 if (m == mem) {
1761 if (i == 1) {
1762 // if the first edge was a loop, check second edge too.
1763 // If both are replaceable - we are in an infinite loop
1764 Node *n = optimize_memory_chain(mem->in(2), t_oop, this, phase);
1765 if (n == mem) {
1766 break;
1767 }
1768 }
1769 set_req(Memory, mem->in(cnt - i));
1770 return this; // made change
1771 }
1772 }
1773 }
1774 }
1775 if (base_is_phi) {
1776 if (!stable_phi(base->as_Phi(), phase)) {
1777 return nullptr; // Wait stable graph
1778 }
1779 uint cnt = base->req();
1780 // Check for loop invariant memory.
1781 if (cnt == 3) {
1782 for (uint i = 1; i < cnt; i++) {
1783 if (base->in(i) == base) {
1784 return nullptr; // Wait stable graph
1785 }
1786 }
1787 }
1788 }
1789
1790 // Split through Phi (see original code in loopopts.cpp).
1791 assert(ignore_missing_instance_id || C->have_alias_type(t_oop), "instance should have alias type");
1792
1793 // Do nothing here if Identity will find a value
1794 // (to avoid infinite chain of value phis generation).
1795 if (this != Identity(phase)) {
1796 return nullptr;
1797 }
1798
1799 // Select Region to split through.
1800 Node* region;
1801 DomResult dom_result = DomResult::Dominate;
1802 if (!base_is_phi) {
1803 assert(mem->is_Phi(), "sanity");
1804 region = mem->in(0);
1805 // Skip if the region dominates some control edge of the address.
1806 // We will check `dom_result` later.
1807 dom_result = MemNode::maybe_all_controls_dominate(address, region, phase);
1808 } else if (!mem->is_Phi()) {
1809 assert(base_is_phi, "sanity");
1810 region = base->in(0);
1811 // Skip if the region dominates some control edge of the memory.
1812 // We will check `dom_result` later.
1813 dom_result = MemNode::maybe_all_controls_dominate(mem, region, phase);
1814 } else if (base->in(0) != mem->in(0)) {
1815 assert(base_is_phi && mem->is_Phi(), "sanity");
1816 dom_result = MemNode::maybe_all_controls_dominate(mem, base->in(0), phase);
1817 if (dom_result == DomResult::Dominate) {
1818 region = base->in(0);
1819 } else {
1820 dom_result = MemNode::maybe_all_controls_dominate(address, mem->in(0), phase);
1821 if (dom_result == DomResult::Dominate) {
1822 region = mem->in(0);
1823 }
1824 // Otherwise we encountered a complex graph.
1825 }
1826 } else {
1827 assert(base->in(0) == mem->in(0), "sanity");
1828 region = mem->in(0);
1829 }
1830
1831 PhaseIterGVN* igvn = phase->is_IterGVN();
1832 if (dom_result != DomResult::Dominate) {
1833 if (dom_result == DomResult::EncounteredDeadCode) {
1834 // There is some dead code which eventually will be removed in IGVN.
1835 // Once this is the case, we get an unambiguous dominance result.
1836 // Push the node to the worklist again until the dead code is removed.
1837 igvn->_worklist.push(this);
1838 }
1839 return nullptr;
1840 }
1841
1842 Node* phi = nullptr;
1843 const Type* this_type = this->bottom_type();
1844 if (t_oop != nullptr && (t_oop->is_known_instance_field() || load_boxed_values)) {
1845 int this_index = C->get_alias_index(t_oop);
1846 int this_offset = t_oop->offset();
1847 int this_iid = t_oop->is_known_instance_field() ? t_oop->instance_id() : base->_idx;
1848 phi = new PhiNode(region, this_type, nullptr, mem->_idx, this_iid, this_index, this_offset);
1849 } else if (ignore_missing_instance_id) {
1850 phi = new PhiNode(region, this_type, nullptr, mem->_idx);
1851 } else {
1852 return nullptr;
1853 }
1854
1855 for (uint i = 1; i < region->req(); i++) {
1856 Node* x;
1857 Node* the_clone = nullptr;
1858 Node* in = region->in(i);
1859 if (region->is_CountedLoop() && region->as_Loop()->is_strip_mined() && i == LoopNode::EntryControl &&
1860 in != nullptr && in->is_OuterStripMinedLoop()) {
1861 // No node should go in the outer strip mined loop
1862 in = in->in(LoopNode::EntryControl);
1863 }
1864 if (in == nullptr || in == C->top()) {
1865 x = C->top(); // Dead path? Use a dead data op
1866 } else {
1867 x = this->clone(); // Else clone up the data op
1868 the_clone = x; // Remember for possible deletion.
1869 // Alter data node to use pre-phi inputs
1870 if (this->in(0) == region) {
1871 x->set_req(0, in);
1872 } else {
1873 x->set_req(0, nullptr);
1874 }
1875 if (mem->is_Phi() && (mem->in(0) == region)) {
1876 x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone.
1877 }
1878 if (address->is_Phi() && address->in(0) == region) {
1879 x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone
1880 }
1881 if (base_is_phi && (base->in(0) == region)) {
1882 Node* base_x = base->in(i); // Clone address for loads from boxed objects.
1883 Node* adr_x = phase->transform(AddPNode::make_with_base(base_x, address->in(AddPNode::Offset)));
1884 x->set_req(Address, adr_x);
1885 }
1886 }
1887 // Check for a 'win' on some paths
1888 const Type *t = x->Value(igvn);
1889
1890 bool singleton = t->singleton();
1891
1892 // See comments in PhaseIdealLoop::split_thru_phi().
1893 if (singleton && t == Type::TOP) {
1894 singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
1895 }
1896
1897 if (singleton) {
1898 x = igvn->makecon(t);
1899 } else {
1900 // We now call Identity to try to simplify the cloned node.
1901 // Note that some Identity methods call phase->type(this).
1902 // Make sure that the type array is big enough for
1903 // our new node, even though we may throw the node away.
1904 // (This tweaking with igvn only works because x is a new node.)
1905 igvn->set_type(x, t);
1906 // If x is a TypeNode, capture any more-precise type permanently into Node
1907 // otherwise it will be not updated during igvn->transform since
1908 // igvn->type(x) is set to x->Value() already.
1909 x->raise_bottom_type(t);
1910 Node* y = x->Identity(igvn);
1911 if (y != x) {
1912 x = y;
1913 } else {
1914 y = igvn->hash_find_insert(x);
1915 if (y) {
1916 x = y;
1917 } else {
1918 // Else x is a new node we are keeping
1919 // We do not need register_new_node_with_optimizer
1920 // because set_type has already been called.
1921 igvn->_worklist.push(x);
1922 }
1923 }
1924 }
1925 if (x != the_clone && the_clone != nullptr) {
1926 igvn->remove_dead_node(the_clone, PhaseIterGVN::NodeOrigin::Speculative);
1927 }
1928 phi->set_req(i, x);
1929 }
1930 // Record Phi
1931 igvn->register_new_node_with_optimizer(phi);
1932 return phi;
1933 }
1934
1935 AllocateNode* LoadNode::is_new_object_mark_load() const {
1936 if (Opcode() == Op_LoadX) {
1937 Node* address = in(MemNode::Address);
1938 AllocateNode* alloc = AllocateNode::Ideal_allocation(address);
1939 Node* mem = in(MemNode::Memory);
1940 if (alloc != nullptr && mem->is_Proj() &&
1941 mem->in(0) != nullptr &&
1942 mem->in(0) == alloc->initialization() &&
1943 alloc->initialization()->proj_out_or_null(0) != nullptr) {
1944 return alloc;
1945 }
1946 }
1947 return nullptr;
1948 }
1949
1950
1951 //------------------------------Ideal------------------------------------------
1952 // If the load is from Field memory and the pointer is non-null, it might be possible to
1953 // zero out the control input.
1954 // If the offset is constant and the base is an object allocation,
1955 // try to hook me up to the exact initializing store.
1956 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1957 if (has_pinned_control_dependency()) {
1958 return nullptr;
1959 }
1960 Node* p = MemNode::Ideal_common(phase, can_reshape);
1961 if (p) return (p == NodeSentinel) ? nullptr : p;
1962
1963 Node* ctrl = in(MemNode::Control);
1964 Node* address = in(MemNode::Address);
1965
1966 bool addr_mark = ((phase->type(address)->isa_oopptr() || phase->type(address)->isa_narrowoop()) &&
1967 phase->type(address)->is_ptr()->offset() == oopDesc::mark_offset_in_bytes());
1968
1969 // Skip up past a SafePoint control. Cannot do this for Stores because
1970 // pointer stores & cardmarks must stay on the same side of a SafePoint.
1971 if( ctrl != nullptr && ctrl->Opcode() == Op_SafePoint &&
1972 phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw &&
1973 !addr_mark &&
1974 (depends_only_on_test() || has_unknown_control_dependency())) {
1975 ctrl = ctrl->in(0);
1976 set_req(MemNode::Control,ctrl);
1977 return this;
1978 }
1979
1980 intptr_t ignore = 0;
1981 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1982 if (base != nullptr
1983 && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) {
1984 // Check for useless control edge in some common special cases
1985 if (in(MemNode::Control) != nullptr
1986 && can_remove_control()
1987 && phase->type(base)->higher_equal(TypePtr::NOTNULL)
1988 && all_controls_dominate(base, phase->C->start(), phase)) {
1989 // A method-invariant, non-null address (constant or 'this' argument).
1990 set_req(MemNode::Control, nullptr);
1991 return this;
1992 }
1993 }
1994
1995 Node* mem = in(MemNode::Memory);
1996 const TypePtr *addr_t = phase->type(address)->isa_ptr();
1997
1998 if (can_reshape && (addr_t != nullptr)) {
1999 // try to optimize our memory input
2000 Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase);
2001 if (opt_mem != mem) {
2002 set_req_X(MemNode::Memory, opt_mem, phase);
2003 if (phase->type( opt_mem ) == Type::TOP) return nullptr;
2004 return this;
2005 }
2006 const TypeOopPtr *t_oop = addr_t->isa_oopptr();
2007 if ((t_oop != nullptr) &&
2008 (t_oop->is_known_instance_field() ||
2009 t_oop->is_ptr_to_boxed_value())) {
2010 PhaseIterGVN *igvn = phase->is_IterGVN();
2011 assert(igvn != nullptr, "must be PhaseIterGVN when can_reshape is true");
2012 if (igvn->_worklist.member(opt_mem)) {
2013 // Delay this transformation until memory Phi is processed.
2014 igvn->_worklist.push(this);
2015 return nullptr;
2016 }
2017 // Split instance field load through Phi.
2018 Node* result = split_through_phi(phase);
2019 if (result != nullptr) return result;
2020
2021 if (t_oop->is_ptr_to_boxed_value()) {
2022 Node* result = eliminate_autobox(igvn);
2023 if (result != nullptr) return result;
2024 }
2025 }
2026 }
2027
2028 // Is there a dominating load that loads the same value? Leave
2029 // anything that is not a load of a field/array element (like
2030 // barriers etc.) alone
2031 if (in(0) != nullptr && !adr_type()->isa_rawptr() && can_reshape) {
2032 for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
2033 Node *use = mem->fast_out(i);
2034 if (use != this &&
2035 use->Opcode() == Opcode() &&
2036 use->in(0) != nullptr &&
2037 use->in(0) != in(0) &&
2038 use->in(Address) == in(Address)) {
2039 Node* ctl = in(0);
2040 for (int i = 0; i < 10 && ctl != nullptr; i++) {
2041 ctl = IfNode::up_one_dom(ctl);
2042 if (ctl == use->in(0)) {
2043 set_req(0, use->in(0));
2044 return this;
2045 }
2046 }
2047 }
2048 }
2049 }
2050
2051 // Check for prior store with a different base or offset; make Load
2052 // independent. Skip through any number of them. Bail out if the stores
2053 // are in an endless dead cycle and report no progress. This is a key
2054 // transform for Reflection. However, if after skipping through the Stores
2055 // we can't then fold up against a prior store do NOT do the transform as
2056 // this amounts to using the 'Oracle' model of aliasing. It leaves the same
2057 // array memory alive twice: once for the hoisted Load and again after the
2058 // bypassed Store. This situation only works if EVERYBODY who does
2059 // anti-dependence work knows how to bypass. I.e. we need all
2060 // anti-dependence checks to ask the same Oracle. Right now, that Oracle is
2061 // the alias index stuff. So instead, peek through Stores and IFF we can
2062 // fold up, do so.
2063 Node* prev_mem = find_previous_store(phase);
2064 if (prev_mem != nullptr && prev_mem->is_top()) {
2065 // find_previous_store returns top when the access is dead
2066 return prev_mem;
2067 }
2068 if (prev_mem != nullptr) {
2069 Node* value = can_see_arraycopy_value(prev_mem, phase);
2070 if (value != nullptr) {
2071 return value;
2072 }
2073 }
2074 // Steps (a), (b): Walk past independent stores to find an exact match.
2075 if (prev_mem != nullptr && prev_mem != in(MemNode::Memory)) {
2076 // (c) See if we can fold up on the spot, but don't fold up here.
2077 // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or
2078 // just return a prior value, which is done by Identity calls.
2079 if (can_see_stored_value_through_membars(prev_mem, phase)) {
2080 // Make ready for step (d):
2081 set_req_X(MemNode::Memory, prev_mem, phase);
2082 return this;
2083 }
2084 }
2085
2086 if (!can_reshape) {
2087 phase->record_for_igvn(this);
2088 }
2089
2090 return nullptr;
2091 }
2092
2093 // Helper to recognize certain Klass fields which are invariant across
2094 // some group of array types (e.g., int[] or all T[] where T < Object).
2095 const Type*
2096 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
2097 ciKlass* klass) const {
2098 assert(!UseCompactObjectHeaders || tkls->offset() != in_bytes(Klass::prototype_header_offset()),
2099 "must not happen");
2100
2101 if (tkls->isa_instklassptr() && tkls->offset() == in_bytes(InstanceKlass::access_flags_offset())) {
2102 // The field is InstanceKlass::_access_flags. Return its (constant) value.
2103 assert(Opcode() == Op_LoadUS, "must load an unsigned short from _access_flags");
2104 ciInstanceKlass* iklass = tkls->is_instklassptr()->instance_klass();
2105 return TypeInt::make(iklass->access_flags());
2106 }
2107 if (tkls->offset() == in_bytes(Klass::misc_flags_offset())) {
2108 // The field is Klass::_misc_flags. Return its (constant) value.
2109 assert(Opcode() == Op_LoadUB, "must load an unsigned byte from _misc_flags");
2110 return TypeInt::make(klass->misc_flags());
2111 }
2112 if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
2113 // The field is Klass::_layout_helper. Return its constant value if known.
2114 assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
2115 return TypeInt::make(klass->layout_helper());
2116 }
2117
2118 // No match.
2119 return nullptr;
2120 }
2121
2122 //------------------------------Value-----------------------------------------
2123 const Type* LoadNode::Value(PhaseGVN* phase) const {
2124 // Either input is TOP ==> the result is TOP
2125 Node* mem = in(MemNode::Memory);
2126 const Type *t1 = phase->type(mem);
2127 if (t1 == Type::TOP) return Type::TOP;
2128 Node* adr = in(MemNode::Address);
2129 const TypePtr* tp = phase->type(adr)->isa_ptr();
2130 if (tp == nullptr || tp->empty()) return Type::TOP;
2131 int off = tp->offset();
2132 assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
2133 Compile* C = phase->C;
2134
2135 // If load can see a previous constant store, use that.
2136 Node* value = can_see_stored_value_through_membars(mem, phase);
2137 if (value != nullptr && value->is_Con()) {
2138 assert(value->bottom_type()->higher_equal(_type), "sanity");
2139 return value->bottom_type();
2140 }
2141
2142 // Try to guess loaded type from pointer type
2143 if (tp->isa_aryptr()) {
2144 const TypeAryPtr* ary = tp->is_aryptr();
2145 const Type* t = ary->elem();
2146
2147 // Determine whether the reference is beyond the header or not, by comparing
2148 // the offset against the offset of the start of the array's data.
2149 // Different array types begin at slightly different offsets (12 vs. 16).
2150 // We choose T_BYTE as an example base type that is least restrictive
2151 // as to alignment, which will therefore produce the smallest
2152 // possible base offset.
2153 const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
2154 const bool off_beyond_header = (off >= min_base_off);
2155
2156 // Try to constant-fold a stable array element.
2157 if (FoldStableValues && !is_mismatched_access() && ary->is_stable()) {
2158 // Make sure the reference is not into the header and the offset is constant
2159 ciObject* aobj = ary->const_oop();
2160 if (aobj != nullptr && off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
2161 int stable_dimension = (ary->stable_dimension() > 0 ? ary->stable_dimension() - 1 : 0);
2162 const Type* con_type = Type::make_constant_from_array_element(aobj->as_array(), off,
2163 stable_dimension,
2164 value_basic_type(), is_unsigned());
2165 if (con_type != nullptr) {
2166 return con_type;
2167 }
2168 }
2169 }
2170
2171 // Don't do this for integer types. There is only potential profit if
2172 // the element type t is lower than _type; that is, for int types, if _type is
2173 // more restrictive than t. This only happens here if one is short and the other
2174 // char (both 16 bits), and in those cases we've made an intentional decision
2175 // to use one kind of load over the other. See AndINode::Ideal and 4965907.
2176 // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
2177 //
2178 // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
2179 // where the _gvn.type of the AddP is wider than 8. This occurs when an earlier
2180 // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
2181 // subsumed by p1. If p1 is on the worklist but has not yet been re-transformed,
2182 // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
2183 // In fact, that could have been the original type of p1, and p1 could have
2184 // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
2185 // expression (LShiftL quux 3) independently optimized to the constant 8.
2186 if ((t->isa_int() == nullptr) && (t->isa_long() == nullptr)
2187 && (_type->isa_vect() == nullptr)
2188 && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
2189 // t might actually be lower than _type, if _type is a unique
2190 // concrete subclass of abstract class t.
2191 if (off_beyond_header || off == Type::OffsetBot) { // is the offset beyond the header?
2192 const Type* jt = t->join_speculative(_type);
2193 // In any case, do not allow the join, per se, to empty out the type.
2194 if (jt->empty() && !t->empty()) {
2195 // This can happen if a interface-typed array narrows to a class type.
2196 jt = _type;
2197 }
2198 #ifdef ASSERT
2199 if (phase->C->eliminate_boxing() && adr->is_AddP()) {
2200 // The pointers in the autobox arrays are always non-null
2201 Node* base = adr->in(AddPNode::Base);
2202 if ((base != nullptr) && base->is_DecodeN()) {
2203 // Get LoadN node which loads IntegerCache.cache field
2204 base = base->in(1);
2205 }
2206 if ((base != nullptr) && base->is_Con()) {
2207 const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
2208 if ((base_type != nullptr) && base_type->is_autobox_cache()) {
2209 // It could be narrow oop
2210 assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
2211 }
2212 }
2213 }
2214 #endif
2215 return jt;
2216 }
2217 }
2218 } else if (tp->base() == Type::InstPtr) {
2219 assert( off != Type::OffsetBot ||
2220 // arrays can be cast to Objects
2221 !tp->isa_instptr() ||
2222 tp->is_instptr()->instance_klass()->is_java_lang_Object() ||
2223 // unsafe field access may not have a constant offset
2224 C->has_unsafe_access(),
2225 "Field accesses must be precise" );
2226 // For oop loads, we expect the _type to be precise.
2227
2228 // Optimize loads from constant fields.
2229 const TypeInstPtr* tinst = tp->is_instptr();
2230 ciObject* const_oop = tinst->const_oop();
2231 if (!is_mismatched_access() && off != Type::OffsetBot && const_oop != nullptr && const_oop->is_instance()) {
2232 const Type* con_type = Type::make_constant_from_field(const_oop->as_instance(), off, is_unsigned(), value_basic_type());
2233 if (con_type != nullptr) {
2234 return con_type;
2235 }
2236 }
2237 } else if (tp->base() == Type::KlassPtr || tp->base() == Type::InstKlassPtr || tp->base() == Type::AryKlassPtr) {
2238 assert(off != Type::OffsetBot ||
2239 !tp->isa_instklassptr() ||
2240 // arrays can be cast to Objects
2241 tp->isa_instklassptr()->instance_klass()->is_java_lang_Object() ||
2242 // also allow array-loading from the primary supertype
2243 // array during subtype checks
2244 Opcode() == Op_LoadKlass,
2245 "Field accesses must be precise");
2246 // For klass/static loads, we expect the _type to be precise
2247 } else if (tp->base() == Type::RawPtr && adr->is_Load() && off == 0) {
2248 /* With mirrors being an indirect in the Klass*
2249 * the VM is now using two loads. LoadKlass(LoadP(LoadP(Klass, mirror_offset), zero_offset))
2250 * The LoadP from the Klass has a RawPtr type (see LibraryCallKit::load_mirror_from_klass).
2251 *
2252 * So check the type and klass of the node before the LoadP.
2253 */
2254 Node* adr2 = adr->in(MemNode::Address);
2255 const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2256 if (tkls != nullptr && !StressReflectiveCode) {
2257 if (tkls->is_loaded() && tkls->klass_is_exact() && tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
2258 ciKlass* klass = tkls->exact_klass();
2259 assert(adr->Opcode() == Op_LoadP, "must load an oop from _java_mirror");
2260 assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
2261 return TypeInstPtr::make(klass->java_mirror());
2262 }
2263 }
2264 }
2265
2266 const TypeKlassPtr *tkls = tp->isa_klassptr();
2267 if (tkls != nullptr) {
2268 if (tkls->is_loaded() && tkls->klass_is_exact()) {
2269 ciKlass* klass = tkls->exact_klass();
2270 // We are loading a field from a Klass metaobject whose identity
2271 // is known at compile time (the type is "exact" or "precise").
2272 // Check for fields we know are maintained as constants by the VM.
2273 if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
2274 // The field is Klass::_super_check_offset. Return its (constant) value.
2275 // (Folds up type checking code.)
2276 assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
2277 return TypeInt::make(klass->super_check_offset());
2278 }
2279 if (UseCompactObjectHeaders) {
2280 if (tkls->offset() == in_bytes(Klass::prototype_header_offset())) {
2281 // The field is Klass::_prototype_header. Return its (constant) value.
2282 assert(this->Opcode() == Op_LoadX, "must load a proper type from _prototype_header");
2283 return TypeX::make(klass->prototype_header());
2284 }
2285 }
2286 // Compute index into primary_supers array
2287 juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
2288 // Check for overflowing; use unsigned compare to handle the negative case.
2289 if( depth < ciKlass::primary_super_limit() ) {
2290 // The field is an element of Klass::_primary_supers. Return its (constant) value.
2291 // (Folds up type checking code.)
2292 assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
2293 ciKlass *ss = klass->super_of_depth(depth);
2294 return ss ? TypeKlassPtr::make(ss, Type::trust_interfaces) : TypePtr::NULL_PTR;
2295 }
2296 const Type* aift = load_array_final_field(tkls, klass);
2297 if (aift != nullptr) return aift;
2298 }
2299
2300 // We can still check if we are loading from the primary_supers array at a
2301 // shallow enough depth. Even though the klass is not exact, entries less
2302 // than or equal to its super depth are correct.
2303 if (tkls->is_loaded()) {
2304 ciKlass* klass = nullptr;
2305 if (tkls->isa_instklassptr()) {
2306 klass = tkls->is_instklassptr()->instance_klass();
2307 } else {
2308 int dims;
2309 const Type* inner = tkls->is_aryklassptr()->base_element_type(dims);
2310 if (inner->isa_instklassptr()) {
2311 klass = inner->is_instklassptr()->instance_klass();
2312 klass = ciObjArrayKlass::make(klass, dims);
2313 }
2314 }
2315 if (klass != nullptr) {
2316 // Compute index into primary_supers array
2317 juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
2318 // Check for overflowing; use unsigned compare to handle the negative case.
2319 if (depth < ciKlass::primary_super_limit() &&
2320 depth <= klass->super_depth()) { // allow self-depth checks to handle self-check case
2321 // The field is an element of Klass::_primary_supers. Return its (constant) value.
2322 // (Folds up type checking code.)
2323 assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
2324 ciKlass *ss = klass->super_of_depth(depth);
2325 return ss ? TypeKlassPtr::make(ss, Type::trust_interfaces) : TypePtr::NULL_PTR;
2326 }
2327 }
2328 }
2329
2330 // If the type is enough to determine that the thing is not an array,
2331 // we can give the layout_helper a positive interval type.
2332 // This will help short-circuit some reflective code.
2333 if (tkls->offset() == in_bytes(Klass::layout_helper_offset()) &&
2334 tkls->isa_instklassptr() && // not directly typed as an array
2335 !tkls->is_instklassptr()->might_be_an_array() // not the supertype of all T[] (java.lang.Object) or has an interface that is not Serializable or Cloneable
2336 ) {
2337 assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
2338 jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
2339 // The key property of this type is that it folds up tests
2340 // for array-ness, since it proves that the layout_helper is positive.
2341 // Thus, a generic value like the basic object layout helper works fine.
2342 return TypeInt::make(min_size, max_jint, Type::WidenMin);
2343 }
2344 }
2345
2346 // If we are loading from a freshly-allocated object/array, produce a zero.
2347 // Things to check:
2348 // 1. Load is beyond the header: headers are not guaranteed to be zero
2349 // 2. Load is not vectorized: vectors have no zero constant
2350 // 3. Load has no matching store, i.e. the input is the initial memory state
2351 const TypeOopPtr* tinst = tp->isa_oopptr();
2352 bool is_not_header = (tinst != nullptr) && tinst->is_known_instance_field();
2353 bool is_not_vect = (_type->isa_vect() == nullptr);
2354 if (is_not_header && is_not_vect) {
2355 Node* mem = in(MemNode::Memory);
2356 if (mem->is_Parm() && mem->in(0)->is_Start()) {
2357 assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
2358 return Type::get_zero_type(_type->basic_type());
2359 }
2360 }
2361
2362 if (!UseCompactObjectHeaders) {
2363 Node* alloc = is_new_object_mark_load();
2364 if (alloc != nullptr) {
2365 return TypeX::make(markWord::prototype().value());
2366 }
2367 }
2368
2369 return _type;
2370 }
2371
2372 //------------------------------match_edge-------------------------------------
2373 // Do we Match on this edge index or not? Match only the address.
2374 uint LoadNode::match_edge(uint idx) const {
2375 return idx == MemNode::Address;
2376 }
2377
2378 //--------------------------LoadBNode::Ideal--------------------------------------
2379 //
2380 // If the previous store is to the same address as this load,
2381 // and the value stored was larger than a byte, replace this load
2382 // with the value stored truncated to a byte. If no truncation is
2383 // needed, the replacement is done in LoadNode::Identity().
2384 //
2385 Node* LoadBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2386 Node* mem = in(MemNode::Memory);
2387 Node* value = can_see_stored_value_through_membars(mem, phase);
2388 if (value != nullptr) {
2389 Node* narrow = Compile::narrow_value(T_BYTE, value, _type, phase, false);
2390 if (narrow != value) {
2391 return narrow;
2392 }
2393 }
2394 // Identity call will handle the case where truncation is not needed.
2395 return LoadNode::Ideal(phase, can_reshape);
2396 }
2397
2398 const Type* LoadBNode::Value(PhaseGVN* phase) const {
2399 Node* mem = in(MemNode::Memory);
2400 Node* value = can_see_stored_value_through_membars(mem, phase);
2401 if (value != nullptr && value->is_Con() &&
2402 !value->bottom_type()->higher_equal(_type)) {
2403 // If the input to the store does not fit with the load's result type,
2404 // it must be truncated. We can't delay until Ideal call since
2405 // a singleton Value is needed for split_thru_phi optimization.
2406 int con = value->get_int();
2407 return TypeInt::make((con << 24) >> 24);
2408 }
2409 return LoadNode::Value(phase);
2410 }
2411
2412 //--------------------------LoadUBNode::Ideal-------------------------------------
2413 //
2414 // If the previous store is to the same address as this load,
2415 // and the value stored was larger than a byte, replace this load
2416 // with the value stored truncated to a byte. If no truncation is
2417 // needed, the replacement is done in LoadNode::Identity().
2418 //
2419 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2420 Node* mem = in(MemNode::Memory);
2421 Node* value = can_see_stored_value_through_membars(mem, phase);
2422 if (value != nullptr) {
2423 Node* narrow = Compile::narrow_value(T_BOOLEAN, value, _type, phase, false);
2424 if (narrow != value) {
2425 return narrow;
2426 }
2427 }
2428 // Identity call will handle the case where truncation is not needed.
2429 return LoadNode::Ideal(phase, can_reshape);
2430 }
2431
2432 const Type* LoadUBNode::Value(PhaseGVN* phase) const {
2433 Node* mem = in(MemNode::Memory);
2434 Node* value = can_see_stored_value_through_membars(mem, phase);
2435 if (value != nullptr && value->is_Con() &&
2436 !value->bottom_type()->higher_equal(_type)) {
2437 // If the input to the store does not fit with the load's result type,
2438 // it must be truncated. We can't delay until Ideal call since
2439 // a singleton Value is needed for split_thru_phi optimization.
2440 int con = value->get_int();
2441 return TypeInt::make(con & 0xFF);
2442 }
2443 return LoadNode::Value(phase);
2444 }
2445
2446 //--------------------------LoadUSNode::Ideal-------------------------------------
2447 //
2448 // If the previous store is to the same address as this load,
2449 // and the value stored was larger than a char, replace this load
2450 // with the value stored truncated to a char. If no truncation is
2451 // needed, the replacement is done in LoadNode::Identity().
2452 //
2453 Node* LoadUSNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2454 Node* mem = in(MemNode::Memory);
2455 Node* value = can_see_stored_value_through_membars(mem, phase);
2456 if (value != nullptr) {
2457 Node* narrow = Compile::narrow_value(T_CHAR, value, _type, phase, false);
2458 if (narrow != value) {
2459 return narrow;
2460 }
2461 }
2462 // Identity call will handle the case where truncation is not needed.
2463 return LoadNode::Ideal(phase, can_reshape);
2464 }
2465
2466 const Type* LoadUSNode::Value(PhaseGVN* phase) const {
2467 Node* mem = in(MemNode::Memory);
2468 Node* value = can_see_stored_value_through_membars(mem, phase);
2469 if (value != nullptr && value->is_Con() &&
2470 !value->bottom_type()->higher_equal(_type)) {
2471 // If the input to the store does not fit with the load's result type,
2472 // it must be truncated. We can't delay until Ideal call since
2473 // a singleton Value is needed for split_thru_phi optimization.
2474 int con = value->get_int();
2475 return TypeInt::make(con & 0xFFFF);
2476 }
2477 return LoadNode::Value(phase);
2478 }
2479
2480 //--------------------------LoadSNode::Ideal--------------------------------------
2481 //
2482 // If the previous store is to the same address as this load,
2483 // and the value stored was larger than a short, replace this load
2484 // with the value stored truncated to a short. If no truncation is
2485 // needed, the replacement is done in LoadNode::Identity().
2486 //
2487 Node* LoadSNode::Ideal(PhaseGVN* phase, bool can_reshape) {
2488 Node* mem = in(MemNode::Memory);
2489 Node* value = can_see_stored_value_through_membars(mem, phase);
2490 if (value != nullptr) {
2491 Node* narrow = Compile::narrow_value(T_SHORT, value, _type, phase, false);
2492 if (narrow != value) {
2493 return narrow;
2494 }
2495 }
2496 // Identity call will handle the case where truncation is not needed.
2497 return LoadNode::Ideal(phase, can_reshape);
2498 }
2499
2500 const Type* LoadSNode::Value(PhaseGVN* phase) const {
2501 Node* mem = in(MemNode::Memory);
2502 Node* value = can_see_stored_value_through_membars(mem, phase);
2503 if (value != nullptr && value->is_Con() &&
2504 !value->bottom_type()->higher_equal(_type)) {
2505 // If the input to the store does not fit with the load's result type,
2506 // it must be truncated. We can't delay until Ideal call since
2507 // a singleton Value is needed for split_thru_phi optimization.
2508 int con = value->get_int();
2509 return TypeInt::make((con << 16) >> 16);
2510 }
2511 return LoadNode::Value(phase);
2512 }
2513
2514 //=============================================================================
2515 //----------------------------LoadKlassNode::make------------------------------
2516 // Polymorphic factory method:
2517 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) {
2518 // sanity check the alias category against the created node type
2519 const TypePtr* adr_type = adr->bottom_type()->isa_ptr();
2520 assert(adr_type != nullptr, "expecting TypeKlassPtr");
2521 #ifdef _LP64
2522 if (adr_type->is_ptr_to_narrowklass()) {
2523 Node* load_klass = gvn.transform(new LoadNKlassNode(mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
2524 return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
2525 }
2526 #endif
2527 assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
2528 return new LoadKlassNode(mem, adr, at, tk, MemNode::unordered);
2529 }
2530
2531 //------------------------------Value------------------------------------------
2532 const Type* LoadKlassNode::Value(PhaseGVN* phase) const {
2533 return klass_value_common(phase);
2534 }
2535
2536 const Type* LoadNode::klass_value_common(PhaseGVN* phase) const {
2537 // Either input is TOP ==> the result is TOP
2538 const Type *t1 = phase->type( in(MemNode::Memory) );
2539 if (t1 == Type::TOP) return Type::TOP;
2540 Node *adr = in(MemNode::Address);
2541 const Type *t2 = phase->type( adr );
2542 if (t2 == Type::TOP) return Type::TOP;
2543 const TypePtr *tp = t2->is_ptr();
2544 if (TypePtr::above_centerline(tp->ptr()) ||
2545 tp->ptr() == TypePtr::Null) return Type::TOP;
2546
2547 // Return a more precise klass, if possible
2548 const TypeInstPtr *tinst = tp->isa_instptr();
2549 if (tinst != nullptr) {
2550 ciInstanceKlass* ik = tinst->instance_klass();
2551 int offset = tinst->offset();
2552 if (ik == phase->C->env()->Class_klass()
2553 && (offset == java_lang_Class::klass_offset() ||
2554 offset == java_lang_Class::array_klass_offset())) {
2555 // We are loading a special hidden field from a Class mirror object,
2556 // the field which points to the VM's Klass metaobject.
2557 ciType* t = tinst->java_mirror_type();
2558 // java_mirror_type returns non-null for compile-time Class constants.
2559 if (t != nullptr) {
2560 // constant oop => constant klass
2561 if (offset == java_lang_Class::array_klass_offset()) {
2562 if (t->is_void()) {
2563 // We cannot create a void array. Since void is a primitive type return null
2564 // klass. Users of this result need to do a null check on the returned klass.
2565 return TypePtr::NULL_PTR;
2566 }
2567 return TypeKlassPtr::make(ciArrayKlass::make(t), Type::trust_interfaces);
2568 }
2569 if (!t->is_klass()) {
2570 // a primitive Class (e.g., int.class) has null for a klass field
2571 return TypePtr::NULL_PTR;
2572 }
2573 // Fold up the load of the hidden field
2574 return TypeKlassPtr::make(t->as_klass(), Type::trust_interfaces);
2575 }
2576 // non-constant mirror, so we can't tell what's going on
2577 }
2578 if (!tinst->is_loaded())
2579 return _type; // Bail out if not loaded
2580 if (offset == oopDesc::klass_offset_in_bytes()) {
2581 return tinst->as_klass_type(true);
2582 }
2583 }
2584
2585 // Check for loading klass from an array
2586 const TypeAryPtr *tary = tp->isa_aryptr();
2587 if (tary != nullptr &&
2588 tary->offset() == oopDesc::klass_offset_in_bytes()) {
2589 return tary->as_klass_type(true);
2590 }
2591
2592 // Check for loading klass from an array klass
2593 const TypeKlassPtr *tkls = tp->isa_klassptr();
2594 if (tkls != nullptr && !StressReflectiveCode) {
2595 if (!tkls->is_loaded())
2596 return _type; // Bail out if not loaded
2597 if (tkls->isa_aryklassptr() && tkls->is_aryklassptr()->elem()->isa_klassptr() &&
2598 tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
2599 // // Always returning precise element type is incorrect,
2600 // // e.g., element type could be object and array may contain strings
2601 // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
2602
2603 // The array's TypeKlassPtr was declared 'precise' or 'not precise'
2604 // according to the element type's subclassing.
2605 return tkls->is_aryklassptr()->elem()->isa_klassptr()->cast_to_exactness(tkls->klass_is_exact());
2606 }
2607 if (tkls->isa_instklassptr() != nullptr && tkls->klass_is_exact() &&
2608 tkls->offset() == in_bytes(Klass::super_offset())) {
2609 ciKlass* sup = tkls->is_instklassptr()->instance_klass()->super();
2610 // The field is Klass::_super. Return its (constant) value.
2611 // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
2612 return sup ? TypeKlassPtr::make(sup, Type::trust_interfaces) : TypePtr::NULL_PTR;
2613 }
2614 }
2615
2616 if (tkls != nullptr && !UseSecondarySupersCache
2617 && tkls->offset() == in_bytes(Klass::secondary_super_cache_offset())) {
2618 // Treat Klass::_secondary_super_cache as a constant when the cache is disabled.
2619 return TypePtr::NULL_PTR;
2620 }
2621
2622 // Bailout case
2623 return LoadNode::Value(phase);
2624 }
2625
2626 //------------------------------Identity---------------------------------------
2627 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
2628 // Also feed through the klass in Allocate(...klass...)._klass.
2629 Node* LoadKlassNode::Identity(PhaseGVN* phase) {
2630 return klass_identity_common(phase);
2631 }
2632
2633 Node* LoadNode::klass_identity_common(PhaseGVN* phase) {
2634 Node* x = LoadNode::Identity(phase);
2635 if (x != this) return x;
2636
2637 // Take apart the address into an oop and offset.
2638 // Return 'this' if we cannot.
2639 Node* adr = in(MemNode::Address);
2640 intptr_t offset = 0;
2641 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2642 if (base == nullptr) return this;
2643 const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
2644 if (toop == nullptr) return this;
2645
2646 // Step over potential GC barrier for OopHandle resolve
2647 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2648 if (bs->is_gc_barrier_node(base)) {
2649 base = bs->step_over_gc_barrier(base);
2650 }
2651
2652 // We can fetch the klass directly through an AllocateNode.
2653 // This works even if the klass is not constant (clone or newArray).
2654 if (offset == oopDesc::klass_offset_in_bytes()) {
2655 Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
2656 if (allocated_klass != nullptr) {
2657 return allocated_klass;
2658 }
2659 }
2660
2661 // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
2662 // See inline_native_Class_query for occurrences of these patterns.
2663 // Java Example: x.getClass().isAssignableFrom(y)
2664 //
2665 // This improves reflective code, often making the Class
2666 // mirror go completely dead. (Current exception: Class
2667 // mirrors may appear in debug info, but we could clean them out by
2668 // introducing a new debug info operator for Klass.java_mirror).
2669
2670 if (toop->isa_instptr() && toop->is_instptr()->instance_klass() == phase->C->env()->Class_klass()
2671 && offset == java_lang_Class::klass_offset()) {
2672 if (base->is_Load()) {
2673 Node* base2 = base->in(MemNode::Address);
2674 if (base2->is_Load()) { /* direct load of a load which is the OopHandle */
2675 Node* adr2 = base2->in(MemNode::Address);
2676 const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2677 if (tkls != nullptr && !tkls->empty()
2678 && (tkls->isa_instklassptr() || tkls->isa_aryklassptr())
2679 && adr2->is_AddP()
2680 ) {
2681 int mirror_field = in_bytes(Klass::java_mirror_offset());
2682 if (tkls->offset() == mirror_field) {
2683 #ifdef ASSERT
2684 const TypeKlassPtr* tkls2 = phase->type(adr2->in(AddPNode::Address))->is_klassptr();
2685 assert(tkls2->offset() == 0, "not a load of java_mirror");
2686 #endif
2687 assert(adr2->in(AddPNode::Base)->is_top(), "not an off heap load");
2688 assert(adr2->in(AddPNode::Offset)->find_intptr_t_con(-1) == in_bytes(Klass::java_mirror_offset()), "incorrect offset");
2689 return adr2->in(AddPNode::Address);
2690 }
2691 }
2692 }
2693 }
2694 }
2695
2696 return this;
2697 }
2698
2699 LoadNode* LoadNode::clone_pinned() const {
2700 LoadNode* ld = clone()->as_Load();
2701 ld->_control_dependency = UnknownControl;
2702 return ld;
2703 }
2704
2705 // Pin a LoadNode if it carries a dependency on its control input. There are cases when the node
2706 // does not actually have any dependency on its control input. For example, if we have a LoadNode
2707 // being used only outside a loop but it must be scheduled inside the loop, we can clone the node
2708 // for each of its use so that all the clones can be scheduled outside the loop. Then, to prevent
2709 // the clones from being GVN-ed again, we add a control input for each of them at the loop exit. In
2710 // those case, since there is not a dependency between the node and its control input, we do not
2711 // need to pin it.
2712 LoadNode* LoadNode::pin_node_under_control_impl() const {
2713 const TypePtr* adr_type = this->adr_type();
2714 if (adr_type != nullptr && adr_type->isa_aryptr()) {
2715 // Only array accesses have dependencies on their control input
2716 return clone_pinned();
2717 }
2718 return nullptr;
2719 }
2720
2721 //------------------------------Value------------------------------------------
2722 const Type* LoadNKlassNode::Value(PhaseGVN* phase) const {
2723 const Type *t = klass_value_common(phase);
2724 if (t == Type::TOP)
2725 return t;
2726
2727 return t->make_narrowklass();
2728 }
2729
2730 //------------------------------Identity---------------------------------------
2731 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
2732 // Also feed through the klass in Allocate(...klass...)._klass.
2733 Node* LoadNKlassNode::Identity(PhaseGVN* phase) {
2734 Node *x = klass_identity_common(phase);
2735
2736 const Type *t = phase->type( x );
2737 if( t == Type::TOP ) return x;
2738 if( t->isa_narrowklass()) return x;
2739 assert (!t->isa_narrowoop(), "no narrow oop here");
2740
2741 return phase->transform(new EncodePKlassNode(x, t->make_narrowklass()));
2742 }
2743
2744 //------------------------------Value-----------------------------------------
2745 const Type* LoadRangeNode::Value(PhaseGVN* phase) const {
2746 // Either input is TOP ==> the result is TOP
2747 const Type *t1 = phase->type( in(MemNode::Memory) );
2748 if( t1 == Type::TOP ) return Type::TOP;
2749 Node *adr = in(MemNode::Address);
2750 const Type *t2 = phase->type( adr );
2751 if( t2 == Type::TOP ) return Type::TOP;
2752 const TypePtr *tp = t2->is_ptr();
2753 if (TypePtr::above_centerline(tp->ptr())) return Type::TOP;
2754 const TypeAryPtr *tap = tp->isa_aryptr();
2755 if( !tap ) return _type;
2756 return tap->size();
2757 }
2758
2759 //-------------------------------Ideal---------------------------------------
2760 // Feed through the length in AllocateArray(...length...)._length.
2761 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2762 Node* p = MemNode::Ideal_common(phase, can_reshape);
2763 if (p) return (p == NodeSentinel) ? nullptr : p;
2764
2765 // Take apart the address into an oop and offset.
2766 // Return 'this' if we cannot.
2767 Node* adr = in(MemNode::Address);
2768 intptr_t offset = 0;
2769 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2770 if (base == nullptr) return nullptr;
2771 const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2772 if (tary == nullptr) return nullptr;
2773
2774 // We can fetch the length directly through an AllocateArrayNode.
2775 // This works even if the length is not constant (clone or newArray).
2776 if (offset == arrayOopDesc::length_offset_in_bytes()) {
2777 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base);
2778 if (alloc != nullptr) {
2779 Node* allocated_length = alloc->Ideal_length();
2780 Node* len = alloc->make_ideal_length(tary, phase);
2781 if (allocated_length != len) {
2782 // New CastII improves on this.
2783 return len;
2784 }
2785 }
2786 }
2787
2788 return nullptr;
2789 }
2790
2791 //------------------------------Identity---------------------------------------
2792 // Feed through the length in AllocateArray(...length...)._length.
2793 Node* LoadRangeNode::Identity(PhaseGVN* phase) {
2794 Node* x = LoadINode::Identity(phase);
2795 if (x != this) return x;
2796
2797 // Take apart the address into an oop and offset.
2798 // Return 'this' if we cannot.
2799 Node* adr = in(MemNode::Address);
2800 intptr_t offset = 0;
2801 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2802 if (base == nullptr) return this;
2803 const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2804 if (tary == nullptr) return this;
2805
2806 // We can fetch the length directly through an AllocateArrayNode.
2807 // This works even if the length is not constant (clone or newArray).
2808 if (offset == arrayOopDesc::length_offset_in_bytes()) {
2809 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base);
2810 if (alloc != nullptr) {
2811 Node* allocated_length = alloc->Ideal_length();
2812 // Do not allow make_ideal_length to allocate a CastII node.
2813 Node* len = alloc->make_ideal_length(tary, phase, false);
2814 if (allocated_length == len) {
2815 // Return allocated_length only if it would not be improved by a CastII.
2816 return allocated_length;
2817 }
2818 }
2819 }
2820
2821 return this;
2822
2823 }
2824
2825 //=============================================================================
2826 //---------------------------StoreNode::make-----------------------------------
2827 // Polymorphic factory method:
2828 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo, bool require_atomic_access) {
2829 assert((mo == unordered || mo == release), "unexpected");
2830 Compile* C = gvn.C;
2831 assert(adr_type == nullptr || adr->is_top() || C->get_alias_index(gvn.type(adr)->is_ptr()) == C->get_alias_index(adr_type), "adr and adr_type must agree");
2832 assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
2833 ctl != nullptr, "raw memory operations should have control edge");
2834
2835 switch (bt) {
2836 case T_BOOLEAN: val = gvn.transform(new AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case
2837 case T_BYTE: return new StoreBNode(ctl, mem, adr, adr_type, val, mo);
2838 case T_INT: return new StoreINode(ctl, mem, adr, adr_type, val, mo);
2839 case T_CHAR:
2840 case T_SHORT: return new StoreCNode(ctl, mem, adr, adr_type, val, mo);
2841 case T_LONG: return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access);
2842 case T_FLOAT: return new StoreFNode(ctl, mem, adr, adr_type, val, mo);
2843 case T_DOUBLE: return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access);
2844 case T_METADATA:
2845 case T_ADDRESS:
2846 case T_OBJECT:
2847 #ifdef _LP64
2848 if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2849 val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop()));
2850 return new StoreNNode(ctl, mem, adr, adr_type, val, mo);
2851 } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
2852 (val->bottom_type()->isa_klassptr() && adr->bottom_type()->isa_rawptr())) {
2853 val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
2854 return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
2855 }
2856 #endif
2857 {
2858 return new StorePNode(ctl, mem, adr, adr_type, val, mo);
2859 }
2860 default:
2861 ShouldNotReachHere();
2862 return (StoreNode*)nullptr;
2863 }
2864 }
2865
2866 //--------------------------bottom_type----------------------------------------
2867 const Type *StoreNode::bottom_type() const {
2868 return Type::MEMORY;
2869 }
2870
2871 //------------------------------hash-------------------------------------------
2872 uint StoreNode::hash() const {
2873 // unroll addition of interesting fields
2874 //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
2875
2876 // Since they are not commoned, do not hash them:
2877 return NO_HASH;
2878 }
2879
2880 // Link together multiple stores (B/S/C/I) into a longer one.
2881 //
2882 // Example: _store = StoreB[i+3]
2883 //
2884 // RangeCheck[i+0] RangeCheck[i+0]
2885 // StoreB[i+0]
2886 // RangeCheck[i+3] RangeCheck[i+3]
2887 // StoreB[i+1] --> pass: fail:
2888 // StoreB[i+2] StoreI[i+0] StoreB[i+0]
2889 // StoreB[i+3]
2890 //
2891 // The 4 StoreB are merged into a single StoreI node. We have to be careful with RangeCheck[i+1]: before
2892 // the optimization, if this RangeCheck[i+1] fails, then we execute only StoreB[i+0], and then trap. After
2893 // the optimization, the new StoreI[i+0] is on the passing path of RangeCheck[i+3], and StoreB[i+0] on the
2894 // failing path.
2895 //
2896 // Note: For normal array stores, every store at first has a RangeCheck. But they can be removed with:
2897 // - RCE (RangeCheck Elimination): the RangeChecks in the loop are hoisted out and before the loop,
2898 // and possibly no RangeChecks remain between the stores.
2899 // - RangeCheck smearing: the earlier RangeChecks are adjusted such that they cover later RangeChecks,
2900 // and those later RangeChecks can be removed. Example:
2901 //
2902 // RangeCheck[i+0] RangeCheck[i+0] <- before first store
2903 // StoreB[i+0] StoreB[i+0] <- first store
2904 // RangeCheck[i+1] --> smeared --> RangeCheck[i+3] <- only RC between first and last store
2905 // StoreB[i+1] StoreB[i+1] <- second store
2906 // RangeCheck[i+2] --> removed
2907 // StoreB[i+2] StoreB[i+2]
2908 // RangeCheck[i+3] --> removed
2909 // StoreB[i+3] StoreB[i+3] <- last store
2910 //
2911 // Thus, it is a common pattern that between the first and last store in a chain
2912 // of adjacent stores there remains exactly one RangeCheck, located between the
2913 // first and the second store (e.g. RangeCheck[i+3]).
2914 //
2915 class MergePrimitiveStores : public StackObj {
2916 private:
2917 PhaseGVN* const _phase;
2918 StoreNode* const _store;
2919 // State machine with initial state Unknown
2920 // Allowed transitions:
2921 // Unknown -> Const
2922 // Unknown -> Platform
2923 // Unknown -> Reverse
2924 // Unknown -> NotAdjacent
2925 // Const -> Const
2926 // Const -> NotAdjacent
2927 // Platform -> Platform
2928 // Platform -> NotAdjacent
2929 // Reverse -> Reverse
2930 // Reverse -> NotAdjacent
2931 // NotAdjacent -> NotAdjacent
2932 enum ValueOrder : uint8_t {
2933 Unknown, // Initial state
2934 Const, // Input values are const
2935 Platform, // Platform order
2936 Reverse, // Reverse platform order
2937 NotAdjacent // Not adjacent
2938 };
2939 ValueOrder _value_order;
2940
2941 NOT_PRODUCT( const CHeapBitMap &_trace_tags; )
2942
2943 public:
2944 MergePrimitiveStores(PhaseGVN* phase, StoreNode* store) :
2945 _phase(phase), _store(store), _value_order(ValueOrder::Unknown)
2946 NOT_PRODUCT( COMMA _trace_tags(Compile::current()->directive()->trace_merge_stores_tags()) )
2947 {}
2948
2949 StoreNode* run();
2950
2951 private:
2952 bool is_compatible_store(const StoreNode* other_store) const;
2953 bool is_adjacent_pair(const StoreNode* use_store, const StoreNode* def_store) const;
2954 bool is_adjacent_input_pair(const Node* n1, const Node* n2, const int memory_size) const;
2955 static bool is_con_RShift(const Node* n, Node const*& base_out, jint& shift_out, PhaseGVN* phase);
2956 enum CFGStatus { SuccessNoRangeCheck, SuccessWithRangeCheck, Failure };
2957 static CFGStatus cfg_status_for_pair(const StoreNode* use_store, const StoreNode* def_store);
2958
2959 class Status {
2960 private:
2961 StoreNode* _found_store;
2962 bool _found_range_check;
2963
2964 Status(StoreNode* found_store, bool found_range_check)
2965 : _found_store(found_store), _found_range_check(found_range_check) {}
2966
2967 public:
2968 StoreNode* found_store() const { return _found_store; }
2969 bool found_range_check() const { return _found_range_check; }
2970 static Status make_failure() { return Status(nullptr, false); }
2971
2972 static Status make(StoreNode* found_store, const CFGStatus cfg_status) {
2973 if (cfg_status == CFGStatus::Failure) {
2974 return Status::make_failure();
2975 }
2976 return Status(found_store, cfg_status == CFGStatus::SuccessWithRangeCheck);
2977 }
2978
2979 #ifndef PRODUCT
2980 void print_on(outputStream* st) const {
2981 if (_found_store == nullptr) {
2982 st->print_cr("None");
2983 } else {
2984 st->print_cr("Found[%d %s, %s]", _found_store->_idx, _found_store->Name(),
2985 _found_range_check ? "RC" : "no-RC");
2986 }
2987 }
2988 #endif
2989 };
2990
2991 enum ValueOrder find_adjacent_input_value_order(const Node* n1, const Node* n2, const int memory_size) const;
2992 Status find_adjacent_use_store(const StoreNode* def_store) const;
2993 Status find_adjacent_def_store(const StoreNode* use_store) const;
2994 Status find_use_store(const StoreNode* def_store) const;
2995 Status find_def_store(const StoreNode* use_store) const;
2996 Status find_use_store_unidirectional(const StoreNode* def_store) const;
2997 Status find_def_store_unidirectional(const StoreNode* use_store) const;
2998
2999 void collect_merge_list(Node_List& merge_list) const;
3000 Node* make_merged_input_value(const Node_List& merge_list);
3001 StoreNode* make_merged_store(const Node_List& merge_list, Node* merged_input_value);
3002
3003 #ifndef PRODUCT
3004 // Access to TraceMergeStores tags
3005 bool is_trace(TraceMergeStores::Tag tag) const {
3006 return _trace_tags.at(tag);
3007 }
3008
3009 bool is_trace_basic() const {
3010 return is_trace(TraceMergeStores::Tag::BASIC);
3011 }
3012
3013 bool is_trace_pointer_parsing() const {
3014 return is_trace(TraceMergeStores::Tag::POINTER_PARSING);
3015 }
3016
3017 bool is_trace_pointer_aliasing() const {
3018 return is_trace(TraceMergeStores::Tag::POINTER_ALIASING);
3019 }
3020
3021 bool is_trace_pointer_adjacency() const {
3022 return is_trace(TraceMergeStores::Tag::POINTER_ADJACENCY);
3023 }
3024
3025 bool is_trace_success() const {
3026 return is_trace(TraceMergeStores::Tag::SUCCESS);
3027 }
3028 #endif
3029
3030 NOT_PRODUCT( void trace(const Node_List& merge_list, const Node* merged_input_value, const StoreNode* merged_store) const; )
3031 };
3032
3033 StoreNode* MergePrimitiveStores::run() {
3034 // Check for B/S/C/I
3035 int opc = _store->Opcode();
3036 if (opc != Op_StoreB && opc != Op_StoreC && opc != Op_StoreI) {
3037 return nullptr;
3038 }
3039
3040 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] MergePrimitiveStores::run: "); _store->dump(); })
3041
3042 // The _store must be the "last" store in a chain. If we find a use we could merge with
3043 // then that use or a store further down is the "last" store.
3044 Status status_use = find_adjacent_use_store(_store);
3045 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] expect no use: "); status_use.print_on(tty); })
3046 if (status_use.found_store() != nullptr) {
3047 return nullptr;
3048 }
3049
3050 // Check if we can merge with at least one def, so that we have at least 2 stores to merge.
3051 Status status_def = find_adjacent_def_store(_store);
3052 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] expect def: "); status_def.print_on(tty); })
3053 Node* def_store = status_def.found_store();
3054 if (def_store == nullptr) {
3055 return nullptr;
3056 }
3057
3058 // Initialize value order
3059 _value_order = find_adjacent_input_value_order(def_store->in(MemNode::ValueIn),
3060 _store->in(MemNode::ValueIn),
3061 _store->memory_size());
3062 assert(_value_order != ValueOrder::NotAdjacent && _value_order != ValueOrder::Unknown, "Order should be checked");
3063
3064 ResourceMark rm;
3065 Node_List merge_list;
3066 collect_merge_list(merge_list);
3067
3068 Node* merged_input_value = make_merged_input_value(merge_list);
3069 if (merged_input_value == nullptr) { return nullptr; }
3070
3071 StoreNode* merged_store = make_merged_store(merge_list, merged_input_value);
3072
3073 NOT_PRODUCT( if (is_trace_success()) { trace(merge_list, merged_input_value, merged_store); } )
3074
3075 return merged_store;
3076 }
3077
3078 // Check compatibility between _store and other_store.
3079 bool MergePrimitiveStores::is_compatible_store(const StoreNode* other_store) const {
3080 int opc = _store->Opcode();
3081 assert(opc == Op_StoreB || opc == Op_StoreC || opc == Op_StoreI, "precondition");
3082
3083 if (other_store == nullptr ||
3084 _store->Opcode() != other_store->Opcode()) {
3085 return false;
3086 }
3087
3088 return true;
3089 }
3090
3091 bool MergePrimitiveStores::is_adjacent_pair(const StoreNode* use_store, const StoreNode* def_store) const {
3092 if (!is_adjacent_input_pair(def_store->in(MemNode::ValueIn),
3093 use_store->in(MemNode::ValueIn),
3094 def_store->memory_size())) {
3095 return false;
3096 }
3097
3098 ResourceMark rm;
3099 #ifndef PRODUCT
3100 const TraceMemPointer trace(is_trace_pointer_parsing(),
3101 is_trace_pointer_aliasing(),
3102 is_trace_pointer_adjacency(),
3103 true);
3104 #endif
3105 const MemPointer pointer_use(use_store NOT_PRODUCT(COMMA trace));
3106 const MemPointer pointer_def(def_store NOT_PRODUCT(COMMA trace));
3107 return pointer_def.is_adjacent_to_and_before(pointer_use);
3108 }
3109
3110 // Check input values n1 and n2 can be merged and return the value order
3111 MergePrimitiveStores::ValueOrder MergePrimitiveStores::find_adjacent_input_value_order(const Node* n1, const Node* n2,
3112 const int memory_size) const {
3113 // Pattern: [n1 = ConI, n2 = ConI]
3114 if (n1->Opcode() == Op_ConI && n2->Opcode() == Op_ConI) {
3115 return ValueOrder::Const;
3116 }
3117
3118 Node const *base_n2;
3119 jint shift_n2;
3120 if (!is_con_RShift(n2, base_n2, shift_n2, _phase)) {
3121 return ValueOrder::NotAdjacent;
3122 }
3123 Node const *base_n1;
3124 jint shift_n1;
3125 if (!is_con_RShift(n1, base_n1, shift_n1, _phase)) {
3126 return ValueOrder::NotAdjacent;
3127 }
3128
3129 int bits_per_store = memory_size * 8;
3130 if (base_n1 != base_n2 ||
3131 abs(shift_n1 - shift_n2) != bits_per_store ||
3132 shift_n1 % bits_per_store != 0) {
3133 // Values are not adjacent
3134 return ValueOrder::NotAdjacent;
3135 }
3136
3137 // Detect value order
3138 #ifdef VM_LITTLE_ENDIAN
3139 return shift_n1 < shift_n2 ? ValueOrder::Platform // Pattern: [n1 = base >> shift, n2 = base >> (shift + memory_size)]
3140 : ValueOrder::Reverse; // Pattern: [n1 = base >> (shift + memory_size), n2 = base >> shift]
3141 #else
3142 return shift_n1 > shift_n2 ? ValueOrder::Platform // Pattern: [n1 = base >> (shift + memory_size), n2 = base >> shift]
3143 : ValueOrder::Reverse; // Pattern: [n1 = base >> shift, n2 = base >> (shift + memory_size)]
3144 #endif
3145 }
3146
3147 bool MergePrimitiveStores::is_adjacent_input_pair(const Node* n1, const Node* n2, const int memory_size) const {
3148 ValueOrder input_value_order = find_adjacent_input_value_order(n1, n2, memory_size);
3149
3150 switch (input_value_order) {
3151 case ValueOrder::NotAdjacent:
3152 return false;
3153 case ValueOrder::Reverse:
3154 if (memory_size != 1 ||
3155 !Matcher::match_rule_supported(Op_ReverseBytesS) ||
3156 !Matcher::match_rule_supported(Op_ReverseBytesI) ||
3157 !Matcher::match_rule_supported(Op_ReverseBytesL)) {
3158 // ReverseBytes are not supported by platform
3159 return false;
3160 }
3161 // fall-through.
3162 case ValueOrder::Const:
3163 case ValueOrder::Platform:
3164 if (_value_order == ValueOrder::Unknown) {
3165 // Initial state is Unknown, and we find a valid input value order
3166 return true;
3167 }
3168 // The value order can not be changed
3169 return _value_order == input_value_order;
3170 case ValueOrder::Unknown:
3171 default:
3172 ShouldNotReachHere();
3173 }
3174 return false;
3175 }
3176
3177 // Detect pattern: n = base_out >> shift_out
3178 bool MergePrimitiveStores::is_con_RShift(const Node* n, Node const*& base_out, jint& shift_out, PhaseGVN* phase) {
3179 assert(n != nullptr, "precondition");
3180
3181 int opc = n->Opcode();
3182 if (opc == Op_ConvL2I) {
3183 n = n->in(1);
3184 opc = n->Opcode();
3185 }
3186
3187 if ((opc == Op_RShiftI ||
3188 opc == Op_RShiftL ||
3189 opc == Op_URShiftI ||
3190 opc == Op_URShiftL) &&
3191 n->in(2)->is_ConI()) {
3192 base_out = n->in(1);
3193 shift_out = n->in(2)->get_int();
3194 // The shift must be positive:
3195 return shift_out >= 0;
3196 }
3197
3198 if (phase->type(n)->isa_int() != nullptr ||
3199 phase->type(n)->isa_long() != nullptr) {
3200 // (base >> 0)
3201 base_out = n;
3202 shift_out = 0;
3203 return true;
3204 }
3205 return false;
3206 }
3207
3208 // Check if there is nothing between the two stores, except optionally a RangeCheck leading to an uncommon trap.
3209 MergePrimitiveStores::CFGStatus MergePrimitiveStores::cfg_status_for_pair(const StoreNode* use_store, const StoreNode* def_store) {
3210 assert(use_store->in(MemNode::Memory) == def_store, "use-def relationship");
3211
3212 Node* ctrl_use = use_store->in(MemNode::Control);
3213 Node* ctrl_def = def_store->in(MemNode::Control);
3214 if (ctrl_use == nullptr || ctrl_def == nullptr) {
3215 return CFGStatus::Failure;
3216 }
3217
3218 if (ctrl_use == ctrl_def) {
3219 // Same ctrl -> no RangeCheck in between.
3220 // Check: use_store must be the only use of def_store.
3221 if (def_store->outcnt() > 1) {
3222 return CFGStatus::Failure;
3223 }
3224 return CFGStatus::SuccessNoRangeCheck;
3225 }
3226
3227 // Different ctrl -> could have RangeCheck in between.
3228 // Check: 1. def_store only has these uses: use_store and MergeMem for uncommon trap, and
3229 // 2. ctrl separated by RangeCheck.
3230 if (def_store->outcnt() != 2) {
3231 return CFGStatus::Failure; // Cannot have exactly these uses: use_store and MergeMem for uncommon trap.
3232 }
3233 int use_store_out_idx = def_store->raw_out(0) == use_store ? 0 : 1;
3234 Node* merge_mem = def_store->raw_out(1 - use_store_out_idx)->isa_MergeMem();
3235 if (merge_mem == nullptr ||
3236 merge_mem->outcnt() != 1) {
3237 return CFGStatus::Failure; // Does not have MergeMem for uncommon trap.
3238 }
3239 if (!ctrl_use->is_IfProj() ||
3240 !ctrl_use->in(0)->is_RangeCheck() ||
3241 ctrl_use->in(0)->outcnt() != 2) {
3242 return CFGStatus::Failure; // Not RangeCheck.
3243 }
3244 IfProjNode* other_proj = ctrl_use->as_IfProj()->other_if_proj();
3245 Node* trap = other_proj->is_uncommon_trap_proj(Deoptimization::Reason_range_check);
3246 if (trap != merge_mem->unique_out() ||
3247 ctrl_use->in(0)->in(0) != ctrl_def) {
3248 return CFGStatus::Failure; // Not RangeCheck with merge_mem leading to uncommon trap.
3249 }
3250
3251 return CFGStatus::SuccessWithRangeCheck;
3252 }
3253
3254 MergePrimitiveStores::Status MergePrimitiveStores::find_adjacent_use_store(const StoreNode* def_store) const {
3255 Status status_use = find_use_store(def_store);
3256 StoreNode* use_store = status_use.found_store();
3257 if (use_store != nullptr && !is_adjacent_pair(use_store, def_store)) {
3258 return Status::make_failure();
3259 }
3260 return status_use;
3261 }
3262
3263 MergePrimitiveStores::Status MergePrimitiveStores::find_adjacent_def_store(const StoreNode* use_store) const {
3264 Status status_def = find_def_store(use_store);
3265 StoreNode* def_store = status_def.found_store();
3266 if (def_store != nullptr && !is_adjacent_pair(use_store, def_store)) {
3267 return Status::make_failure();
3268 }
3269 return status_def;
3270 }
3271
3272 MergePrimitiveStores::Status MergePrimitiveStores::find_use_store(const StoreNode* def_store) const {
3273 Status status_use = find_use_store_unidirectional(def_store);
3274
3275 #ifdef ASSERT
3276 StoreNode* use_store = status_use.found_store();
3277 if (use_store != nullptr) {
3278 Status status_def = find_def_store_unidirectional(use_store);
3279 assert(status_def.found_store() == def_store &&
3280 status_def.found_range_check() == status_use.found_range_check(),
3281 "find_use_store and find_def_store must be symmetric");
3282 }
3283 #endif
3284
3285 return status_use;
3286 }
3287
3288 MergePrimitiveStores::Status MergePrimitiveStores::find_def_store(const StoreNode* use_store) const {
3289 Status status_def = find_def_store_unidirectional(use_store);
3290
3291 #ifdef ASSERT
3292 StoreNode* def_store = status_def.found_store();
3293 if (def_store != nullptr) {
3294 Status status_use = find_use_store_unidirectional(def_store);
3295 assert(status_use.found_store() == use_store &&
3296 status_use.found_range_check() == status_def.found_range_check(),
3297 "find_use_store and find_def_store must be symmetric");
3298 }
3299 #endif
3300
3301 return status_def;
3302 }
3303
3304 MergePrimitiveStores::Status MergePrimitiveStores::find_use_store_unidirectional(const StoreNode* def_store) const {
3305 assert(is_compatible_store(def_store), "precondition: must be compatible with _store");
3306
3307 for (DUIterator_Fast imax, i = def_store->fast_outs(imax); i < imax; i++) {
3308 StoreNode* use_store = def_store->fast_out(i)->isa_Store();
3309 if (is_compatible_store(use_store)) {
3310 return Status::make(use_store, cfg_status_for_pair(use_store, def_store));
3311 }
3312 }
3313
3314 return Status::make_failure();
3315 }
3316
3317 MergePrimitiveStores::Status MergePrimitiveStores::find_def_store_unidirectional(const StoreNode* use_store) const {
3318 assert(is_compatible_store(use_store), "precondition: must be compatible with _store");
3319
3320 StoreNode* def_store = use_store->in(MemNode::Memory)->isa_Store();
3321 if (!is_compatible_store(def_store)) {
3322 return Status::make_failure();
3323 }
3324
3325 return Status::make(def_store, cfg_status_for_pair(use_store, def_store));
3326 }
3327
3328 void MergePrimitiveStores::collect_merge_list(Node_List& merge_list) const {
3329 // The merged store can be at most 8 bytes.
3330 const uint merge_list_max_size = 8 / _store->memory_size();
3331 assert(merge_list_max_size >= 2 &&
3332 merge_list_max_size <= 8 &&
3333 is_power_of_2(merge_list_max_size),
3334 "must be 2, 4 or 8");
3335
3336 // Traverse up the chain of adjacent def stores.
3337 StoreNode* current = _store;
3338 merge_list.push(current);
3339 while (current != nullptr && merge_list.size() < merge_list_max_size) {
3340 Status status = find_adjacent_def_store(current);
3341 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] find def: "); status.print_on(tty); })
3342
3343 current = status.found_store();
3344 if (current != nullptr) {
3345 merge_list.push(current);
3346
3347 // We can have at most one RangeCheck.
3348 if (status.found_range_check()) {
3349 NOT_PRODUCT( if (is_trace_basic()) { tty->print_cr("[TraceMergeStores] found RangeCheck, stop traversal."); })
3350 break;
3351 }
3352 }
3353 }
3354
3355 NOT_PRODUCT( if (is_trace_basic()) { tty->print_cr("[TraceMergeStores] found:"); merge_list.dump(); })
3356
3357 // Truncate the merge_list to a power of 2.
3358 const uint pow2size = round_down_power_of_2(merge_list.size());
3359 assert(pow2size >= 2, "must be merging at least 2 stores");
3360 while (merge_list.size() > pow2size) { merge_list.pop(); }
3361
3362 NOT_PRODUCT( if (is_trace_basic()) { tty->print_cr("[TraceMergeStores] truncated:"); merge_list.dump(); })
3363 }
3364
3365 // Merge the input values of the smaller stores to a single larger input value.
3366 Node* MergePrimitiveStores::make_merged_input_value(const Node_List& merge_list) {
3367 int new_memory_size = _store->memory_size() * merge_list.size();
3368 Node* first = merge_list.at(merge_list.size()-1);
3369 Node* merged_input_value = nullptr;
3370 if (_store->in(MemNode::ValueIn)->Opcode() == Op_ConI) {
3371 assert(_value_order == ValueOrder::Const, "must match");
3372 // Pattern: [ConI, ConI, ...] -> new constant
3373 jlong con = 0;
3374 jlong bits_per_store = _store->memory_size() * 8;
3375 jlong mask = (((jlong)1) << bits_per_store) - 1;
3376 for (uint i = 0; i < merge_list.size(); i++) {
3377 jlong con_i = merge_list.at(i)->in(MemNode::ValueIn)->get_int();
3378 #ifdef VM_LITTLE_ENDIAN
3379 con = con << bits_per_store;
3380 con = con | (mask & con_i);
3381 #else // VM_LITTLE_ENDIAN
3382 con_i = (mask & con_i) << (i * bits_per_store);
3383 con = con | con_i;
3384 #endif // VM_LITTLE_ENDIAN
3385 }
3386 merged_input_value = _phase->longcon(con);
3387 } else {
3388 assert(_value_order == ValueOrder::Platform || _value_order == ValueOrder::Reverse, "must match");
3389 // Pattern: [base >> 24, base >> 16, base >> 8, base] -> base
3390 // | |
3391 // _store first
3392 //
3393 Node* hi = _store->in(MemNode::ValueIn);
3394 Node* lo = first->in(MemNode::ValueIn);
3395 #ifndef VM_LITTLE_ENDIAN
3396 // `_store` and `first` are swapped in the diagram above
3397 swap(hi, lo);
3398 #endif // !VM_LITTLE_ENDIAN
3399 if (_value_order == ValueOrder::Reverse) {
3400 swap(hi, lo);
3401 }
3402 Node const* hi_base;
3403 jint hi_shift;
3404 merged_input_value = lo;
3405 bool is_true = is_con_RShift(hi, hi_base, hi_shift, _phase);
3406 assert(is_true, "must detect con RShift");
3407 if (merged_input_value != hi_base && merged_input_value->Opcode() == Op_ConvL2I) {
3408 // look through
3409 merged_input_value = merged_input_value->in(1);
3410 }
3411 if (merged_input_value != hi_base) {
3412 // merged_input_value is not the base
3413 return nullptr;
3414 }
3415 }
3416
3417 if (_phase->type(merged_input_value)->isa_long() != nullptr && new_memory_size <= 4) {
3418 // Example:
3419 //
3420 // long base = ...;
3421 // a[0] = (byte)(base >> 0);
3422 // a[1] = (byte)(base >> 8);
3423 //
3424 merged_input_value = _phase->transform(new ConvL2INode(merged_input_value));
3425 }
3426
3427 assert((_phase->type(merged_input_value)->isa_int() != nullptr && new_memory_size <= 4) ||
3428 (_phase->type(merged_input_value)->isa_long() != nullptr && new_memory_size == 8),
3429 "merged_input_value is either int or long, and new_memory_size is small enough");
3430
3431 if (_value_order == ValueOrder::Reverse) {
3432 assert(_store->memory_size() == 1, "only implemented for bytes");
3433 if (new_memory_size == 8) {
3434 merged_input_value = _phase->transform(new ReverseBytesLNode(merged_input_value));
3435 } else if (new_memory_size == 4) {
3436 merged_input_value = _phase->transform(new ReverseBytesINode(merged_input_value));
3437 } else {
3438 assert(new_memory_size == 2, "sanity check");
3439 merged_input_value = _phase->transform(new ReverseBytesSNode(merged_input_value));
3440 }
3441 }
3442 return merged_input_value;
3443 }
3444
3445 // //
3446 // first_ctrl first_mem first_adr first_ctrl first_mem first_adr //
3447 // | | | | | | //
3448 // | | | | +---------------+ | //
3449 // | | | | | | | //
3450 // | | +---------+ | | +---------------+ //
3451 // | | | | | | | | //
3452 // +--------------+ | | v1 +------------------------------+ | | v1 //
3453 // | | | | | | | | | | | | //
3454 // RangeCheck first_store RangeCheck | | first_store //
3455 // | | | | | | | //
3456 // last_ctrl | +----> unc_trap last_ctrl | | +----> unc_trap //
3457 // | | ===> | | | //
3458 // +--------------+ | a2 v2 | | | //
3459 // | | | | | | | | //
3460 // | second_store | | | //
3461 // | | | | | [v1 v2 ... vn] //
3462 // ... ... | | | | //
3463 // | | | | | v //
3464 // +--------------+ | an vn +--------------+ | | merged_input_value //
3465 // | | | | | | | | //
3466 // last_store (= _store) merged_store //
3467 // //
3468 StoreNode* MergePrimitiveStores::make_merged_store(const Node_List& merge_list, Node* merged_input_value) {
3469 Node* first_store = merge_list.at(merge_list.size()-1);
3470 Node* last_ctrl = _store->in(MemNode::Control); // after (optional) RangeCheck
3471 Node* first_mem = first_store->in(MemNode::Memory);
3472 Node* first_adr = first_store->in(MemNode::Address);
3473
3474 const TypePtr* new_adr_type = _store->adr_type();
3475
3476 int new_memory_size = _store->memory_size() * merge_list.size();
3477 BasicType bt = T_ILLEGAL;
3478 switch (new_memory_size) {
3479 case 2: bt = T_SHORT; break;
3480 case 4: bt = T_INT; break;
3481 case 8: bt = T_LONG; break;
3482 }
3483
3484 StoreNode* merged_store = StoreNode::make(*_phase, last_ctrl, first_mem, first_adr,
3485 new_adr_type, merged_input_value, bt, MemNode::unordered);
3486
3487 // Marking the store mismatched is sufficient to prevent reordering, since array stores
3488 // are all on the same slice. Hence, we need no barriers.
3489 merged_store->set_mismatched_access();
3490
3491 // Constants above may now also be be packed -> put candidate on worklist
3492 _phase->is_IterGVN()->_worklist.push(first_mem);
3493
3494 return merged_store;
3495 }
3496
3497 #ifndef PRODUCT
3498 void MergePrimitiveStores::trace(const Node_List& merge_list, const Node* merged_input_value, const StoreNode* merged_store) const {
3499 stringStream ss;
3500 ss.print_cr("[TraceMergeStores]: Replace");
3501 for (int i = (int)merge_list.size() - 1; i >= 0; i--) {
3502 merge_list.at(i)->dump("\n", false, &ss);
3503 }
3504 ss.print_cr("[TraceMergeStores]: with");
3505 merged_input_value->dump("\n", false, &ss);
3506 merged_store->dump("\n", false, &ss);
3507 tty->print("%s", ss.as_string());
3508 }
3509 #endif
3510
3511 //------------------------------Ideal------------------------------------------
3512 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
3513 // When a store immediately follows a relevant allocation/initialization,
3514 // try to capture it into the initialization, or hoist it above.
3515 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3516 Node* p = MemNode::Ideal_common(phase, can_reshape);
3517 if (p) return (p == NodeSentinel) ? nullptr : p;
3518
3519 Node* mem = in(MemNode::Memory);
3520 Node* address = in(MemNode::Address);
3521 Node* value = in(MemNode::ValueIn);
3522 // Back-to-back stores to same address? Fold em up. Generally
3523 // unsafe if I have intervening uses.
3524 {
3525 Node* st = mem;
3526 // If Store 'st' has more than one use, we cannot fold 'st' away.
3527 // For example, 'st' might be the final state at a conditional
3528 // return. Or, 'st' might be used by some node which is live at
3529 // the same time 'st' is live, which might be unschedulable. So,
3530 // require exactly ONE user until such time as we clone 'mem' for
3531 // each of 'mem's uses (thus making the exactly-1-user-rule hold
3532 // true).
3533 while (st->is_Store() && st->outcnt() == 1) {
3534 // Looking at a dead closed cycle of memory?
3535 assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
3536 assert(Opcode() == st->Opcode() ||
3537 st->Opcode() == Op_StoreVector ||
3538 Opcode() == Op_StoreVector ||
3539 st->Opcode() == Op_StoreVectorScatter ||
3540 Opcode() == Op_StoreVectorScatter ||
3541 phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw ||
3542 (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode
3543 (Opcode() == Op_StoreI && st->Opcode() == Op_StoreL) || // initialization by arraycopy
3544 (is_mismatched_access() || st->as_Store()->is_mismatched_access()),
3545 "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]);
3546
3547 if (st->in(MemNode::Address)->eqv_uncast(address) &&
3548 st->as_Store()->memory_size() <= this->memory_size()) {
3549 Node* use = st->raw_out(0);
3550 if (phase->is_IterGVN()) {
3551 phase->is_IterGVN()->rehash_node_delayed(use);
3552 }
3553 // It's OK to do this in the parser, since DU info is always accurate,
3554 // and the parser always refers to nodes via SafePointNode maps.
3555 use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase);
3556 return this;
3557 }
3558 st = st->in(MemNode::Memory);
3559 }
3560 }
3561
3562
3563 // Capture an unaliased, unconditional, simple store into an initializer.
3564 // Or, if it is independent of the allocation, hoist it above the allocation.
3565 if (ReduceFieldZeroing && /*can_reshape &&*/
3566 mem->is_Proj() && mem->in(0)->is_Initialize()) {
3567 InitializeNode* init = mem->in(0)->as_Initialize();
3568 intptr_t offset = init->can_capture_store(this, phase, can_reshape);
3569 if (offset > 0) {
3570 Node* moved = init->capture_store(this, offset, phase, can_reshape);
3571 // If the InitializeNode captured me, it made a raw copy of me,
3572 // and I need to disappear.
3573 if (moved != nullptr) {
3574 // %%% hack to ensure that Ideal returns a new node:
3575 mem = MergeMemNode::make(mem);
3576 return mem; // fold me away
3577 }
3578 }
3579 }
3580
3581 // Fold reinterpret cast into memory operation:
3582 // StoreX mem (MoveY2X v) => StoreY mem v
3583 if (value->is_Move()) {
3584 const Type* vt = value->in(1)->bottom_type();
3585 if (has_reinterpret_variant(vt)) {
3586 if (phase->C->post_loop_opts_phase()) {
3587 return convert_to_reinterpret_store(*phase, value->in(1), vt);
3588 } else {
3589 phase->C->record_for_post_loop_opts_igvn(this); // attempt the transformation once loop opts are over
3590 }
3591 }
3592 }
3593
3594 if (MergeStores && UseUnalignedAccesses) {
3595 if (phase->C->merge_stores_phase()) {
3596 MergePrimitiveStores merge(phase, this);
3597 Node* progress = merge.run();
3598 if (progress != nullptr) { return progress; }
3599 } else {
3600 // We need to wait with merging stores until RangeCheck smearing has removed the RangeChecks during
3601 // the post loops IGVN phase. If we do it earlier, then there may still be some RangeChecks between
3602 // the stores, and we merge the wrong sequence of stores.
3603 // Example:
3604 // StoreI RangeCheck StoreI StoreI RangeCheck StoreI
3605 // Apply MergeStores:
3606 // StoreI RangeCheck [ StoreL ] RangeCheck StoreI
3607 // Remove more RangeChecks:
3608 // StoreI [ StoreL ] StoreI
3609 // But now it would have been better to do this instead:
3610 // [ StoreL ] [ StoreL ]
3611 phase->C->record_for_merge_stores_igvn(this);
3612 }
3613 }
3614
3615 return nullptr; // No further progress
3616 }
3617
3618 //------------------------------Value-----------------------------------------
3619 const Type* StoreNode::Value(PhaseGVN* phase) const {
3620 // Either input is TOP ==> the result is TOP
3621 const Type *t1 = phase->type( in(MemNode::Memory) );
3622 if( t1 == Type::TOP ) return Type::TOP;
3623 const Type *t2 = phase->type( in(MemNode::Address) );
3624 if( t2 == Type::TOP ) return Type::TOP;
3625 const Type *t3 = phase->type( in(MemNode::ValueIn) );
3626 if( t3 == Type::TOP ) return Type::TOP;
3627 return Type::MEMORY;
3628 }
3629
3630 //------------------------------Identity---------------------------------------
3631 // Remove redundant stores:
3632 // Store(m, p, Load(m, p)) changes to m.
3633 // Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
3634 Node* StoreNode::Identity(PhaseGVN* phase) {
3635 Node* mem = in(MemNode::Memory);
3636 Node* adr = in(MemNode::Address);
3637 Node* val = in(MemNode::ValueIn);
3638
3639 Node* result = this;
3640
3641 // Load then Store? Then the Store is useless
3642 if (val->is_Load() &&
3643 val->in(MemNode::Address)->eqv_uncast(adr) &&
3644 val->in(MemNode::Memory )->eqv_uncast(mem) &&
3645 val->as_Load()->store_Opcode() == Opcode()) {
3646 if (!is_StoreVector()) {
3647 result = mem;
3648 } else if (Opcode() == Op_StoreVector && val->Opcode() == Op_LoadVector &&
3649 as_StoreVector()->vect_type() == val->as_LoadVector()->vect_type()) {
3650 // Ensure both are not masked accesses or gathers/scatters and vector types are the same
3651 result = mem;
3652 }
3653 }
3654
3655 // Two stores in a row of the same value?
3656 if (result == this &&
3657 mem->is_Store() &&
3658 mem->in(MemNode::Address)->eqv_uncast(adr) &&
3659 mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
3660 mem->Opcode() == Opcode()) {
3661 if (!is_StoreVector()) {
3662 result = mem;
3663 } else {
3664 const StoreVectorNode* store_vector = as_StoreVector();
3665 const StoreVectorNode* mem_vector = mem->as_StoreVector();
3666 const Node* store_indices = store_vector->indices();
3667 const Node* mem_indices = mem_vector->indices();
3668 const Node* store_mask = store_vector->mask();
3669 const Node* mem_mask = mem_vector->mask();
3670 // Ensure types, indices, and masks match
3671 if (store_vector->vect_type() == mem_vector->vect_type() &&
3672 ((store_indices == nullptr) == (mem_indices == nullptr) &&
3673 (store_indices == nullptr || store_indices->eqv_uncast(mem_indices))) &&
3674 ((store_mask == nullptr) == (mem_mask == nullptr) &&
3675 (store_mask == nullptr || store_mask->eqv_uncast(mem_mask)))) {
3676 result = mem;
3677 }
3678 }
3679 }
3680
3681 // Store of zero anywhere into a freshly-allocated object?
3682 // Then the store is useless.
3683 // (It must already have been captured by the InitializeNode.)
3684 if (result == this &&
3685 ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
3686 // a newly allocated object is already all-zeroes everywhere
3687 if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
3688 result = mem;
3689 }
3690
3691 if (result == this) {
3692 // the store may also apply to zero-bits in an earlier object
3693 Node* prev_mem = find_previous_store(phase);
3694 // Steps (a), (b): Walk past independent stores to find an exact match.
3695 if (prev_mem != nullptr) {
3696 if (prev_mem->is_top()) {
3697 // find_previous_store returns top when the access is dead
3698 return prev_mem;
3699 }
3700 Node* prev_val = can_see_stored_value(prev_mem, phase);
3701 if (prev_val != nullptr && prev_val == val) {
3702 // prev_val and val might differ by a cast; it would be good
3703 // to keep the more informative of the two.
3704 result = mem;
3705 }
3706 }
3707 }
3708 }
3709
3710 PhaseIterGVN* igvn = phase->is_IterGVN();
3711 if (result != this && igvn != nullptr) {
3712 MemBarNode* trailing = trailing_membar();
3713 if (trailing != nullptr) {
3714 #ifdef ASSERT
3715 const TypeOopPtr* t_oop = phase->type(in(Address))->isa_oopptr();
3716 assert(t_oop == nullptr || t_oop->is_known_instance_field(), "only for non escaping objects");
3717 #endif
3718 trailing->remove(igvn);
3719 }
3720 }
3721
3722 return result;
3723 }
3724
3725 //------------------------------match_edge-------------------------------------
3726 // Do we Match on this edge index or not? Match only memory & value
3727 uint StoreNode::match_edge(uint idx) const {
3728 return idx == MemNode::Address || idx == MemNode::ValueIn;
3729 }
3730
3731 //------------------------------cmp--------------------------------------------
3732 // Do not common stores up together. They generally have to be split
3733 // back up anyways, so do not bother.
3734 bool StoreNode::cmp( const Node &n ) const {
3735 return (&n == this); // Always fail except on self
3736 }
3737
3738 //------------------------------Ideal_masked_input-----------------------------
3739 // Check for a useless mask before a partial-word store
3740 // (StoreB ... (AndI valIn conIa) )
3741 // If (conIa & mask == mask) this simplifies to
3742 // (StoreB ... (valIn) )
3743 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
3744 Node *val = in(MemNode::ValueIn);
3745 if( val->Opcode() == Op_AndI ) {
3746 const TypeInt *t = phase->type( val->in(2) )->isa_int();
3747 if( t && t->is_con() && (t->get_con() & mask) == mask ) {
3748 set_req_X(MemNode::ValueIn, val->in(1), phase);
3749 return this;
3750 }
3751 }
3752 return nullptr;
3753 }
3754
3755
3756 //------------------------------Ideal_sign_extended_input----------------------
3757 // Check for useless sign-extension before a partial-word store
3758 // (StoreB ... (RShiftI _ (LShiftI _ v conIL) conIR))
3759 // If (conIL == conIR && conIR <= num_rejected_bits) this simplifies to
3760 // (StoreB ... (v))
3761 // If (conIL > conIR) under some conditions, it can be simplified into
3762 // (StoreB ... (LShiftI _ v (conIL - conIR)))
3763 // This case happens when the value of the store was itself a left shift, that
3764 // gets merged into the inner left shift of the sign-extension. For instance,
3765 // if we have
3766 // array_of_shorts[0] = (short)(v << 2)
3767 // We get a structure such as:
3768 // (StoreB ... (RShiftI _ (LShiftI _ (LShiftI _ v 2) 16) 16))
3769 // that is simplified into
3770 // (StoreB ... (RShiftI _ (LShiftI _ v 18) 16)).
3771 // It is thus useful to handle cases where conIL > conIR. But this simplification
3772 // does not always hold. Let's see in which cases it's valid.
3773 //
3774 // Let's assume we have the following 32 bits integer v:
3775 // +----------------------------------+
3776 // | v[0..31] |
3777 // +----------------------------------+
3778 // 31 0
3779 // that will be stuffed in 8 bits byte after a shift left and a shift right of
3780 // potentially different magnitudes.
3781 // We denote num_rejected_bits the number of bits of the discarded part. In this
3782 // case, num_rejected_bits == 24.
3783 //
3784 // Statement (proved further below in case analysis):
3785 // Given:
3786 // - 0 <= conIL < BitsPerJavaInteger (no wrap in shift, enforced by maskShiftAmount)
3787 // - 0 <= conIR < BitsPerJavaInteger (no wrap in shift, enforced by maskShiftAmount)
3788 // - conIL >= conIR
3789 // - num_rejected_bits >= conIR
3790 // Then this form:
3791 // (RShiftI _ (LShiftI _ v conIL) conIR)
3792 // can be replaced with this form:
3793 // (LShiftI _ v (conIL-conIR))
3794 //
3795 // Note: We only have to show that the non-rejected lowest bits (8 bits for byte)
3796 // have to be correct, as the higher bits are rejected / truncated by the store.
3797 //
3798 // The hypotheses
3799 // 0 <= conIL < BitsPerJavaInteger
3800 // 0 <= conIR < BitsPerJavaInteger
3801 // are ensured by maskShiftAmount (called from ::Ideal of shift nodes). Indeed,
3802 // (v << 31) << 2 must be simplified into 0, not into v << 33 (which is equivalent
3803 // to v << 1).
3804 //
3805 //
3806 // If you don't like case analysis, jump after the conclusion.
3807 // ### Case 1 : conIL == conIR
3808 // ###### Case 1.1: conIL == conIR == num_rejected_bits
3809 // If we do the shift left then right by 24 bits, we get:
3810 // after: v << 24
3811 // +---------+------------------------+
3812 // | v[0..7] | 0 |
3813 // +---------+------------------------+
3814 // 31 24 23 0
3815 // after: (v << 24) >> 24
3816 // +------------------------+---------+
3817 // | sign bit | v[0..7] |
3818 // +------------------------+---------+
3819 // 31 8 7 0
3820 // The non-rejected bits (bits kept by the store, that is the 8 lower bits of the
3821 // result) are the same before and after, so, indeed, simplifying is correct.
3822
3823 // ###### Case 1.2: conIL == conIR < num_rejected_bits
3824 // If we do the shift left then right by 22 bits, we get:
3825 // after: v << 22
3826 // +---------+------------------------+
3827 // | v[0..9] | 0 |
3828 // +---------+------------------------+
3829 // 31 22 21 0
3830 // after: (v << 22) >> 22
3831 // +------------------------+---------+
3832 // | sign bit | v[0..9] |
3833 // +------------------------+---------+
3834 // 31 10 9 0
3835 // The non-rejected bits are the 8 lower bits of v. The bits 8 and 9 of v are still
3836 // present in (v << 22) >> 22 but will be dropped by the store. The simplification is
3837 // still correct.
3838
3839 // ###### But! Case 1.3: conIL == conIR > num_rejected_bits
3840 // If we do the shift left then right by 26 bits, we get:
3841 // after: v << 26
3842 // +---------+------------------------+
3843 // | v[0..5] | 0 |
3844 // +---------+------------------------+
3845 // 31 26 25 0
3846 // after: (v << 26) >> 26
3847 // +------------------------+---------+
3848 // | sign bit | v[0..5] |
3849 // +------------------------+---------+
3850 // 31 6 5 0
3851 // The non-rejected bits are made of
3852 // - 0-5 => the bits 0 to 5 of v
3853 // - 6-7 => the sign bit of v[0..5] (that is v[5])
3854 // Simplifying this as v is not correct.
3855 // The condition conIR <= num_rejected_bits is indeed necessary in Case 1
3856 //
3857 // ### Case 2: conIL > conIR
3858 // ###### Case 2.1: num_rejected_bits == conIR
3859 // We take conIL == 26 for this example.
3860 // after: v << 26
3861 // +---------+------------------------+
3862 // | v[0..5] | 0 |
3863 // +---------+------------------------+
3864 // 31 26 25 0
3865 // after: (v << 26) >> 24
3866 // +------------------+---------+-----+
3867 // | sign bit | v[0..5] | 0 |
3868 // +------------------+---------+-----+
3869 // 31 8 7 2 1 0
3870 // The non-rejected bits are the 8 lower ones of (v << conIL - conIR).
3871 // The bits 6 and 7 of v have been thrown away after the shift left.
3872 // The simplification is still correct.
3873 //
3874 // ###### Case 2.2: num_rejected_bits > conIR.
3875 // Let's say conIL == 26 and conIR == 22.
3876 // after: v << 26
3877 // +---------+------------------------+
3878 // | v[0..5] | 0 |
3879 // +---------+------------------------+
3880 // 31 26 25 0
3881 // after: (v << 26) >> 22
3882 // +------------------+---------+-----+
3883 // | sign bit | v[0..5] | 0 |
3884 // +------------------+---------+-----+
3885 // 31 10 9 4 3 0
3886 // The bits non-rejected by the store are exactly the 8 lower ones of (v << (conIL - conIR)):
3887 // - 0-3 => 0
3888 // - 4-7 => bits 0 to 3 of v
3889 // The simplification is still correct.
3890 // The bits 4 and 5 of v are still present in (v << (conIL - conIR)) but they don't
3891 // matter as they are not in the 8 lower bits: they will be cut out by the store.
3892 //
3893 // ###### But! Case 2.3: num_rejected_bits < conIR.
3894 // Let's see that this case is not as easy to simplify.
3895 // Let's say conIL == 28 and conIR == 26.
3896 // after: v << 28
3897 // +---------+------------------------+
3898 // | v[0..3] | 0 |
3899 // +---------+------------------------+
3900 // 31 28 27 0
3901 // after: (v << 28) >> 26
3902 // +------------------+---------+-----+
3903 // | sign bit | v[0..3] | 0 |
3904 // +------------------+---------+-----+
3905 // 31 6 5 2 1 0
3906 // The non-rejected bits are made of
3907 // - 0-1 => 0
3908 // - 2-5 => the bits 0 to 3 of v
3909 // - 6-7 => the sign bit of v[0..3] (that is v[3])
3910 // Simplifying this as (v << 2) is not correct.
3911 // The condition conIR <= num_rejected_bits is indeed necessary in Case 2.
3912 //
3913 // ### Conclusion:
3914 // Our hypotheses are indeed sufficient:
3915 // - 0 <= conIL < BitsPerJavaInteger
3916 // - 0 <= conIR < BitsPerJavaInteger
3917 // - conIL >= conIR
3918 // - num_rejected_bits >= conIR
3919 //
3920 // ### A rationale without case analysis:
3921 // After the shift left, conIL upper bits of v are discarded and conIL lower bit
3922 // zeroes are added. After the shift right, conIR lower bits of the previous result
3923 // are discarded. If conIL >= conIR, we discard only the zeroes we made up during
3924 // the shift left, but if conIL < conIR, then we discard also lower bits of v. But
3925 // the point of the simplification is to get an expression of the form
3926 // (v << (conIL - conIR)). This expression discard only higher bits of v, thus the
3927 // simplification is not correct if conIL < conIR.
3928 //
3929 // Moreover, after the shift right, the higher bit of (v << conIL) is repeated on the
3930 // conIR higher bits of ((v << conIL) >> conIR), it's the sign-extension. If
3931 // conIR > num_rejected_bits, then at least one artificial copy of this sign bit will
3932 // be in the window of the store. Thus ((v << conIL) >> conIR) is not equivalent to
3933 // (v << (conIL-conIR)) if conIR > num_rejected_bits.
3934 //
3935 // We do not treat the case conIL < conIR here since the point of this function is
3936 // to skip sign-extensions (that is conIL == conIR == num_rejected_bits). The need
3937 // of treating conIL > conIR comes from the cases where the sign-extended value is
3938 // also left-shift expression. Computing the sign-extension of a right-shift expression
3939 // doesn't yield a situation such as
3940 // (StoreB ... (RShiftI _ (LShiftI _ v conIL) conIR))
3941 // where conIL < conIR.
3942 Node* StoreNode::Ideal_sign_extended_input(PhaseGVN* phase, int num_rejected_bits) {
3943 Node* shr = in(MemNode::ValueIn);
3944 if (shr->Opcode() == Op_RShiftI) {
3945 const TypeInt* conIR = phase->type(shr->in(2))->isa_int();
3946 if (conIR != nullptr && conIR->is_con() && conIR->get_con() >= 0 && conIR->get_con() < BitsPerJavaInteger && conIR->get_con() <= num_rejected_bits) {
3947 Node* shl = shr->in(1);
3948 if (shl->Opcode() == Op_LShiftI) {
3949 const TypeInt* conIL = phase->type(shl->in(2))->isa_int();
3950 if (conIL != nullptr && conIL->is_con() && conIL->get_con() >= 0 && conIL->get_con() < BitsPerJavaInteger) {
3951 if (conIL->get_con() == conIR->get_con()) {
3952 set_req_X(MemNode::ValueIn, shl->in(1), phase);
3953 return this;
3954 }
3955 if (conIL->get_con() > conIR->get_con()) {
3956 Node* new_shl = phase->transform(new LShiftINode(shl->in(1), phase->intcon(conIL->get_con() - conIR->get_con())));
3957 set_req_X(MemNode::ValueIn, new_shl, phase);
3958 return this;
3959 }
3960 }
3961 }
3962 }
3963 }
3964 return nullptr;
3965 }
3966
3967 //------------------------------value_never_loaded-----------------------------------
3968 // Determine whether there are any possible loads of the value stored.
3969 // For simplicity, we actually check if there are any loads from the
3970 // address stored to, not just for loads of the value stored by this node.
3971 //
3972 bool StoreNode::value_never_loaded(PhaseValues* phase) const {
3973 Node *adr = in(Address);
3974 const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
3975 if (adr_oop == nullptr)
3976 return false;
3977 if (!adr_oop->is_known_instance_field())
3978 return false; // if not a distinct instance, there may be aliases of the address
3979 for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
3980 Node *use = adr->fast_out(i);
3981 if (use->is_Load() || use->is_LoadStore()) {
3982 return false;
3983 }
3984 }
3985 return true;
3986 }
3987
3988 MemBarNode* StoreNode::trailing_membar() const {
3989 if (is_release()) {
3990 MemBarNode* trailing_mb = nullptr;
3991 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
3992 Node* u = fast_out(i);
3993 if (u->is_MemBar()) {
3994 if (u->as_MemBar()->trailing_store()) {
3995 assert(u->Opcode() == Op_MemBarVolatile, "");
3996 assert(trailing_mb == nullptr, "only one");
3997 trailing_mb = u->as_MemBar();
3998 #ifdef ASSERT
3999 Node* leading = u->as_MemBar()->leading_membar();
4000 assert(leading->Opcode() == Op_MemBarRelease, "incorrect membar");
4001 assert(leading->as_MemBar()->leading_store(), "incorrect membar pair");
4002 assert(leading->as_MemBar()->trailing_membar() == u, "incorrect membar pair");
4003 #endif
4004 } else {
4005 assert(u->as_MemBar()->standalone(), "");
4006 }
4007 }
4008 }
4009 return trailing_mb;
4010 }
4011 return nullptr;
4012 }
4013
4014
4015 //=============================================================================
4016 //------------------------------Ideal------------------------------------------
4017 // If the store is from an AND mask that leaves the low bits untouched, then
4018 // we can skip the AND operation. If the store is from a sign-extension
4019 // (a left shift, then right shift) we can skip both.
4020 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
4021 Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
4022 if( progress != nullptr ) return progress;
4023
4024 progress = StoreNode::Ideal_sign_extended_input(phase, 24);
4025 if( progress != nullptr ) return progress;
4026
4027 // Finally check the default case
4028 return StoreNode::Ideal(phase, can_reshape);
4029 }
4030
4031 //=============================================================================
4032 //------------------------------Ideal------------------------------------------
4033 // If the store is from an AND mask that leaves the low bits untouched, then
4034 // we can skip the AND operation
4035 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
4036 Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
4037 if( progress != nullptr ) return progress;
4038
4039 progress = StoreNode::Ideal_sign_extended_input(phase, 16);
4040 if( progress != nullptr ) return progress;
4041
4042 // Finally check the default case
4043 return StoreNode::Ideal(phase, can_reshape);
4044 }
4045
4046 //=============================================================================
4047 //----------------------------------SCMemProjNode------------------------------
4048 const Type* SCMemProjNode::Value(PhaseGVN* phase) const
4049 {
4050 if (in(0) == nullptr || phase->type(in(0)) == Type::TOP) {
4051 return Type::TOP;
4052 }
4053 return bottom_type();
4054 }
4055
4056 //=============================================================================
4057 //----------------------------------LoadStoreNode------------------------------
4058 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
4059 : Node(required),
4060 _type(rt),
4061 _barrier_data(0)
4062 {
4063 init_req(MemNode::Control, c );
4064 init_req(MemNode::Memory , mem);
4065 init_req(MemNode::Address, adr);
4066 init_req(MemNode::ValueIn, val);
4067 init_class_id(Class_LoadStore);
4068 DEBUG_ONLY(_adr_type = at; adr_type();)
4069 }
4070
4071 //------------------------------Value-----------------------------------------
4072 const Type* LoadStoreNode::Value(PhaseGVN* phase) const {
4073 // Either input is TOP ==> the result is TOP
4074 if (!in(MemNode::Control) || phase->type(in(MemNode::Control)) == Type::TOP) {
4075 return Type::TOP;
4076 }
4077 const Type* t = phase->type(in(MemNode::Memory));
4078 if (t == Type::TOP) {
4079 return Type::TOP;
4080 }
4081 t = phase->type(in(MemNode::Address));
4082 if (t == Type::TOP) {
4083 return Type::TOP;
4084 }
4085 t = phase->type(in(MemNode::ValueIn));
4086 if (t == Type::TOP) {
4087 return Type::TOP;
4088 }
4089 return bottom_type();
4090 }
4091
4092 const TypePtr* LoadStoreNode::adr_type() const {
4093 const TypePtr* cross_check = DEBUG_ONLY(_adr_type) NOT_DEBUG(nullptr);
4094 return MemNode::calculate_adr_type(in(MemNode::Address)->bottom_type(), cross_check);
4095 }
4096
4097 uint LoadStoreNode::ideal_reg() const {
4098 return _type->ideal_reg();
4099 }
4100
4101 // This method conservatively checks if the result of a LoadStoreNode is
4102 // used, that is, if it returns true, then it is definitely the case that
4103 // the result of the node is not needed.
4104 // For example, GetAndAdd can be matched into a lock_add instead of a
4105 // lock_xadd if the result of LoadStoreNode::result_not_used() is true
4106 bool LoadStoreNode::result_not_used() const {
4107 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
4108 Node *x = fast_out(i);
4109 if (x->Opcode() == Op_SCMemProj || x->is_ReachabilityFence()) {
4110 continue;
4111 }
4112 if (x->bottom_type() == TypeTuple::MEMBAR &&
4113 !x->is_Call() &&
4114 x->Opcode() != Op_Blackhole) {
4115 continue;
4116 }
4117 return false;
4118 }
4119 return true;
4120 }
4121
4122 MemBarNode* LoadStoreNode::trailing_membar() const {
4123 MemBarNode* trailing = nullptr;
4124 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
4125 Node* u = fast_out(i);
4126 if (u->is_MemBar()) {
4127 if (u->as_MemBar()->trailing_load_store()) {
4128 assert(u->Opcode() == Op_MemBarAcquire, "");
4129 assert(trailing == nullptr, "only one");
4130 trailing = u->as_MemBar();
4131 #ifdef ASSERT
4132 Node* leading = trailing->leading_membar();
4133 assert(support_IRIW_for_not_multiple_copy_atomic_cpu || leading->Opcode() == Op_MemBarRelease, "incorrect membar");
4134 assert(leading->as_MemBar()->leading_load_store(), "incorrect membar pair");
4135 assert(leading->as_MemBar()->trailing_membar() == trailing, "incorrect membar pair");
4136 #endif
4137 } else {
4138 assert(u->as_MemBar()->standalone(), "wrong barrier kind");
4139 }
4140 }
4141 }
4142
4143 return trailing;
4144 }
4145
4146 uint LoadStoreNode::size_of() const { return sizeof(*this); }
4147
4148 //=============================================================================
4149 //----------------------------------LoadStoreConditionalNode--------------------
4150 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, nullptr, TypeInt::BOOL, 5) {
4151 init_req(ExpectedIn, ex );
4152 }
4153
4154 const Type* LoadStoreConditionalNode::Value(PhaseGVN* phase) const {
4155 // Either input is TOP ==> the result is TOP
4156 const Type* t = phase->type(in(ExpectedIn));
4157 if (t == Type::TOP) {
4158 return Type::TOP;
4159 }
4160 return LoadStoreNode::Value(phase);
4161 }
4162
4163 //=============================================================================
4164 //-------------------------------adr_type--------------------------------------
4165 const TypePtr* ClearArrayNode::adr_type() const {
4166 Node *adr = in(3);
4167 if (adr == nullptr) return nullptr; // node is dead
4168 return MemNode::calculate_adr_type(adr->bottom_type());
4169 }
4170
4171 //------------------------------match_edge-------------------------------------
4172 // Do we Match on this edge index or not? Do not match memory
4173 uint ClearArrayNode::match_edge(uint idx) const {
4174 return idx > 1;
4175 }
4176
4177 //------------------------------Identity---------------------------------------
4178 // Clearing a zero length array does nothing
4179 Node* ClearArrayNode::Identity(PhaseGVN* phase) {
4180 return phase->type(in(2))->higher_equal(TypeX::ZERO) ? in(1) : this;
4181 }
4182
4183 //------------------------------Idealize---------------------------------------
4184 // Clearing a short array is faster with stores
4185 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4186 // Already know this is a large node, do not try to ideal it
4187 if (_is_large) return nullptr;
4188
4189 const int unit = BytesPerLong;
4190 const TypeX* t = phase->type(in(2))->isa_intptr_t();
4191 if (!t) return nullptr;
4192 if (!t->is_con()) return nullptr;
4193 intptr_t raw_count = t->get_con();
4194 intptr_t size = raw_count;
4195 if (!Matcher::init_array_count_is_in_bytes) size *= unit;
4196 // Clearing nothing uses the Identity call.
4197 // Negative clears are possible on dead ClearArrays
4198 // (see jck test stmt114.stmt11402.val).
4199 if (size <= 0 || size % unit != 0) return nullptr;
4200 intptr_t count = size / unit;
4201 // Length too long; communicate this to matchers and assemblers.
4202 // Assemblers are responsible to produce fast hardware clears for it.
4203 if (size > InitArrayShortSize) {
4204 return new ClearArrayNode(in(0), in(1), in(2), in(3), true);
4205 } else if (size > 2 && Matcher::match_rule_supported_vector(Op_ClearArray, 4, T_LONG)) {
4206 return nullptr;
4207 }
4208 if (!IdealizeClearArrayNode) return nullptr;
4209 Node *mem = in(1);
4210 if( phase->type(mem)==Type::TOP ) return nullptr;
4211 Node *adr = in(3);
4212 const Type* at = phase->type(adr);
4213 if( at==Type::TOP ) return nullptr;
4214 const TypePtr* atp = at->isa_ptr();
4215 // adjust atp to be the correct array element address type
4216 if (atp == nullptr) atp = TypePtr::BOTTOM;
4217 else atp = atp->add_offset(Type::OffsetBot);
4218 // Get base for derived pointer purposes
4219 if( adr->Opcode() != Op_AddP ) Unimplemented();
4220 Node *base = adr->in(1);
4221
4222 Node *zero = phase->makecon(TypeLong::ZERO);
4223 Node *off = phase->MakeConX(BytesPerLong);
4224 mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
4225 count--;
4226 while (count--) {
4227 mem = phase->transform(mem);
4228 adr = phase->transform(AddPNode::make_with_base(base, adr, off));
4229 mem = new StoreLNode(in(0), mem, adr, atp, zero, MemNode::unordered, false);
4230 }
4231 return mem;
4232 }
4233
4234 //----------------------------step_through----------------------------------
4235 // Return allocation input memory edge if it is different instance
4236 // or itself if it is the one we are looking for.
4237 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseValues* phase) {
4238 Node* n = *np;
4239 assert(n->is_ClearArray(), "sanity");
4240 intptr_t offset;
4241 AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
4242 // This method is called only before Allocate nodes are expanded
4243 // during macro nodes expansion. Before that ClearArray nodes are
4244 // only generated in PhaseMacroExpand::generate_arraycopy() (before
4245 // Allocate nodes are expanded) which follows allocations.
4246 assert(alloc != nullptr, "should have allocation");
4247 if (alloc->_idx == instance_id) {
4248 // Can not bypass initialization of the instance we are looking for.
4249 return false;
4250 }
4251 // Otherwise skip it.
4252 InitializeNode* init = alloc->initialization();
4253 if (init != nullptr)
4254 *np = init->in(TypeFunc::Memory);
4255 else
4256 *np = alloc->in(TypeFunc::Memory);
4257 return true;
4258 }
4259
4260 Node* ClearArrayNode::make_address(Node* dest, Node* offset, bool raw_base, PhaseGVN* phase) {
4261 Node* base = dest;
4262 if (raw_base) {
4263 // May be called as part of the initialization of a just allocated object
4264 base = phase->C->top();
4265 }
4266 return phase->transform(AddPNode::make_with_base(base, dest, offset));
4267 }
4268
4269 //----------------------------clear_memory-------------------------------------
4270 // Generate code to initialize object storage to zero.
4271 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
4272 intptr_t start_offset,
4273 Node* end_offset,
4274 bool raw_base,
4275 PhaseGVN* phase) {
4276 intptr_t offset = start_offset;
4277
4278 int unit = BytesPerLong;
4279 if ((offset % unit) != 0) {
4280 Node* adr = make_address(dest, phase->MakeConX(offset), raw_base, phase);
4281 const TypePtr* atp = TypeRawPtr::BOTTOM;
4282 mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
4283 mem = phase->transform(mem);
4284 offset += BytesPerInt;
4285 }
4286 assert((offset % unit) == 0, "");
4287
4288 // Initialize the remaining stuff, if any, with a ClearArray.
4289 return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, raw_base, phase);
4290 }
4291
4292 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
4293 Node* start_offset,
4294 Node* end_offset,
4295 bool raw_base,
4296 PhaseGVN* phase) {
4297 if (start_offset == end_offset) {
4298 // nothing to do
4299 return mem;
4300 }
4301
4302 int unit = BytesPerLong;
4303 Node* zbase = start_offset;
4304 Node* zend = end_offset;
4305
4306 // Scale to the unit required by the CPU:
4307 if (!Matcher::init_array_count_is_in_bytes) {
4308 Node* shift = phase->intcon(exact_log2(unit));
4309 zbase = phase->transform(new URShiftXNode(zbase, shift) );
4310 zend = phase->transform(new URShiftXNode(zend, shift) );
4311 }
4312
4313 // Bulk clear double-words
4314 Node* zsize = phase->transform(new SubXNode(zend, zbase) );
4315 Node* adr = make_address(dest, start_offset, raw_base, phase);
4316 mem = new ClearArrayNode(ctl, mem, zsize, adr, false);
4317 return phase->transform(mem);
4318 }
4319
4320 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
4321 intptr_t start_offset,
4322 intptr_t end_offset,
4323 bool raw_base,
4324 PhaseGVN* phase) {
4325 if (start_offset == end_offset) {
4326 // nothing to do
4327 return mem;
4328 }
4329
4330 assert((end_offset % BytesPerInt) == 0, "odd end offset");
4331 intptr_t done_offset = end_offset;
4332 if ((done_offset % BytesPerLong) != 0) {
4333 done_offset -= BytesPerInt;
4334 }
4335 if (done_offset > start_offset) {
4336 mem = clear_memory(ctl, mem, dest,
4337 start_offset, phase->MakeConX(done_offset), raw_base, phase);
4338 }
4339 if (done_offset < end_offset) { // emit the final 32-bit store
4340 Node* adr = make_address(dest, phase->MakeConX(done_offset), raw_base, phase);
4341 const TypePtr* atp = TypeRawPtr::BOTTOM;
4342 mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
4343 mem = phase->transform(mem);
4344 done_offset += BytesPerInt;
4345 }
4346 assert(done_offset == end_offset, "");
4347 return mem;
4348 }
4349
4350 //=============================================================================
4351 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
4352 : MultiNode(TypeFunc::Parms + (precedent == nullptr? 0: 1)),
4353 _adr_type(C->get_adr_type(alias_idx)), _kind(Standalone)
4354 #ifdef ASSERT
4355 , _pair_idx(0)
4356 #endif
4357 {
4358 init_class_id(Class_MemBar);
4359 Node* top = C->top();
4360 init_req(TypeFunc::I_O,top);
4361 init_req(TypeFunc::FramePtr,top);
4362 init_req(TypeFunc::ReturnAdr,top);
4363 if (precedent != nullptr)
4364 init_req(TypeFunc::Parms, precedent);
4365 }
4366
4367 //------------------------------cmp--------------------------------------------
4368 uint MemBarNode::hash() const { return NO_HASH; }
4369 bool MemBarNode::cmp( const Node &n ) const {
4370 return (&n == this); // Always fail except on self
4371 }
4372
4373 //------------------------------make-------------------------------------------
4374 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
4375 switch (opcode) {
4376 case Op_MemBarAcquire: return new MemBarAcquireNode(C, atp, pn);
4377 case Op_LoadFence: return new LoadFenceNode(C, atp, pn);
4378 case Op_MemBarRelease: return new MemBarReleaseNode(C, atp, pn);
4379 case Op_StoreFence: return new StoreFenceNode(C, atp, pn);
4380 case Op_MemBarStoreStore: return new MemBarStoreStoreNode(C, atp, pn);
4381 case Op_StoreStoreFence: return new StoreStoreFenceNode(C, atp, pn);
4382 case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn);
4383 case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn);
4384 case Op_MemBarStoreLoad: return new MemBarStoreLoadNode(C, atp, pn);
4385 case Op_MemBarVolatile: return new MemBarVolatileNode(C, atp, pn);
4386 case Op_MemBarFull: return new MemBarFullNode(C, atp, pn);
4387 case Op_MemBarCPUOrder: return new MemBarCPUOrderNode(C, atp, pn);
4388 case Op_OnSpinWait: return new OnSpinWaitNode(C, atp, pn);
4389 case Op_Initialize: return new InitializeNode(C, atp, pn);
4390 default: ShouldNotReachHere(); return nullptr;
4391 }
4392 }
4393
4394 void MemBarNode::remove(PhaseIterGVN *igvn) {
4395 assert(outcnt() > 0 && (outcnt() <= 2 || Opcode() == Op_Initialize), "Only one or two out edges allowed");
4396 if (trailing_store() || trailing_load_store()) {
4397 MemBarNode* leading = leading_membar();
4398 if (leading != nullptr) {
4399 assert(leading->trailing_membar() == this, "inconsistent leading/trailing membars");
4400 leading->remove(igvn);
4401 }
4402 }
4403 if (proj_out_or_null(TypeFunc::Control) != nullptr) {
4404 igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
4405 }
4406 if (is_Initialize()) {
4407 as_Initialize()->replace_mem_projs_by(in(TypeFunc::Memory), igvn);
4408 } else {
4409 if (proj_out_or_null(TypeFunc::Memory) != nullptr) {
4410 igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
4411 }
4412 }
4413 }
4414
4415 //------------------------------Ideal------------------------------------------
4416 // Return a node which is more "ideal" than the current node. Strip out
4417 // control copies
4418 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4419 if (remove_dead_region(phase, can_reshape)) return this;
4420 // Don't bother trying to transform a dead node
4421 if (in(0) && in(0)->is_top()) {
4422 return nullptr;
4423 }
4424
4425 bool progress = false;
4426 // Eliminate volatile MemBars for scalar replaced objects.
4427 if (can_reshape && req() == (Precedent+1)) {
4428 bool eliminate = false;
4429 int opc = Opcode();
4430 if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
4431 // Volatile field loads and stores.
4432 Node* my_mem = in(MemBarNode::Precedent);
4433 // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
4434 if ((my_mem != nullptr) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
4435 // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
4436 // replace this Precedent (decodeN) with the Load instead.
4437 if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1)) {
4438 Node* load_node = my_mem->in(1);
4439 set_req(MemBarNode::Precedent, load_node);
4440 phase->is_IterGVN()->_worklist.push(my_mem);
4441 my_mem = load_node;
4442 } else {
4443 assert(my_mem->unique_out() == this, "sanity");
4444 assert(!trailing_load_store(), "load store node can't be eliminated");
4445 del_req(Precedent);
4446 phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
4447 my_mem = nullptr;
4448 }
4449 progress = true;
4450 }
4451 if (my_mem != nullptr && my_mem->is_Mem()) {
4452 const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
4453 // Check for scalar replaced object reference.
4454 if( t_oop != nullptr && t_oop->is_known_instance_field() &&
4455 t_oop->offset() != Type::OffsetBot &&
4456 t_oop->offset() != Type::OffsetTop) {
4457 eliminate = true;
4458 }
4459 }
4460 } else if (opc == Op_MemBarRelease || (UseStoreStoreForCtor && opc == Op_MemBarStoreStore)) {
4461 // Final field stores.
4462 Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent));
4463 if ((alloc != nullptr) && alloc->is_Allocate() &&
4464 alloc->as_Allocate()->does_not_escape_thread()) {
4465 // The allocated object does not escape.
4466 eliminate = true;
4467 }
4468 }
4469 if (eliminate) {
4470 // Replace MemBar projections by its inputs.
4471 PhaseIterGVN* igvn = phase->is_IterGVN();
4472 remove(igvn);
4473 // Must return either the original node (now dead) or a new node
4474 // (Do not return a top here, since that would break the uniqueness of top.)
4475 return new ConINode(TypeInt::ZERO);
4476 }
4477 }
4478 return progress ? this : nullptr;
4479 }
4480
4481 //------------------------------Value------------------------------------------
4482 const Type* MemBarNode::Value(PhaseGVN* phase) const {
4483 if( !in(0) ) return Type::TOP;
4484 if( phase->type(in(0)) == Type::TOP )
4485 return Type::TOP;
4486 return TypeTuple::MEMBAR;
4487 }
4488
4489 //------------------------------match------------------------------------------
4490 // Construct projections for memory.
4491 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
4492 switch (proj->_con) {
4493 case TypeFunc::Control:
4494 case TypeFunc::Memory:
4495 return new MachProjNode(this, proj->_con, RegMask::EMPTY, MachProjNode::unmatched_proj);
4496 }
4497 ShouldNotReachHere();
4498 return nullptr;
4499 }
4500
4501 void MemBarNode::set_store_pair(MemBarNode* leading, MemBarNode* trailing) {
4502 trailing->_kind = TrailingStore;
4503 leading->_kind = LeadingStore;
4504 #ifdef ASSERT
4505 trailing->_pair_idx = leading->_idx;
4506 leading->_pair_idx = leading->_idx;
4507 #endif
4508 }
4509
4510 void MemBarNode::set_load_store_pair(MemBarNode* leading, MemBarNode* trailing) {
4511 trailing->_kind = TrailingLoadStore;
4512 leading->_kind = LeadingLoadStore;
4513 #ifdef ASSERT
4514 trailing->_pair_idx = leading->_idx;
4515 leading->_pair_idx = leading->_idx;
4516 #endif
4517 }
4518
4519 MemBarNode* MemBarNode::trailing_membar() const {
4520 ResourceMark rm;
4521 Node* trailing = (Node*)this;
4522 VectorSet seen;
4523 Node_Stack multis(0);
4524 do {
4525 Node* c = trailing;
4526 uint i = 0;
4527 do {
4528 trailing = nullptr;
4529 for (; i < c->outcnt(); i++) {
4530 Node* next = c->raw_out(i);
4531 if (next != c && next->is_CFG()) {
4532 if (c->is_MultiBranch()) {
4533 if (multis.node() == c) {
4534 multis.set_index(i+1);
4535 } else {
4536 multis.push(c, i+1);
4537 }
4538 }
4539 trailing = next;
4540 break;
4541 }
4542 }
4543 if (trailing != nullptr && !seen.test_set(trailing->_idx)) {
4544 break;
4545 }
4546 while (multis.size() > 0) {
4547 c = multis.node();
4548 i = multis.index();
4549 if (i < c->req()) {
4550 break;
4551 }
4552 multis.pop();
4553 }
4554 } while (multis.size() > 0);
4555 } while (!trailing->is_MemBar() || !trailing->as_MemBar()->trailing());
4556
4557 MemBarNode* mb = trailing->as_MemBar();
4558 assert((mb->_kind == TrailingStore && _kind == LeadingStore) ||
4559 (mb->_kind == TrailingLoadStore && _kind == LeadingLoadStore), "bad trailing membar");
4560 assert(mb->_pair_idx == _pair_idx, "bad trailing membar");
4561 return mb;
4562 }
4563
4564 MemBarNode* MemBarNode::leading_membar() const {
4565 ResourceMark rm;
4566 VectorSet seen;
4567 Node_Stack regions(0);
4568 Node* leading = in(0);
4569 while (leading != nullptr && (!leading->is_MemBar() || !leading->as_MemBar()->leading())) {
4570 while (leading == nullptr || leading->is_top() || seen.test_set(leading->_idx)) {
4571 leading = nullptr;
4572 while (regions.size() > 0 && leading == nullptr) {
4573 Node* r = regions.node();
4574 uint i = regions.index();
4575 if (i < r->req()) {
4576 leading = r->in(i);
4577 regions.set_index(i+1);
4578 } else {
4579 regions.pop();
4580 }
4581 }
4582 if (leading == nullptr) {
4583 assert(regions.size() == 0, "all paths should have been tried");
4584 return nullptr;
4585 }
4586 }
4587 if (leading->is_Region()) {
4588 regions.push(leading, 2);
4589 leading = leading->in(1);
4590 } else {
4591 leading = leading->in(0);
4592 }
4593 }
4594 #ifdef ASSERT
4595 Unique_Node_List wq;
4596 wq.push((Node*)this);
4597 uint found = 0;
4598 for (uint i = 0; i < wq.size(); i++) {
4599 Node* n = wq.at(i);
4600 if (n->is_Region()) {
4601 for (uint j = 1; j < n->req(); j++) {
4602 Node* in = n->in(j);
4603 if (in != nullptr && !in->is_top()) {
4604 wq.push(in);
4605 }
4606 }
4607 } else {
4608 if (n->is_MemBar() && n->as_MemBar()->leading()) {
4609 assert(n == leading, "consistency check failed");
4610 found++;
4611 } else {
4612 Node* in = n->in(0);
4613 if (in != nullptr && !in->is_top()) {
4614 wq.push(in);
4615 }
4616 }
4617 }
4618 }
4619 assert(found == 1 || (found == 0 && leading == nullptr), "consistency check failed");
4620 #endif
4621 if (leading == nullptr) {
4622 return nullptr;
4623 }
4624 MemBarNode* mb = leading->as_MemBar();
4625 assert((mb->_kind == LeadingStore && _kind == TrailingStore) ||
4626 (mb->_kind == LeadingLoadStore && _kind == TrailingLoadStore), "bad leading membar");
4627 assert(mb->_pair_idx == _pair_idx, "bad leading membar");
4628 return mb;
4629 }
4630
4631
4632 //===========================InitializeNode====================================
4633 // SUMMARY:
4634 // This node acts as a memory barrier on raw memory, after some raw stores.
4635 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
4636 // The Initialize can 'capture' suitably constrained stores as raw inits.
4637 // It can coalesce related raw stores into larger units (called 'tiles').
4638 // It can avoid zeroing new storage for memory units which have raw inits.
4639 // At macro-expansion, it is marked 'complete', and does not optimize further.
4640 //
4641 // EXAMPLE:
4642 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
4643 // ctl = incoming control; mem* = incoming memory
4644 // (Note: A star * on a memory edge denotes I/O and other standard edges.)
4645 // First allocate uninitialized memory and fill in the header:
4646 // alloc = (Allocate ctl mem* 16 #short[].klass ...)
4647 // ctl := alloc.Control; mem* := alloc.Memory*
4648 // rawmem = alloc.Memory; rawoop = alloc.RawAddress
4649 // Then initialize to zero the non-header parts of the raw memory block:
4650 // init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
4651 // ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
4652 // After the initialize node executes, the object is ready for service:
4653 // oop := (CheckCastPP init.Control alloc.RawAddress #short[])
4654 // Suppose its body is immediately initialized as {1,2}:
4655 // store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
4656 // store2 = (StoreC init.Control store1 (+ oop 14) 2)
4657 // mem.SLICE(#short[*]) := store2
4658 //
4659 // DETAILS:
4660 // An InitializeNode collects and isolates object initialization after
4661 // an AllocateNode and before the next possible safepoint. As a
4662 // memory barrier (MemBarNode), it keeps critical stores from drifting
4663 // down past any safepoint or any publication of the allocation.
4664 // Before this barrier, a newly-allocated object may have uninitialized bits.
4665 // After this barrier, it may be treated as a real oop, and GC is allowed.
4666 //
4667 // The semantics of the InitializeNode include an implicit zeroing of
4668 // the new object from object header to the end of the object.
4669 // (The object header and end are determined by the AllocateNode.)
4670 //
4671 // Certain stores may be added as direct inputs to the InitializeNode.
4672 // These stores must update raw memory, and they must be to addresses
4673 // derived from the raw address produced by AllocateNode, and with
4674 // a constant offset. They must be ordered by increasing offset.
4675 // The first one is at in(RawStores), the last at in(req()-1).
4676 // Unlike most memory operations, they are not linked in a chain,
4677 // but are displayed in parallel as users of the rawmem output of
4678 // the allocation.
4679 //
4680 // (See comments in InitializeNode::capture_store, which continue
4681 // the example given above.)
4682 //
4683 // When the associated Allocate is macro-expanded, the InitializeNode
4684 // may be rewritten to optimize collected stores. A ClearArrayNode
4685 // may also be created at that point to represent any required zeroing.
4686 // The InitializeNode is then marked 'complete', prohibiting further
4687 // capturing of nearby memory operations.
4688 //
4689 // During macro-expansion, all captured initializations which store
4690 // constant values of 32 bits or smaller are coalesced (if advantageous)
4691 // into larger 'tiles' 32 or 64 bits. This allows an object to be
4692 // initialized in fewer memory operations. Memory words which are
4693 // covered by neither tiles nor non-constant stores are pre-zeroed
4694 // by explicit stores of zero. (The code shape happens to do all
4695 // zeroing first, then all other stores, with both sequences occurring
4696 // in order of ascending offsets.)
4697 //
4698 // Alternatively, code may be inserted between an AllocateNode and its
4699 // InitializeNode, to perform arbitrary initialization of the new object.
4700 // E.g., the object copying intrinsics insert complex data transfers here.
4701 // The initialization must then be marked as 'complete' disable the
4702 // built-in zeroing semantics and the collection of initializing stores.
4703 //
4704 // While an InitializeNode is incomplete, reads from the memory state
4705 // produced by it are optimizable if they match the control edge and
4706 // new oop address associated with the allocation/initialization.
4707 // They return a stored value (if the offset matches) or else zero.
4708 // A write to the memory state, if it matches control and address,
4709 // and if it is to a constant offset, may be 'captured' by the
4710 // InitializeNode. It is cloned as a raw memory operation and rewired
4711 // inside the initialization, to the raw oop produced by the allocation.
4712 // Operations on addresses which are provably distinct (e.g., to
4713 // other AllocateNodes) are allowed to bypass the initialization.
4714 //
4715 // The effect of all this is to consolidate object initialization
4716 // (both arrays and non-arrays, both piecewise and bulk) into a
4717 // single location, where it can be optimized as a unit.
4718 //
4719 // Only stores with an offset less than TrackedInitializationLimit words
4720 // will be considered for capture by an InitializeNode. This puts a
4721 // reasonable limit on the complexity of optimized initializations.
4722
4723 //---------------------------InitializeNode------------------------------------
4724 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
4725 : MemBarNode(C, adr_type, rawoop),
4726 _is_complete(Incomplete), _does_not_escape(false)
4727 {
4728 init_class_id(Class_Initialize);
4729
4730 assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
4731 assert(in(RawAddress) == rawoop, "proper init");
4732 // Note: allocation() can be null, for secondary initialization barriers
4733 }
4734
4735 // Since this node is not matched, it will be processed by the
4736 // register allocator. Declare that there are no constraints
4737 // on the allocation of the RawAddress edge.
4738 const RegMask &InitializeNode::in_RegMask(uint idx) const {
4739 // This edge should be set to top, by the set_complete. But be conservative.
4740 if (idx == InitializeNode::RawAddress)
4741 return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
4742 return RegMask::EMPTY;
4743 }
4744
4745 Node* InitializeNode::memory(uint alias_idx) {
4746 Node* mem = in(Memory);
4747 if (mem->is_MergeMem()) {
4748 return mem->as_MergeMem()->memory_at(alias_idx);
4749 } else {
4750 // incoming raw memory is not split
4751 return mem;
4752 }
4753 }
4754
4755 bool InitializeNode::is_non_zero() {
4756 if (is_complete()) return false;
4757 remove_extra_zeroes();
4758 return (req() > RawStores);
4759 }
4760
4761 void InitializeNode::set_complete(PhaseGVN* phase) {
4762 assert(!is_complete(), "caller responsibility");
4763 _is_complete = Complete;
4764
4765 // After this node is complete, it contains a bunch of
4766 // raw-memory initializations. There is no need for
4767 // it to have anything to do with non-raw memory effects.
4768 // Therefore, tell all non-raw users to re-optimize themselves,
4769 // after skipping the memory effects of this initialization.
4770 PhaseIterGVN* igvn = phase->is_IterGVN();
4771 if (igvn) igvn->add_users_to_worklist(this);
4772 }
4773
4774 // convenience function
4775 // return false if the init contains any stores already
4776 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
4777 InitializeNode* init = initialization();
4778 if (init == nullptr || init->is_complete()) return false;
4779 init->remove_extra_zeroes();
4780 // for now, if this allocation has already collected any inits, bail:
4781 if (init->is_non_zero()) return false;
4782 init->set_complete(phase);
4783 return true;
4784 }
4785
4786 void InitializeNode::remove_extra_zeroes() {
4787 if (req() == RawStores) return;
4788 Node* zmem = zero_memory();
4789 uint fill = RawStores;
4790 for (uint i = fill; i < req(); i++) {
4791 Node* n = in(i);
4792 if (n->is_top() || n == zmem) continue; // skip
4793 if (fill < i) set_req(fill, n); // compact
4794 ++fill;
4795 }
4796 // delete any empty spaces created:
4797 while (fill < req()) {
4798 del_req(fill);
4799 }
4800 }
4801
4802 // Helper for remembering which stores go with which offsets.
4803 intptr_t InitializeNode::get_store_offset(Node* st, PhaseValues* phase) {
4804 if (!st->is_Store()) return -1; // can happen to dead code via subsume_node
4805 intptr_t offset = -1;
4806 Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
4807 phase, offset);
4808 if (base == nullptr) return -1; // something is dead,
4809 if (offset < 0) return -1; // dead, dead
4810 return offset;
4811 }
4812
4813 // Helper for proving that an initialization expression is
4814 // "simple enough" to be folded into an object initialization.
4815 // Attempts to prove that a store's initial value 'n' can be captured
4816 // within the initialization without creating a vicious cycle, such as:
4817 // { Foo p = new Foo(); p.next = p; }
4818 // True for constants and parameters and small combinations thereof.
4819 bool InitializeNode::detect_init_independence(Node* value, PhaseGVN* phase) {
4820 ResourceMark rm;
4821 Unique_Node_List worklist;
4822 worklist.push(value);
4823
4824 uint complexity_limit = 20;
4825 for (uint j = 0; j < worklist.size(); j++) {
4826 if (j >= complexity_limit) {
4827 return false; // Bail out if processed too many nodes
4828 }
4829
4830 Node* n = worklist.at(j);
4831 if (n == nullptr) continue; // (can this really happen?)
4832 if (n->is_Proj()) n = n->in(0);
4833 if (n == this) return false; // found a cycle
4834 if (n->is_Con()) continue;
4835 if (n->is_Start()) continue; // params, etc., are OK
4836 if (n->is_Root()) continue; // even better
4837
4838 // There cannot be any dependency if 'n' is a CFG node that dominates the current allocation
4839 if (n->is_CFG() && phase->is_dominator(n, allocation())) {
4840 continue;
4841 }
4842
4843 Node* ctl = n->in(0);
4844 if (ctl != nullptr && !ctl->is_top()) {
4845 if (ctl->is_Proj()) ctl = ctl->in(0);
4846 if (ctl == this) return false;
4847
4848 // If we already know that the enclosing memory op is pinned right after
4849 // the init, then any control flow that the store has picked up
4850 // must have preceded the init, or else be equal to the init.
4851 // Even after loop optimizations (which might change control edges)
4852 // a store is never pinned *before* the availability of its inputs.
4853 if (!MemNode::all_controls_dominate(n, this, phase)) {
4854 return false; // failed to prove a good control
4855 }
4856 }
4857
4858 // Check data edges for possible dependencies on 'this'.
4859 for (uint i = 1; i < n->req(); i++) {
4860 Node* m = n->in(i);
4861 if (m == nullptr || m == n || m->is_top()) continue;
4862
4863 // Only process data inputs once
4864 worklist.push(m);
4865 }
4866 }
4867
4868 return true;
4869 }
4870
4871 // Here are all the checks a Store must pass before it can be moved into
4872 // an initialization. Returns zero if a check fails.
4873 // On success, returns the (constant) offset to which the store applies,
4874 // within the initialized memory.
4875 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseGVN* phase, bool can_reshape) {
4876 const int FAIL = 0;
4877 if (st->req() != MemNode::ValueIn + 1)
4878 return FAIL; // an inscrutable StoreNode (card mark?)
4879 Node* ctl = st->in(MemNode::Control);
4880 if (!(ctl != nullptr && ctl->is_Proj() && ctl->in(0) == this))
4881 return FAIL; // must be unconditional after the initialization
4882 Node* mem = st->in(MemNode::Memory);
4883 if (!(mem->is_Proj() && mem->in(0) == this))
4884 return FAIL; // must not be preceded by other stores
4885 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4886 if ((st->Opcode() == Op_StoreP || st->Opcode() == Op_StoreN) &&
4887 !bs->can_initialize_object(st)) {
4888 return FAIL;
4889 }
4890 Node* adr = st->in(MemNode::Address);
4891 intptr_t offset;
4892 AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
4893 if (alloc == nullptr)
4894 return FAIL; // inscrutable address
4895 if (alloc != allocation())
4896 return FAIL; // wrong allocation! (store needs to float up)
4897 int size_in_bytes = st->memory_size();
4898 if ((size_in_bytes != 0) && (offset % size_in_bytes) != 0) {
4899 return FAIL; // mismatched access
4900 }
4901 Node* val = st->in(MemNode::ValueIn);
4902
4903 if (!detect_init_independence(val, phase))
4904 return FAIL; // stored value must be 'simple enough'
4905
4906 // The Store can be captured only if nothing after the allocation
4907 // and before the Store is using the memory location that the store
4908 // overwrites.
4909 bool failed = false;
4910 // If is_complete_with_arraycopy() is true the shape of the graph is
4911 // well defined and is safe so no need for extra checks.
4912 if (!is_complete_with_arraycopy()) {
4913 // We are going to look at each use of the memory state following
4914 // the allocation to make sure nothing reads the memory that the
4915 // Store writes.
4916 const TypePtr* t_adr = phase->type(adr)->isa_ptr();
4917 int alias_idx = phase->C->get_alias_index(t_adr);
4918 ResourceMark rm;
4919 Unique_Node_List mems;
4920 mems.push(mem);
4921 Node* unique_merge = nullptr;
4922 for (uint next = 0; next < mems.size(); ++next) {
4923 Node *m = mems.at(next);
4924 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
4925 Node *n = m->fast_out(j);
4926 if (n->outcnt() == 0) {
4927 continue;
4928 }
4929 if (n == st) {
4930 continue;
4931 } else if (n->in(0) != nullptr && n->in(0) != ctl) {
4932 // If the control of this use is different from the control
4933 // of the Store which is right after the InitializeNode then
4934 // this node cannot be between the InitializeNode and the
4935 // Store.
4936 continue;
4937 } else if (n->is_MergeMem()) {
4938 if (n->as_MergeMem()->memory_at(alias_idx) == m) {
4939 // We can hit a MergeMemNode (that will likely go away
4940 // later) that is a direct use of the memory state
4941 // following the InitializeNode on the same slice as the
4942 // store node that we'd like to capture. We need to check
4943 // the uses of the MergeMemNode.
4944 mems.push(n);
4945 }
4946 } else if (n->is_Mem()) {
4947 Node* other_adr = n->in(MemNode::Address);
4948 if (other_adr == adr) {
4949 failed = true;
4950 break;
4951 } else {
4952 const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
4953 if (other_t_adr != nullptr) {
4954 int other_alias_idx = phase->C->get_alias_index(other_t_adr);
4955 if (other_alias_idx == alias_idx) {
4956 // A load from the same memory slice as the store right
4957 // after the InitializeNode. We check the control of the
4958 // object/array that is loaded from. If it's the same as
4959 // the store control then we cannot capture the store.
4960 assert(!n->is_Store(), "2 stores to same slice on same control?");
4961 Node* base = other_adr;
4962 assert(base->is_AddP(), "should be addp but is %s", base->Name());
4963 base = base->in(AddPNode::Base);
4964 if (base != nullptr) {
4965 base = base->uncast();
4966 if (base->is_Proj() && base->in(0) == alloc) {
4967 failed = true;
4968 break;
4969 }
4970 }
4971 }
4972 }
4973 }
4974 } else {
4975 failed = true;
4976 break;
4977 }
4978 }
4979 }
4980 }
4981 if (failed) {
4982 if (!can_reshape) {
4983 // We decided we couldn't capture the store during parsing. We
4984 // should try again during the next IGVN once the graph is
4985 // cleaner.
4986 phase->C->record_for_igvn(st);
4987 }
4988 return FAIL;
4989 }
4990
4991 return offset; // success
4992 }
4993
4994 // Find the captured store in(i) which corresponds to the range
4995 // [start..start+size) in the initialized object.
4996 // If there is one, return its index i. If there isn't, return the
4997 // negative of the index where it should be inserted.
4998 // Return 0 if the queried range overlaps an initialization boundary
4999 // or if dead code is encountered.
5000 // If size_in_bytes is zero, do not bother with overlap checks.
5001 int InitializeNode::captured_store_insertion_point(intptr_t start,
5002 int size_in_bytes,
5003 PhaseValues* phase) {
5004 const int FAIL = 0, MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize);
5005
5006 if (is_complete())
5007 return FAIL; // arraycopy got here first; punt
5008
5009 assert(allocation() != nullptr, "must be present");
5010
5011 // no negatives, no header fields:
5012 if (start < (intptr_t) allocation()->minimum_header_size()) return FAIL;
5013
5014 // after a certain size, we bail out on tracking all the stores:
5015 intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
5016 if (start >= ti_limit) return FAIL;
5017
5018 for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
5019 if (i >= limit) return -(int)i; // not found; here is where to put it
5020
5021 Node* st = in(i);
5022 intptr_t st_off = get_store_offset(st, phase);
5023 if (st_off < 0) {
5024 if (st != zero_memory()) {
5025 return FAIL; // bail out if there is dead garbage
5026 }
5027 } else if (st_off > start) {
5028 // ...we are done, since stores are ordered
5029 if (st_off < start + size_in_bytes) {
5030 return FAIL; // the next store overlaps
5031 }
5032 return -(int)i; // not found; here is where to put it
5033 } else if (st_off < start) {
5034 assert(st->as_Store()->memory_size() <= MAX_STORE, "");
5035 if (size_in_bytes != 0 &&
5036 start < st_off + MAX_STORE &&
5037 start < st_off + st->as_Store()->memory_size()) {
5038 return FAIL; // the previous store overlaps
5039 }
5040 } else {
5041 if (size_in_bytes != 0 &&
5042 st->as_Store()->memory_size() != size_in_bytes) {
5043 return FAIL; // mismatched store size
5044 }
5045 return i;
5046 }
5047
5048 ++i;
5049 }
5050 }
5051
5052 // Look for a captured store which initializes at the offset 'start'
5053 // with the given size. If there is no such store, and no other
5054 // initialization interferes, then return zero_memory (the memory
5055 // projection of the AllocateNode).
5056 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
5057 PhaseValues* phase) {
5058 assert(stores_are_sane(phase), "");
5059 int i = captured_store_insertion_point(start, size_in_bytes, phase);
5060 if (i == 0) {
5061 return nullptr; // something is dead
5062 } else if (i < 0) {
5063 return zero_memory(); // just primordial zero bits here
5064 } else {
5065 Node* st = in(i); // here is the store at this position
5066 assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
5067 return st;
5068 }
5069 }
5070
5071 // Create, as a raw pointer, an address within my new object at 'offset'.
5072 Node* InitializeNode::make_raw_address(intptr_t offset,
5073 PhaseGVN* phase) {
5074 Node* addr = in(RawAddress);
5075 if (offset != 0) {
5076 Compile* C = phase->C;
5077 addr = phase->transform(AddPNode::make_off_heap(addr, phase->MakeConX(offset)));
5078 }
5079 return addr;
5080 }
5081
5082 // Clone the given store, converting it into a raw store
5083 // initializing a field or element of my new object.
5084 // Caller is responsible for retiring the original store,
5085 // with subsume_node or the like.
5086 //
5087 // From the example above InitializeNode::InitializeNode,
5088 // here are the old stores to be captured:
5089 // store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
5090 // store2 = (StoreC init.Control store1 (+ oop 14) 2)
5091 //
5092 // Here is the changed code; note the extra edges on init:
5093 // alloc = (Allocate ...)
5094 // rawoop = alloc.RawAddress
5095 // rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
5096 // rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
5097 // init = (Initialize alloc.Control alloc.Memory rawoop
5098 // rawstore1 rawstore2)
5099 //
5100 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
5101 PhaseGVN* phase, bool can_reshape) {
5102 assert(stores_are_sane(phase), "");
5103
5104 if (start < 0) return nullptr;
5105 assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
5106
5107 Compile* C = phase->C;
5108 int size_in_bytes = st->memory_size();
5109 int i = captured_store_insertion_point(start, size_in_bytes, phase);
5110 if (i == 0) return nullptr; // bail out
5111 Node* prev_mem = nullptr; // raw memory for the captured store
5112 if (i > 0) {
5113 prev_mem = in(i); // there is a pre-existing store under this one
5114 set_req(i, C->top()); // temporarily disconnect it
5115 // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
5116 } else {
5117 i = -i; // no pre-existing store
5118 prev_mem = zero_memory(); // a slice of the newly allocated object
5119 if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
5120 set_req(--i, C->top()); // reuse this edge; it has been folded away
5121 else
5122 ins_req(i, C->top()); // build a new edge
5123 }
5124 Node* new_st = st->clone_with_adr_type(TypeRawPtr::BOTTOM);
5125 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5126 new_st->set_req(MemNode::Control, in(Control));
5127 new_st->set_req(MemNode::Memory, prev_mem);
5128 new_st->set_req(MemNode::Address, make_raw_address(start, phase));
5129 bs->eliminate_gc_barrier_data(new_st);
5130 new_st = phase->transform(new_st);
5131
5132 // At this point, new_st might have swallowed a pre-existing store
5133 // at the same offset, or perhaps new_st might have disappeared,
5134 // if it redundantly stored the same value (or zero to fresh memory).
5135
5136 // In any case, wire it in:
5137 PhaseIterGVN* igvn = phase->is_IterGVN();
5138 if (igvn) {
5139 igvn->rehash_node_delayed(this);
5140 }
5141 set_req(i, new_st);
5142
5143 // The caller may now kill the old guy.
5144 DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
5145 assert(check_st == new_st || check_st == nullptr, "must be findable");
5146 assert(!is_complete(), "");
5147 return new_st;
5148 }
5149
5150 static bool store_constant(jlong* tiles, int num_tiles,
5151 intptr_t st_off, int st_size,
5152 jlong con) {
5153 if ((st_off & (st_size-1)) != 0)
5154 return false; // strange store offset (assume size==2**N)
5155 address addr = (address)tiles + st_off;
5156 assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
5157 switch (st_size) {
5158 case sizeof(jbyte): *(jbyte*) addr = (jbyte) con; break;
5159 case sizeof(jchar): *(jchar*) addr = (jchar) con; break;
5160 case sizeof(jint): *(jint*) addr = (jint) con; break;
5161 case sizeof(jlong): *(jlong*) addr = (jlong) con; break;
5162 default: return false; // strange store size (detect size!=2**N here)
5163 }
5164 return true; // return success to caller
5165 }
5166
5167 // Coalesce subword constants into int constants and possibly
5168 // into long constants. The goal, if the CPU permits,
5169 // is to initialize the object with a small number of 64-bit tiles.
5170 // Also, convert floating-point constants to bit patterns.
5171 // Non-constants are not relevant to this pass.
5172 //
5173 // In terms of the running example on InitializeNode::InitializeNode
5174 // and InitializeNode::capture_store, here is the transformation
5175 // of rawstore1 and rawstore2 into rawstore12:
5176 // alloc = (Allocate ...)
5177 // rawoop = alloc.RawAddress
5178 // tile12 = 0x00010002
5179 // rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
5180 // init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
5181 //
5182 void
5183 InitializeNode::coalesce_subword_stores(intptr_t header_size,
5184 Node* size_in_bytes,
5185 PhaseGVN* phase) {
5186 Compile* C = phase->C;
5187
5188 assert(stores_are_sane(phase), "");
5189 // Note: After this pass, they are not completely sane,
5190 // since there may be some overlaps.
5191
5192 int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
5193
5194 intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
5195 intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
5196 size_limit = MIN2(size_limit, ti_limit);
5197 size_limit = align_up(size_limit, BytesPerLong);
5198 int num_tiles = size_limit / BytesPerLong;
5199
5200 // allocate space for the tile map:
5201 const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
5202 jlong tiles_buf[small_len];
5203 Node* nodes_buf[small_len];
5204 jlong inits_buf[small_len];
5205 jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
5206 : NEW_RESOURCE_ARRAY(jlong, num_tiles));
5207 Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
5208 : NEW_RESOURCE_ARRAY(Node*, num_tiles));
5209 jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
5210 : NEW_RESOURCE_ARRAY(jlong, num_tiles));
5211 // tiles: exact bitwise model of all primitive constants
5212 // nodes: last constant-storing node subsumed into the tiles model
5213 // inits: which bytes (in each tile) are touched by any initializations
5214
5215 //// Pass A: Fill in the tile model with any relevant stores.
5216
5217 Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
5218 Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
5219 Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
5220 Node* zmem = zero_memory(); // initially zero memory state
5221 for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
5222 Node* st = in(i);
5223 intptr_t st_off = get_store_offset(st, phase);
5224
5225 // Figure out the store's offset and constant value:
5226 if (st_off < header_size) continue; //skip (ignore header)
5227 if (st->in(MemNode::Memory) != zmem) continue; //skip (odd store chain)
5228 int st_size = st->as_Store()->memory_size();
5229 if (st_off + st_size > size_limit) break;
5230
5231 // Record which bytes are touched, whether by constant or not.
5232 if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
5233 continue; // skip (strange store size)
5234
5235 const Type* val = phase->type(st->in(MemNode::ValueIn));
5236 if (!val->singleton()) continue; //skip (non-con store)
5237 BasicType type = val->basic_type();
5238
5239 jlong con = 0;
5240 switch (type) {
5241 case T_INT: con = val->is_int()->get_con(); break;
5242 case T_LONG: con = val->is_long()->get_con(); break;
5243 case T_FLOAT: con = jint_cast(val->getf()); break;
5244 case T_DOUBLE: con = jlong_cast(val->getd()); break;
5245 default: continue; //skip (odd store type)
5246 }
5247
5248 if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
5249 st->Opcode() == Op_StoreL) {
5250 continue; // This StoreL is already optimal.
5251 }
5252
5253 // Store down the constant.
5254 store_constant(tiles, num_tiles, st_off, st_size, con);
5255
5256 intptr_t j = st_off >> LogBytesPerLong;
5257
5258 if (type == T_INT && st_size == BytesPerInt
5259 && (st_off & BytesPerInt) == BytesPerInt) {
5260 jlong lcon = tiles[j];
5261 if (!Matcher::isSimpleConstant64(lcon) &&
5262 st->Opcode() == Op_StoreI) {
5263 // This StoreI is already optimal by itself.
5264 jint* intcon = (jint*) &tiles[j];
5265 intcon[1] = 0; // undo the store_constant()
5266
5267 // If the previous store is also optimal by itself, back up and
5268 // undo the action of the previous loop iteration... if we can.
5269 // But if we can't, just let the previous half take care of itself.
5270 st = nodes[j];
5271 st_off -= BytesPerInt;
5272 con = intcon[0];
5273 if (con != 0 && st != nullptr && st->Opcode() == Op_StoreI) {
5274 assert(st_off >= header_size, "still ignoring header");
5275 assert(get_store_offset(st, phase) == st_off, "must be");
5276 assert(in(i-1) == zmem, "must be");
5277 DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
5278 assert(con == tcon->is_int()->get_con(), "must be");
5279 // Undo the effects of the previous loop trip, which swallowed st:
5280 intcon[0] = 0; // undo store_constant()
5281 set_req(i-1, st); // undo set_req(i, zmem)
5282 nodes[j] = nullptr; // undo nodes[j] = st
5283 --old_subword; // undo ++old_subword
5284 }
5285 continue; // This StoreI is already optimal.
5286 }
5287 }
5288
5289 // This store is not needed.
5290 set_req(i, zmem);
5291 nodes[j] = st; // record for the moment
5292 if (st_size < BytesPerLong) // something has changed
5293 ++old_subword; // includes int/float, but who's counting...
5294 else ++old_long;
5295 }
5296
5297 if ((old_subword + old_long) == 0)
5298 return; // nothing more to do
5299
5300 //// Pass B: Convert any non-zero tiles into optimal constant stores.
5301 // Be sure to insert them before overlapping non-constant stores.
5302 // (E.g., byte[] x = { 1,2,y,4 } => x[int 0] = 0x01020004, x[2]=y.)
5303 for (int j = 0; j < num_tiles; j++) {
5304 jlong con = tiles[j];
5305 jlong init = inits[j];
5306 if (con == 0) continue;
5307 jint con0, con1; // split the constant, address-wise
5308 jint init0, init1; // split the init map, address-wise
5309 { union { jlong con; jint intcon[2]; } u;
5310 u.con = con;
5311 con0 = u.intcon[0];
5312 con1 = u.intcon[1];
5313 u.con = init;
5314 init0 = u.intcon[0];
5315 init1 = u.intcon[1];
5316 }
5317
5318 Node* old = nodes[j];
5319 assert(old != nullptr, "need the prior store");
5320 intptr_t offset = (j * BytesPerLong);
5321
5322 bool split = !Matcher::isSimpleConstant64(con);
5323
5324 if (offset < header_size) {
5325 assert(offset + BytesPerInt >= header_size, "second int counts");
5326 assert(*(jint*)&tiles[j] == 0, "junk in header");
5327 split = true; // only the second word counts
5328 // Example: int a[] = { 42 ... }
5329 } else if (con0 == 0 && init0 == -1) {
5330 split = true; // first word is covered by full inits
5331 // Example: int a[] = { ... foo(), 42 ... }
5332 } else if (con1 == 0 && init1 == -1) {
5333 split = true; // second word is covered by full inits
5334 // Example: int a[] = { ... 42, foo() ... }
5335 }
5336
5337 // Here's a case where init0 is neither 0 nor -1:
5338 // byte a[] = { ... 0,0,foo(),0, 0,0,0,42 ... }
5339 // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
5340 // In this case the tile is not split; it is (jlong)42.
5341 // The big tile is stored down, and then the foo() value is inserted.
5342 // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
5343
5344 Node* ctl = old->in(MemNode::Control);
5345 Node* adr = make_raw_address(offset, phase);
5346 const TypePtr* atp = TypeRawPtr::BOTTOM;
5347
5348 // One or two coalesced stores to plop down.
5349 Node* st[2];
5350 intptr_t off[2];
5351 int nst = 0;
5352 if (!split) {
5353 ++new_long;
5354 off[nst] = offset;
5355 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
5356 phase->longcon(con), T_LONG, MemNode::unordered);
5357 } else {
5358 // Omit either if it is a zero.
5359 if (con0 != 0) {
5360 ++new_int;
5361 off[nst] = offset;
5362 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
5363 phase->intcon(con0), T_INT, MemNode::unordered);
5364 }
5365 if (con1 != 0) {
5366 ++new_int;
5367 offset += BytesPerInt;
5368 adr = make_raw_address(offset, phase);
5369 off[nst] = offset;
5370 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
5371 phase->intcon(con1), T_INT, MemNode::unordered);
5372 }
5373 }
5374
5375 // Insert second store first, then the first before the second.
5376 // Insert each one just before any overlapping non-constant stores.
5377 while (nst > 0) {
5378 Node* st1 = st[--nst];
5379 C->copy_node_notes_to(st1, old);
5380 st1 = phase->transform(st1);
5381 offset = off[nst];
5382 assert(offset >= header_size, "do not smash header");
5383 int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
5384 guarantee(ins_idx != 0, "must re-insert constant store");
5385 if (ins_idx < 0) ins_idx = -ins_idx; // never overlap
5386 if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
5387 set_req(--ins_idx, st1);
5388 else
5389 ins_req(ins_idx, st1);
5390 }
5391 }
5392
5393 if (PrintCompilation && WizardMode)
5394 tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
5395 old_subword, old_long, new_int, new_long);
5396 if (C->log() != nullptr)
5397 C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
5398 old_subword, old_long, new_int, new_long);
5399
5400 // Clean up any remaining occurrences of zmem:
5401 remove_extra_zeroes();
5402 }
5403
5404 // Explore forward from in(start) to find the first fully initialized
5405 // word, and return its offset. Skip groups of subword stores which
5406 // together initialize full words. If in(start) is itself part of a
5407 // fully initialized word, return the offset of in(start). If there
5408 // are no following full-word stores, or if something is fishy, return
5409 // a negative value.
5410 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
5411 int int_map = 0;
5412 intptr_t int_map_off = 0;
5413 const int FULL_MAP = right_n_bits(BytesPerInt); // the int_map we hope for
5414
5415 for (uint i = start, limit = req(); i < limit; i++) {
5416 Node* st = in(i);
5417
5418 intptr_t st_off = get_store_offset(st, phase);
5419 if (st_off < 0) break; // return conservative answer
5420
5421 int st_size = st->as_Store()->memory_size();
5422 if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
5423 return st_off; // we found a complete word init
5424 }
5425
5426 // update the map:
5427
5428 intptr_t this_int_off = align_down(st_off, BytesPerInt);
5429 if (this_int_off != int_map_off) {
5430 // reset the map:
5431 int_map = 0;
5432 int_map_off = this_int_off;
5433 }
5434
5435 int subword_off = st_off - this_int_off;
5436 int_map |= right_n_bits(st_size) << subword_off;
5437 if ((int_map & FULL_MAP) == FULL_MAP) {
5438 return this_int_off; // we found a complete word init
5439 }
5440
5441 // Did this store hit or cross the word boundary?
5442 intptr_t next_int_off = align_down(st_off + st_size, BytesPerInt);
5443 if (next_int_off == this_int_off + BytesPerInt) {
5444 // We passed the current int, without fully initializing it.
5445 int_map_off = next_int_off;
5446 int_map >>= BytesPerInt;
5447 } else if (next_int_off > this_int_off + BytesPerInt) {
5448 // We passed the current and next int.
5449 return this_int_off + BytesPerInt;
5450 }
5451 }
5452
5453 return -1;
5454 }
5455
5456
5457 // Called when the associated AllocateNode is expanded into CFG.
5458 // At this point, we may perform additional optimizations.
5459 // Linearize the stores by ascending offset, to make memory
5460 // activity as coherent as possible.
5461 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
5462 intptr_t header_size,
5463 Node* size_in_bytes,
5464 PhaseIterGVN* phase) {
5465 assert(!is_complete(), "not already complete");
5466 assert(stores_are_sane(phase), "");
5467 assert(allocation() != nullptr, "must be present");
5468
5469 remove_extra_zeroes();
5470
5471 if (ReduceFieldZeroing || ReduceBulkZeroing)
5472 // reduce instruction count for common initialization patterns
5473 coalesce_subword_stores(header_size, size_in_bytes, phase);
5474
5475 Node* zmem = zero_memory(); // initially zero memory state
5476 Node* inits = zmem; // accumulating a linearized chain of inits
5477 #ifdef ASSERT
5478 intptr_t first_offset = allocation()->minimum_header_size();
5479 intptr_t last_init_off = first_offset; // previous init offset
5480 intptr_t last_init_end = first_offset; // previous init offset+size
5481 intptr_t last_tile_end = first_offset; // previous tile offset+size
5482 #endif
5483 intptr_t zeroes_done = header_size;
5484
5485 bool do_zeroing = true; // we might give up if inits are very sparse
5486 int big_init_gaps = 0; // how many large gaps have we seen?
5487
5488 if (UseTLAB && ZeroTLAB) do_zeroing = false;
5489 if (!ReduceFieldZeroing && !ReduceBulkZeroing) do_zeroing = false;
5490
5491 for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
5492 Node* st = in(i);
5493 intptr_t st_off = get_store_offset(st, phase);
5494 if (st_off < 0)
5495 break; // unknown junk in the inits
5496 if (st->in(MemNode::Memory) != zmem)
5497 break; // complicated store chains somehow in list
5498
5499 int st_size = st->as_Store()->memory_size();
5500 intptr_t next_init_off = st_off + st_size;
5501
5502 if (do_zeroing && zeroes_done < next_init_off) {
5503 // See if this store needs a zero before it or under it.
5504 intptr_t zeroes_needed = st_off;
5505
5506 if (st_size < BytesPerInt) {
5507 // Look for subword stores which only partially initialize words.
5508 // If we find some, we must lay down some word-level zeroes first,
5509 // underneath the subword stores.
5510 //
5511 // Examples:
5512 // byte[] a = { p,q,r,s } => a[0]=p,a[1]=q,a[2]=r,a[3]=s
5513 // byte[] a = { x,y,0,0 } => a[0..3] = 0, a[0]=x,a[1]=y
5514 // byte[] a = { 0,0,z,0 } => a[0..3] = 0, a[2]=z
5515 //
5516 // Note: coalesce_subword_stores may have already done this,
5517 // if it was prompted by constant non-zero subword initializers.
5518 // But this case can still arise with non-constant stores.
5519
5520 intptr_t next_full_store = find_next_fullword_store(i, phase);
5521
5522 // In the examples above:
5523 // in(i) p q r s x y z
5524 // st_off 12 13 14 15 12 13 14
5525 // st_size 1 1 1 1 1 1 1
5526 // next_full_s. 12 16 16 16 16 16 16
5527 // z's_done 12 16 16 16 12 16 12
5528 // z's_needed 12 16 16 16 16 16 16
5529 // zsize 0 0 0 0 4 0 4
5530 if (next_full_store < 0) {
5531 // Conservative tack: Zero to end of current word.
5532 zeroes_needed = align_up(zeroes_needed, BytesPerInt);
5533 } else {
5534 // Zero to beginning of next fully initialized word.
5535 // Or, don't zero at all, if we are already in that word.
5536 assert(next_full_store >= zeroes_needed, "must go forward");
5537 assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
5538 zeroes_needed = next_full_store;
5539 }
5540 }
5541
5542 if (zeroes_needed > zeroes_done) {
5543 intptr_t zsize = zeroes_needed - zeroes_done;
5544 // Do some incremental zeroing on rawmem, in parallel with inits.
5545 zeroes_done = align_down(zeroes_done, BytesPerInt);
5546 rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
5547 zeroes_done, zeroes_needed,
5548 true,
5549 phase);
5550 zeroes_done = zeroes_needed;
5551 if (zsize > InitArrayShortSize && ++big_init_gaps > 2)
5552 do_zeroing = false; // leave the hole, next time
5553 }
5554 }
5555
5556 // Collect the store and move on:
5557 phase->replace_input_of(st, MemNode::Memory, inits);
5558 inits = st; // put it on the linearized chain
5559 set_req(i, zmem); // unhook from previous position
5560
5561 if (zeroes_done == st_off)
5562 zeroes_done = next_init_off;
5563
5564 assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
5565
5566 #ifdef ASSERT
5567 // Various order invariants. Weaker than stores_are_sane because
5568 // a large constant tile can be filled in by smaller non-constant stores.
5569 assert(st_off >= last_init_off, "inits do not reverse");
5570 last_init_off = st_off;
5571 const Type* val = nullptr;
5572 if (st_size >= BytesPerInt &&
5573 (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
5574 (int)val->basic_type() < (int)T_OBJECT) {
5575 assert(st_off >= last_tile_end, "tiles do not overlap");
5576 assert(st_off >= last_init_end, "tiles do not overwrite inits");
5577 last_tile_end = MAX2(last_tile_end, next_init_off);
5578 } else {
5579 intptr_t st_tile_end = align_up(next_init_off, BytesPerLong);
5580 assert(st_tile_end >= last_tile_end, "inits stay with tiles");
5581 assert(st_off >= last_init_end, "inits do not overlap");
5582 last_init_end = next_init_off; // it's a non-tile
5583 }
5584 #endif //ASSERT
5585 }
5586
5587 remove_extra_zeroes(); // clear out all the zmems left over
5588 add_req(inits);
5589
5590 if (!(UseTLAB && ZeroTLAB)) {
5591 // If anything remains to be zeroed, zero it all now.
5592 zeroes_done = align_down(zeroes_done, BytesPerInt);
5593 // if it is the last unused 4 bytes of an instance, forget about it
5594 intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
5595 if (zeroes_done + BytesPerLong >= size_limit) {
5596 AllocateNode* alloc = allocation();
5597 assert(alloc != nullptr, "must be present");
5598 if (alloc != nullptr && alloc->Opcode() == Op_Allocate) {
5599 Node* klass_node = alloc->in(AllocateNode::KlassNode);
5600 ciKlass* k = phase->type(klass_node)->is_instklassptr()->instance_klass();
5601 if (zeroes_done == k->layout_helper())
5602 zeroes_done = size_limit;
5603 }
5604 }
5605 if (zeroes_done < size_limit) {
5606 rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
5607 zeroes_done, size_in_bytes, true, phase);
5608 }
5609 }
5610
5611 set_complete(phase);
5612 return rawmem;
5613 }
5614
5615 void InitializeNode::replace_mem_projs_by(Node* mem, Compile* C) {
5616 auto replace_proj = [&](ProjNode* proj) {
5617 C->gvn_replace_by(proj, mem);
5618 return CONTINUE;
5619 };
5620 apply_to_projs(replace_proj, TypeFunc::Memory);
5621 }
5622
5623 void InitializeNode::replace_mem_projs_by(Node* mem, PhaseIterGVN* igvn) {
5624 DUIterator_Fast imax, i = fast_outs(imax);
5625 auto replace_proj = [&](ProjNode* proj) {
5626 igvn->replace_node(proj, mem);
5627 --i; --imax;
5628 return CONTINUE;
5629 };
5630 apply_to_projs(imax, i, replace_proj, TypeFunc::Memory);
5631 }
5632
5633 bool InitializeNode::already_has_narrow_mem_proj_with_adr_type(const TypePtr* adr_type) const {
5634 auto find_proj = [&](ProjNode* proj) {
5635 if (proj->adr_type() == adr_type) {
5636 return BREAK_AND_RETURN_CURRENT_PROJ;
5637 }
5638 return CONTINUE;
5639 };
5640 DUIterator_Fast imax, i = fast_outs(imax);
5641 return apply_to_narrow_mem_projs_any_iterator(UsesIteratorFast(imax, i, this), find_proj) != nullptr;
5642 }
5643
5644 MachProjNode* InitializeNode::mem_mach_proj() const {
5645 auto find_proj = [](ProjNode* proj) {
5646 if (proj->is_MachProj()) {
5647 return BREAK_AND_RETURN_CURRENT_PROJ;
5648 }
5649 return CONTINUE;
5650 };
5651 ProjNode* proj = apply_to_projs(find_proj, TypeFunc::Memory);
5652 if (proj == nullptr) {
5653 return nullptr;
5654 }
5655 return proj->as_MachProj();
5656 }
5657
5658 #ifdef ASSERT
5659 bool InitializeNode::stores_are_sane(PhaseValues* phase) {
5660 if (is_complete())
5661 return true; // stores could be anything at this point
5662 assert(allocation() != nullptr, "must be present");
5663 intptr_t last_off = allocation()->minimum_header_size();
5664 for (uint i = InitializeNode::RawStores; i < req(); i++) {
5665 Node* st = in(i);
5666 intptr_t st_off = get_store_offset(st, phase);
5667 if (st_off < 0) continue; // ignore dead garbage
5668 if (last_off > st_off) {
5669 tty->print_cr("*** bad store offset at %d: %zd > %zd", i, last_off, st_off);
5670 this->dump(2);
5671 assert(false, "ascending store offsets");
5672 return false;
5673 }
5674 last_off = st_off + st->as_Store()->memory_size();
5675 }
5676 return true;
5677 }
5678 #endif //ASSERT
5679
5680
5681
5682
5683 //============================MergeMemNode=====================================
5684 //
5685 // SEMANTICS OF MEMORY MERGES: A MergeMem is a memory state assembled from several
5686 // contributing store or call operations. Each contributor provides the memory
5687 // state for a particular "alias type" (see Compile::alias_type). For example,
5688 // if a MergeMem has an input X for alias category #6, then any memory reference
5689 // to alias category #6 may use X as its memory state input, as an exact equivalent
5690 // to using the MergeMem as a whole.
5691 // Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
5692 //
5693 // (Here, the <N> notation gives the index of the relevant adr_type.)
5694 //
5695 // In one special case (and more cases in the future), alias categories overlap.
5696 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
5697 // states. Therefore, if a MergeMem has only one contributing input W for Bot,
5698 // it is exactly equivalent to that state W:
5699 // MergeMem(<Bot>: W) <==> W
5700 //
5701 // Usually, the merge has more than one input. In that case, where inputs
5702 // overlap (i.e., one is Bot), the narrower alias type determines the memory
5703 // state for that type, and the wider alias type (Bot) fills in everywhere else:
5704 // Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
5705 // Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
5706 //
5707 // A merge can take a "wide" memory state as one of its narrow inputs.
5708 // This simply means that the merge observes out only the relevant parts of
5709 // the wide input. That is, wide memory states arriving at narrow merge inputs
5710 // are implicitly "filtered" or "sliced" as necessary. (This is rare.)
5711 //
5712 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
5713 // and that memory slices "leak through":
5714 // MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
5715 //
5716 // But, in such a cascade, repeated memory slices can "block the leak":
5717 // MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
5718 //
5719 // In the last example, Y is not part of the combined memory state of the
5720 // outermost MergeMem. The system must, of course, prevent unschedulable
5721 // memory states from arising, so you can be sure that the state Y is somehow
5722 // a precursor to state Y'.
5723 //
5724 //
5725 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
5726 // of each MergeMemNode array are exactly the numerical alias indexes, including
5727 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw. The functions
5728 // Compile::alias_type (and kin) produce and manage these indexes.
5729 //
5730 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
5731 // (Note that this provides quick access to the top node inside MergeMem methods,
5732 // without the need to reach out via TLS to Compile::current.)
5733 //
5734 // As a consequence of what was just described, a MergeMem that represents a full
5735 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
5736 // containing all alias categories.
5737 //
5738 // MergeMem nodes never (?) have control inputs, so in(0) is null.
5739 //
5740 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
5741 // a memory state for the alias type <N>, or else the top node, meaning that
5742 // there is no particular input for that alias type. Note that the length of
5743 // a MergeMem is variable, and may be extended at any time to accommodate new
5744 // memory states at larger alias indexes. When merges grow, they are of course
5745 // filled with "top" in the unused in() positions.
5746 //
5747 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
5748 // (Top was chosen because it works smoothly with passes like GCM.)
5749 //
5750 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM. (It is
5751 // the type of random VM bits like TLS references.) Since it is always the
5752 // first non-Bot memory slice, some low-level loops use it to initialize an
5753 // index variable: for (i = AliasIdxRaw; i < req(); i++).
5754 //
5755 //
5756 // ACCESSORS: There is a special accessor MergeMemNode::base_memory which returns
5757 // the distinguished "wide" state. The accessor MergeMemNode::memory_at(N) returns
5758 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
5759 // it returns the base memory. To prevent bugs, memory_at does not accept <Top>
5760 // or <Bot> indexes. The iterator MergeMemStream provides robust iteration over
5761 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
5762 //
5763 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
5764 // really that different from the other memory inputs. An abbreviation called
5765 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
5766 //
5767 //
5768 // PARTIAL MEMORY STATES: During optimization, MergeMem nodes may arise that represent
5769 // partial memory states. When a Phi splits through a MergeMem, the copy of the Phi
5770 // that "emerges though" the base memory will be marked as excluding the alias types
5771 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
5772 //
5773 // Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
5774 // ==Ideal=> MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
5775 //
5776 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
5777 // (It is currently unimplemented.) As you can see, the resulting merge is
5778 // actually a disjoint union of memory states, rather than an overlay.
5779 //
5780
5781 //------------------------------MergeMemNode-----------------------------------
5782 Node* MergeMemNode::make_empty_memory() {
5783 Node* empty_memory = (Node*) Compile::current()->top();
5784 assert(empty_memory->is_top(), "correct sentinel identity");
5785 return empty_memory;
5786 }
5787
5788 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
5789 init_class_id(Class_MergeMem);
5790 // all inputs are nullified in Node::Node(int)
5791 // set_input(0, nullptr); // no control input
5792
5793 // Initialize the edges uniformly to top, for starters.
5794 Node* empty_mem = make_empty_memory();
5795 for (uint i = Compile::AliasIdxTop; i < req(); i++) {
5796 init_req(i,empty_mem);
5797 }
5798 assert(empty_memory() == empty_mem, "");
5799
5800 if( new_base != nullptr && new_base->is_MergeMem() ) {
5801 MergeMemNode* mdef = new_base->as_MergeMem();
5802 assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
5803 for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
5804 mms.set_memory(mms.memory2());
5805 }
5806 assert(base_memory() == mdef->base_memory(), "");
5807 } else {
5808 set_base_memory(new_base);
5809 }
5810 }
5811
5812 // Make a new, untransformed MergeMem with the same base as 'mem'.
5813 // If mem is itself a MergeMem, populate the result with the same edges.
5814 MergeMemNode* MergeMemNode::make(Node* mem) {
5815 return new MergeMemNode(mem);
5816 }
5817
5818 //------------------------------cmp--------------------------------------------
5819 uint MergeMemNode::hash() const { return NO_HASH; }
5820 bool MergeMemNode::cmp( const Node &n ) const {
5821 return (&n == this); // Always fail except on self
5822 }
5823
5824 //------------------------------Identity---------------------------------------
5825 Node* MergeMemNode::Identity(PhaseGVN* phase) {
5826 // Identity if this merge point does not record any interesting memory
5827 // disambiguations.
5828 Node* base_mem = base_memory();
5829 Node* empty_mem = empty_memory();
5830 if (base_mem != empty_mem) { // Memory path is not dead?
5831 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
5832 Node* mem = in(i);
5833 if (mem != empty_mem && mem != base_mem) {
5834 return this; // Many memory splits; no change
5835 }
5836 }
5837 }
5838 return base_mem; // No memory splits; ID on the one true input
5839 }
5840
5841 //------------------------------Ideal------------------------------------------
5842 // This method is invoked recursively on chains of MergeMem nodes
5843 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
5844 // Remove chain'd MergeMems
5845 //
5846 // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
5847 // relative to the "in(Bot)". Since we are patching both at the same time,
5848 // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
5849 // but rewrite each "in(i)" relative to the new "in(Bot)".
5850 Node *progress = nullptr;
5851
5852
5853 Node* old_base = base_memory();
5854 Node* empty_mem = empty_memory();
5855 if (old_base == empty_mem)
5856 return nullptr; // Dead memory path.
5857
5858 MergeMemNode* old_mbase;
5859 if (old_base != nullptr && old_base->is_MergeMem())
5860 old_mbase = old_base->as_MergeMem();
5861 else
5862 old_mbase = nullptr;
5863 Node* new_base = old_base;
5864
5865 // simplify stacked MergeMems in base memory
5866 if (old_mbase) new_base = old_mbase->base_memory();
5867
5868 // the base memory might contribute new slices beyond my req()
5869 if (old_mbase) grow_to_match(old_mbase);
5870
5871 // Note: We do not call verify_sparse on entry, because inputs
5872 // can normalize to the base_memory via subsume_node or similar
5873 // mechanisms. This method repairs that damage.
5874
5875 assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
5876
5877 // Look at each slice.
5878 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
5879 Node* old_in = in(i);
5880 // calculate the old memory value
5881 Node* old_mem = old_in;
5882 if (old_mem == empty_mem) old_mem = old_base;
5883 assert(old_mem == memory_at(i), "");
5884
5885 // maybe update (reslice) the old memory value
5886
5887 // simplify stacked MergeMems
5888 Node* new_mem = old_mem;
5889 MergeMemNode* old_mmem;
5890 if (old_mem != nullptr && old_mem->is_MergeMem())
5891 old_mmem = old_mem->as_MergeMem();
5892 else
5893 old_mmem = nullptr;
5894 if (old_mmem == this) {
5895 // This can happen if loops break up and safepoints disappear.
5896 // A merge of BotPtr (default) with a RawPtr memory derived from a
5897 // safepoint can be rewritten to a merge of the same BotPtr with
5898 // the BotPtr phi coming into the loop. If that phi disappears
5899 // also, we can end up with a self-loop of the mergemem.
5900 // In general, if loops degenerate and memory effects disappear,
5901 // a mergemem can be left looking at itself. This simply means
5902 // that the mergemem's default should be used, since there is
5903 // no longer any apparent effect on this slice.
5904 // Note: If a memory slice is a MergeMem cycle, it is unreachable
5905 // from start. Update the input to TOP.
5906 new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
5907 }
5908 else if (old_mmem != nullptr) {
5909 new_mem = old_mmem->memory_at(i);
5910 }
5911 // else preceding memory was not a MergeMem
5912
5913 // maybe store down a new value
5914 Node* new_in = new_mem;
5915 if (new_in == new_base) new_in = empty_mem;
5916
5917 if (new_in != old_in) {
5918 // Warning: Do not combine this "if" with the previous "if"
5919 // A memory slice might have be be rewritten even if it is semantically
5920 // unchanged, if the base_memory value has changed.
5921 set_req_X(i, new_in, phase);
5922 progress = this; // Report progress
5923 }
5924 }
5925
5926 if (new_base != old_base) {
5927 set_req_X(Compile::AliasIdxBot, new_base, phase);
5928 // Don't use set_base_memory(new_base), because we need to update du.
5929 assert(base_memory() == new_base, "");
5930 progress = this;
5931 }
5932
5933 if( base_memory() == this ) {
5934 // a self cycle indicates this memory path is dead
5935 set_req(Compile::AliasIdxBot, empty_mem);
5936 }
5937
5938 // Resolve external cycles by calling Ideal on a MergeMem base_memory
5939 // Recursion must occur after the self cycle check above
5940 if( base_memory()->is_MergeMem() ) {
5941 MergeMemNode *new_mbase = base_memory()->as_MergeMem();
5942 Node *m = phase->transform(new_mbase); // Rollup any cycles
5943 if( m != nullptr &&
5944 (m->is_top() ||
5945 (m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem)) ) {
5946 // propagate rollup of dead cycle to self
5947 set_req(Compile::AliasIdxBot, empty_mem);
5948 }
5949 }
5950
5951 if( base_memory() == empty_mem ) {
5952 progress = this;
5953 // Cut inputs during Parse phase only.
5954 // During Optimize phase a dead MergeMem node will be subsumed by Top.
5955 if( !can_reshape ) {
5956 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
5957 if( in(i) != empty_mem ) { set_req(i, empty_mem); }
5958 }
5959 }
5960 }
5961
5962 if( !progress && base_memory()->is_Phi() && can_reshape ) {
5963 // Check if PhiNode::Ideal's "Split phis through memory merges"
5964 // transform should be attempted. Look for this->phi->this cycle.
5965 uint merge_width = req();
5966 if (merge_width > Compile::AliasIdxRaw) {
5967 PhiNode* phi = base_memory()->as_Phi();
5968 for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
5969 if (phi->in(i) == this) {
5970 phase->is_IterGVN()->_worklist.push(phi);
5971 break;
5972 }
5973 }
5974 }
5975 }
5976
5977 assert(progress || verify_sparse(), "please, no dups of base");
5978 return progress;
5979 }
5980
5981 //-------------------------set_base_memory-------------------------------------
5982 void MergeMemNode::set_base_memory(Node *new_base) {
5983 Node* empty_mem = empty_memory();
5984 set_req(Compile::AliasIdxBot, new_base);
5985 assert(memory_at(req()) == new_base, "must set default memory");
5986 // Clear out other occurrences of new_base:
5987 if (new_base != empty_mem) {
5988 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
5989 if (in(i) == new_base) set_req(i, empty_mem);
5990 }
5991 }
5992 }
5993
5994 //------------------------------out_RegMask------------------------------------
5995 const RegMask &MergeMemNode::out_RegMask() const {
5996 return RegMask::EMPTY;
5997 }
5998
5999 //------------------------------dump_spec--------------------------------------
6000 #ifndef PRODUCT
6001 void MergeMemNode::dump_spec(outputStream *st) const {
6002 st->print(" {");
6003 Node* base_mem = base_memory();
6004 for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
6005 Node* mem = (in(i) != nullptr) ? memory_at(i) : base_mem;
6006 if (mem == base_mem) { st->print(" -"); continue; }
6007 st->print( " N%d:", mem->_idx );
6008 Compile::current()->get_adr_type(i)->dump_on(st);
6009 }
6010 st->print(" }");
6011 }
6012 #endif // !PRODUCT
6013
6014
6015 #ifdef ASSERT
6016 static bool might_be_same(Node* a, Node* b) {
6017 if (a == b) return true;
6018 if (!(a->is_Phi() || b->is_Phi())) return false;
6019 // phis shift around during optimization
6020 return true; // pretty stupid...
6021 }
6022
6023 // verify a narrow slice (either incoming or outgoing)
6024 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
6025 if (!VerifyAliases) return; // don't bother to verify unless requested
6026 if (VMError::is_error_reported()) return; // muzzle asserts when debugging an error
6027 if (Node::in_dump()) return; // muzzle asserts when printing
6028 assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
6029 assert(n != nullptr, "");
6030 // Elide intervening MergeMem's
6031 while (n->is_MergeMem()) {
6032 n = n->as_MergeMem()->memory_at(alias_idx);
6033 }
6034 Compile* C = Compile::current();
6035 const TypePtr* n_adr_type = n->adr_type();
6036 if (n == m->empty_memory()) {
6037 // Implicit copy of base_memory()
6038 } else if (n_adr_type != TypePtr::BOTTOM) {
6039 assert(n_adr_type != nullptr, "new memory must have a well-defined adr_type");
6040 assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
6041 } else {
6042 // A few places like make_runtime_call "know" that VM calls are narrow,
6043 // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
6044 bool expected_wide_mem = false;
6045 if (n == m->base_memory()) {
6046 expected_wide_mem = true;
6047 } else if (alias_idx == Compile::AliasIdxRaw ||
6048 n == m->memory_at(Compile::AliasIdxRaw)) {
6049 expected_wide_mem = true;
6050 } else if (!C->alias_type(alias_idx)->is_rewritable()) {
6051 // memory can "leak through" calls on channels that
6052 // are write-once. Allow this also.
6053 expected_wide_mem = true;
6054 }
6055 assert(expected_wide_mem, "expected narrow slice replacement");
6056 }
6057 }
6058 #else // !ASSERT
6059 #define verify_memory_slice(m,i,n) (void)(0) // PRODUCT version is no-op
6060 #endif
6061
6062
6063 //-----------------------------memory_at---------------------------------------
6064 Node* MergeMemNode::memory_at(uint alias_idx) const {
6065 assert(alias_idx >= Compile::AliasIdxRaw ||
6066 (alias_idx == Compile::AliasIdxBot && !Compile::current()->do_aliasing()),
6067 "must avoid base_memory and AliasIdxTop");
6068
6069 // Otherwise, it is a narrow slice.
6070 Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
6071 if (is_empty_memory(n)) {
6072 // the array is sparse; empty slots are the "top" node
6073 n = base_memory();
6074 assert(Node::in_dump()
6075 || n == nullptr || n->bottom_type() == Type::TOP
6076 || n->adr_type() == nullptr // address is TOP
6077 || n->adr_type() == TypePtr::BOTTOM
6078 || n->adr_type() == TypeRawPtr::BOTTOM
6079 || n->is_NarrowMemProj()
6080 || !Compile::current()->do_aliasing(),
6081 "must be a wide memory");
6082 // do_aliasing == false if we are organizing the memory states manually.
6083 // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
6084 } else {
6085 // make sure the stored slice is sane
6086 #ifdef ASSERT
6087 if (VMError::is_error_reported() || Node::in_dump()) {
6088 } else if (might_be_same(n, base_memory())) {
6089 // Give it a pass: It is a mostly harmless repetition of the base.
6090 // This can arise normally from node subsumption during optimization.
6091 } else {
6092 verify_memory_slice(this, alias_idx, n);
6093 }
6094 #endif
6095 }
6096 return n;
6097 }
6098
6099 //---------------------------set_memory_at-------------------------------------
6100 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
6101 verify_memory_slice(this, alias_idx, n);
6102 Node* empty_mem = empty_memory();
6103 if (n == base_memory()) n = empty_mem; // collapse default
6104 uint need_req = alias_idx+1;
6105 if (req() < need_req) {
6106 if (n == empty_mem) return; // already the default, so do not grow me
6107 // grow the sparse array
6108 do {
6109 add_req(empty_mem);
6110 } while (req() < need_req);
6111 }
6112 set_req( alias_idx, n );
6113 }
6114
6115
6116
6117 //--------------------------iteration_setup------------------------------------
6118 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
6119 if (other != nullptr) {
6120 grow_to_match(other);
6121 // invariant: the finite support of mm2 is within mm->req()
6122 #ifdef ASSERT
6123 for (uint i = req(); i < other->req(); i++) {
6124 assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
6125 }
6126 #endif
6127 }
6128 // Replace spurious copies of base_memory by top.
6129 Node* base_mem = base_memory();
6130 if (base_mem != nullptr && !base_mem->is_top()) {
6131 for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
6132 if (in(i) == base_mem)
6133 set_req(i, empty_memory());
6134 }
6135 }
6136 }
6137
6138 //---------------------------grow_to_match-------------------------------------
6139 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
6140 Node* empty_mem = empty_memory();
6141 assert(other->is_empty_memory(empty_mem), "consistent sentinels");
6142 // look for the finite support of the other memory
6143 for (uint i = other->req(); --i >= req(); ) {
6144 if (other->in(i) != empty_mem) {
6145 uint new_len = i+1;
6146 while (req() < new_len) add_req(empty_mem);
6147 break;
6148 }
6149 }
6150 }
6151
6152 //---------------------------verify_sparse-------------------------------------
6153 #ifndef PRODUCT
6154 bool MergeMemNode::verify_sparse() const {
6155 assert(is_empty_memory(make_empty_memory()), "sane sentinel");
6156 Node* base_mem = base_memory();
6157 // The following can happen in degenerate cases, since empty==top.
6158 if (is_empty_memory(base_mem)) return true;
6159 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
6160 assert(in(i) != nullptr, "sane slice");
6161 if (in(i) == base_mem) return false; // should have been the sentinel value!
6162 }
6163 return true;
6164 }
6165
6166 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
6167 Node* n;
6168 n = mm->in(idx);
6169 if (mem == n) return true; // might be empty_memory()
6170 n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
6171 if (mem == n) return true;
6172 return false;
6173 }
6174 #endif // !PRODUCT