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