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