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