1 /*
2 * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "ci/ciFlatArrayKlass.hpp"
26 #include "ci/ciInlineKlass.hpp"
27 #include "ci/ciInstanceKlass.hpp"
28 #include "compiler/compileLog.hpp"
29 #include "gc/shared/collectedHeap.inline.hpp"
30 #include "gc/shared/tlab_globals.hpp"
31 #include "libadt/vectset.hpp"
32 #include "memory/universe.hpp"
33 #include "opto/addnode.hpp"
34 #include "opto/arraycopynode.hpp"
35 #include "opto/callnode.hpp"
36 #include "opto/castnode.hpp"
37 #include "opto/cfgnode.hpp"
38 #include "opto/compile.hpp"
39 #include "opto/convertnode.hpp"
40 #include "opto/graphKit.hpp"
41 #include "opto/inlinetypenode.hpp"
42 #include "opto/intrinsicnode.hpp"
43 #include "opto/locknode.hpp"
44 #include "opto/loopnode.hpp"
45 #include "opto/macro.hpp"
46 #include "opto/memnode.hpp"
47 #include "opto/narrowptrnode.hpp"
48 #include "opto/node.hpp"
49 #include "opto/opaquenode.hpp"
50 #include "opto/opcodes.hpp"
51 #include "opto/phaseX.hpp"
52 #include "opto/rootnode.hpp"
53 #include "opto/runtime.hpp"
54 #include "opto/subnode.hpp"
55 #include "opto/subtypenode.hpp"
56 #include "opto/type.hpp"
57 #include "prims/jvmtiExport.hpp"
58 #include "runtime/continuation.hpp"
59 #include "runtime/sharedRuntime.hpp"
60 #include "runtime/stubRoutines.hpp"
61 #include "utilities/globalDefinitions.hpp"
62 #include "utilities/macros.hpp"
63 #include "utilities/powerOfTwo.hpp"
64 #if INCLUDE_G1GC
65 #include "gc/g1/g1ThreadLocalData.hpp"
66 #endif // INCLUDE_G1GC
67
68
69 //
70 // Replace any references to "oldref" in inputs to "use" with "newref".
71 // Returns the number of replacements made.
72 //
73 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
74 int nreplacements = 0;
75 uint req = use->req();
76 for (uint j = 0; j < use->len(); j++) {
77 Node *uin = use->in(j);
78 if (uin == oldref) {
79 if (j < req)
80 use->set_req(j, newref);
81 else
82 use->set_prec(j, newref);
83 nreplacements++;
84 } else if (j >= req && uin == nullptr) {
85 break;
86 }
87 }
88 return nreplacements;
89 }
90
91
92 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word) {
93 Node* cmp = word;
94 Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
95 IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
96 transform_later(iff);
97
98 // Fast path taken.
99 Node *fast_taken = transform_later(new IfFalseNode(iff));
100
101 // Fast path not-taken, i.e. slow path
102 Node *slow_taken = transform_later(new IfTrueNode(iff));
103
104 region->init_req(edge, fast_taken); // Capture fast-control
105 return slow_taken;
106 }
107
108 //--------------------copy_predefined_input_for_runtime_call--------------------
109 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
110 // Set fixed predefined input arguments
111 call->init_req( TypeFunc::Control, ctrl );
112 call->init_req( TypeFunc::I_O , oldcall->in( TypeFunc::I_O) );
113 call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ?????
114 call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) );
115 call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) );
116 }
117
118 //------------------------------make_slow_call---------------------------------
119 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type,
120 address slow_call, const char* leaf_name, Node* slow_path,
121 Node* parm0, Node* parm1, Node* parm2) {
122
123 // Slow-path call
124 CallNode *call = leaf_name
125 ? (CallNode*)new CallLeafNode ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
126 : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), TypeRawPtr::BOTTOM );
127
128 // Slow path call has no side-effects, uses few values
129 copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
130 if (parm0 != nullptr) call->init_req(TypeFunc::Parms+0, parm0);
131 if (parm1 != nullptr) call->init_req(TypeFunc::Parms+1, parm1);
132 if (parm2 != nullptr) call->init_req(TypeFunc::Parms+2, parm2);
133 call->copy_call_debug_info(&_igvn, oldcall);
134 call->set_cnt(PROB_UNLIKELY_MAG(4)); // Same effect as RC_UNCOMMON.
135 _igvn.replace_node(oldcall, call);
136 transform_later(call);
137
138 return call;
139 }
140
141 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) {
142 BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
143 bs->eliminate_gc_barrier(&_igvn, p2x);
144 #ifndef PRODUCT
145 if (PrintOptoStatistics) {
146 AtomicAccess::inc(&PhaseMacroExpand::_GC_barriers_removed_counter);
147 }
148 #endif
149 }
150
151 // Search for a memory operation for the specified memory slice.
152 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
153 Node *orig_mem = mem;
154 Node *alloc_mem = alloc->as_Allocate()->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
155 assert(alloc_mem != nullptr, "Allocation without a memory projection.");
156 const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
157 while (true) {
158 if (mem == alloc_mem || mem == start_mem ) {
159 return mem; // hit one of our sentinels
160 } else if (mem->is_MergeMem()) {
161 mem = mem->as_MergeMem()->memory_at(alias_idx);
162 } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
163 Node *in = mem->in(0);
164 // we can safely skip over safepoints, calls, locks and membars because we
165 // already know that the object is safe to eliminate.
166 if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
167 return in;
168 } else if (in->is_Call()) {
169 CallNode *call = in->as_Call();
170 if (call->may_modify(tinst, phase)) {
171 assert(call->is_ArrayCopy(), "ArrayCopy is the only call node that doesn't make allocation escape");
172 if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
173 return in;
174 }
175 }
176 mem = in->in(TypeFunc::Memory);
177 } else if (in->is_MemBar()) {
178 ArrayCopyNode* ac = nullptr;
179 if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
180 if (ac != nullptr) {
181 assert(ac->is_clonebasic(), "Only basic clone is a non escaping clone");
182 return ac;
183 }
184 }
185 mem = in->in(TypeFunc::Memory);
186 } else if (in->is_LoadFlat() || in->is_StoreFlat()) {
187 mem = in->in(TypeFunc::Memory);
188 } else {
189 #ifdef ASSERT
190 in->dump();
191 mem->dump();
192 assert(false, "unexpected projection");
193 #endif
194 }
195 } else if (mem->is_Store()) {
196 const TypePtr* atype = mem->as_Store()->adr_type();
197 int adr_idx = phase->C->get_alias_index(atype);
198 if (adr_idx == alias_idx) {
199 assert(atype->isa_oopptr(), "address type must be oopptr");
200 int adr_offset = atype->flat_offset();
201 uint adr_iid = atype->is_oopptr()->instance_id();
202 // Array elements references have the same alias_idx
203 // but different offset and different instance_id.
204 if (adr_offset == offset && adr_iid == alloc->_idx) {
205 return mem;
206 }
207 } else {
208 assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
209 }
210 mem = mem->in(MemNode::Memory);
211 } else if (mem->is_ClearArray()) {
212 if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
213 // Can not bypass initialization of the instance
214 // we are looking.
215 DEBUG_ONLY(intptr_t offset;)
216 assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
217 InitializeNode* init = alloc->as_Allocate()->initialization();
218 // We are looking for stored value, return Initialize node
219 // or memory edge from Allocate node.
220 if (init != nullptr) {
221 return init;
222 } else {
223 return alloc->in(TypeFunc::Memory); // It will produce zero value (see callers).
224 }
225 }
226 // Otherwise skip it (the call updated 'mem' value).
227 } else if (mem->Opcode() == Op_SCMemProj) {
228 mem = mem->in(0);
229 Node* adr = nullptr;
230 if (mem->is_LoadStore()) {
231 adr = mem->in(MemNode::Address);
232 } else {
233 assert(mem->Opcode() == Op_EncodeISOArray ||
234 mem->Opcode() == Op_StrCompressedCopy, "sanity");
235 adr = mem->in(3); // Destination array
236 }
237 const TypePtr* atype = adr->bottom_type()->is_ptr();
238 int adr_idx = phase->C->get_alias_index(atype);
239 if (adr_idx == alias_idx) {
240 DEBUG_ONLY(mem->dump();)
241 assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
242 return nullptr;
243 }
244 mem = mem->in(MemNode::Memory);
245 } else if (mem->Opcode() == Op_StrInflatedCopy) {
246 Node* adr = mem->in(3); // Destination array
247 const TypePtr* atype = adr->bottom_type()->is_ptr();
248 int adr_idx = phase->C->get_alias_index(atype);
249 if (adr_idx == alias_idx) {
250 DEBUG_ONLY(mem->dump();)
251 assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
252 return nullptr;
253 }
254 mem = mem->in(MemNode::Memory);
255 } else {
256 return mem;
257 }
258 assert(mem != orig_mem, "dead memory loop");
259 }
260 }
261
262 // Generate loads from source of the arraycopy for fields of
263 // destination needed at a deoptimization point
264 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
265 BasicType bt = ft;
266 const Type *type = ftype;
267 if (ft == T_NARROWOOP) {
268 bt = T_OBJECT;
269 type = ftype->make_oopptr();
270 }
271 Node* res = nullptr;
272 if (ac->is_clonebasic()) {
273 assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
274 Node* base = ac->in(ArrayCopyNode::Src);
275 Node* adr = _igvn.transform(new AddPNode(base, base, _igvn.MakeConX(offset)));
276 const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
277 MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
278 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
279 res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
280 } else {
281 if (ac->modifies(offset, offset, &_igvn, true)) {
282 assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
283 uint shift = exact_log2(type2aelembytes(bt));
284 Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
285 Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
286 const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
287 const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
288
289 Node* adr = nullptr;
290 Node* base = ac->in(ArrayCopyNode::Src);
291 const TypeAryPtr* adr_type = _igvn.type(base)->is_aryptr();
292 if (adr_type->is_flat()) {
293 shift = adr_type->flat_log_elem_size();
294 }
295 if (src_pos_t->is_con() && dest_pos_t->is_con()) {
296 intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
297 adr = _igvn.transform(new AddPNode(base, base, _igvn.MakeConX(off)));
298 adr_type = _igvn.type(adr)->is_aryptr();
299 assert(adr_type == _igvn.type(base)->is_aryptr()->add_field_offset_and_offset(off), "incorrect address type");
300 if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
301 // Don't emit a new load from src if src == dst but try to get the value from memory instead
302 return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type, alloc);
303 }
304 } else {
305 if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
306 // Non constant offset in the array: we can't statically
307 // determine the value
308 return nullptr;
309 }
310 Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
311 #ifdef _LP64
312 diff = _igvn.transform(new ConvI2LNode(diff));
313 #endif
314 diff = _igvn.transform(new LShiftXNode(diff, _igvn.intcon(shift)));
315
316 Node* off = _igvn.transform(new AddXNode(_igvn.MakeConX(offset), diff));
317 adr = _igvn.transform(new AddPNode(base, base, off));
318 // In the case of a flat inline type array, each field has its
319 // own slice so we need to extract the field being accessed from
320 // the address computation
321 adr_type = adr_type->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot)->is_aryptr();
322 adr = _igvn.transform(new CastPPNode(ctl, adr, adr_type));
323 }
324 MergeMemNode* mergemen = _igvn.transform(MergeMemNode::make(mem))->as_MergeMem();
325 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
326 res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
327 }
328 }
329 if (res != nullptr) {
330 if (ftype->isa_narrowoop()) {
331 // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
332 assert(res->isa_DecodeN(), "should be narrow oop");
333 res = _igvn.transform(new EncodePNode(res, ftype));
334 }
335 return res;
336 }
337 return nullptr;
338 }
339
340 //
341 // Given a Memory Phi, compute a value Phi containing the values from stores
342 // on the input paths.
343 // Note: this function is recursive, its depth is limited by the "level" argument
344 // Returns the computed Phi, or null if it cannot compute it.
345 Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, AllocateNode *alloc, Node_Stack *value_phis, int level) {
346 assert(mem->is_Phi(), "sanity");
347 int alias_idx = C->get_alias_index(adr_t);
348 int offset = adr_t->flat_offset();
349 int instance_id = adr_t->instance_id();
350
351 // Check if an appropriate value phi already exists.
352 Node* region = mem->in(0);
353 for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
354 Node* phi = region->fast_out(k);
355 if (phi->is_Phi() && phi != mem &&
356 phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
357 return phi;
358 }
359 }
360 // Check if an appropriate new value phi already exists.
361 Node* new_phi = value_phis->find(mem->_idx);
362 if (new_phi != nullptr)
363 return new_phi;
364
365 if (level <= 0) {
366 return nullptr; // Give up: phi tree too deep
367 }
368 Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
369 Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
370 assert(alloc_mem != nullptr, "Allocation without a memory projection.");
371
372 uint length = mem->req();
373 GrowableArray <Node *> values(length, length, nullptr);
374
375 // create a new Phi for the value
376 PhiNode *phi = new PhiNode(mem->in(0), phi_type, nullptr, mem->_idx, instance_id, alias_idx, offset);
377 transform_later(phi);
378 value_phis->push(phi, mem->_idx);
379
380 for (uint j = 1; j < length; j++) {
381 Node *in = mem->in(j);
382 if (in == nullptr || in->is_top()) {
383 values.at_put(j, in);
384 } else {
385 Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
386 if (val == start_mem || val == alloc_mem) {
387 // hit a sentinel, return appropriate value
388 Node* init_value = value_from_alloc(ft, adr_t, alloc);
389 if (init_value == nullptr) {
390 return nullptr;
391 } else {
392 values.at_put(j, init_value);
393 continue;
394 }
395 }
396 if (val->is_Initialize()) {
397 val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
398 }
399 if (val == nullptr) {
400 return nullptr; // can't find a value on this path
401 }
402 if (val == mem) {
403 values.at_put(j, mem);
404 } else if (val->is_Store()) {
405 Node* n = val->in(MemNode::ValueIn);
406 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
407 n = bs->step_over_gc_barrier(n);
408 if (is_subword_type(ft)) {
409 n = Compile::narrow_value(ft, n, phi_type, &_igvn, true);
410 }
411 values.at_put(j, n);
412 } else if (val->is_Proj() && val->in(0) == alloc) {
413 Node* init_value = value_from_alloc(ft, adr_t, alloc);
414 if (init_value == nullptr) {
415 return nullptr;
416 } else {
417 values.at_put(j, init_value);
418 }
419 } else if (val->is_Phi()) {
420 val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
421 if (val == nullptr) {
422 return nullptr;
423 }
424 values.at_put(j, val);
425 } else if (val->Opcode() == Op_SCMemProj) {
426 assert(val->in(0)->is_LoadStore() ||
427 val->in(0)->Opcode() == Op_EncodeISOArray ||
428 val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
429 assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
430 return nullptr;
431 } else if (val->is_ArrayCopy()) {
432 Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
433 if (res == nullptr) {
434 return nullptr;
435 }
436 values.at_put(j, res);
437 } else if (val->is_top()) {
438 // This indicates that this path into the phi is dead. Top will eventually also propagate into the Region.
439 // IGVN will clean this up later.
440 values.at_put(j, val);
441 } else {
442 DEBUG_ONLY( val->dump(); )
443 assert(false, "unknown node on this path");
444 return nullptr; // unknown node on this path
445 }
446 }
447 }
448 // Set Phi's inputs
449 for (uint j = 1; j < length; j++) {
450 if (values.at(j) == mem) {
451 phi->init_req(j, phi);
452 } else {
453 phi->init_req(j, values.at(j));
454 }
455 }
456 return phi;
457 }
458
459 // Extract the initial value of a field in an allocation
460 Node* PhaseMacroExpand::value_from_alloc(BasicType ft, const TypeOopPtr* adr_t, AllocateNode* alloc) {
461 Node* init_value = alloc->in(AllocateNode::InitValue);
462 if (init_value == nullptr) {
463 assert(alloc->in(AllocateNode::RawInitValue) == nullptr, "conflicting InitValue and RawInitValue");
464 return _igvn.zerocon(ft);
465 }
466
467 const TypeAryPtr* ary_t = adr_t->isa_aryptr();
468 assert(ary_t != nullptr, "must be a pointer into an array");
469
470 // If this is not a flat array, then it must be an oop array with elements being init_value
471 if (ary_t->is_not_flat()) {
472 #ifdef ASSERT
473 BasicType init_bt = init_value->bottom_type()->basic_type();
474 assert(ft == init_bt ||
475 (!is_java_primitive(ft) && !is_java_primitive(init_bt) && type2aelembytes(ft, true) == type2aelembytes(init_bt, true)) ||
476 (is_subword_type(ft) && init_bt == T_INT),
477 "invalid init_value of type %s for field of type %s", type2name(init_bt), type2name(ft));
478 #endif // ASSERT
479 return init_value;
480 }
481
482 assert(ary_t->klass_is_exact() && ary_t->is_flat(), "must be an exact flat array");
483 assert(ary_t->field_offset().get() != Type::OffsetBot, "unknown offset");
484 if (init_value->is_EncodeP()) {
485 init_value = init_value->in(1);
486 }
487 // Cannot look through init_value if it is an oop
488 if (!init_value->is_InlineType()) {
489 return nullptr;
490 }
491
492 ciInlineKlass* vk = init_value->bottom_type()->inline_klass();
493 if (ary_t->field_offset().get() == vk->null_marker_offset_in_payload()) {
494 init_value = init_value->as_InlineType()->get_null_marker();
495 } else {
496 init_value = init_value->as_InlineType()->field_value_by_offset(ary_t->field_offset().get() + vk->payload_offset(), true);
497 }
498
499 if (ft == T_NARROWOOP) {
500 assert(init_value->bottom_type()->isa_ptr(), "must be a pointer");
501 init_value = transform_later(new EncodePNode(init_value, init_value->bottom_type()->make_narrowoop()));
502 }
503
504 #ifdef ASSERT
505 BasicType init_bt = init_value->bottom_type()->basic_type();
506 assert(ft == init_bt ||
507 (!is_java_primitive(ft) && !is_java_primitive(init_bt) && type2aelembytes(ft, true) == type2aelembytes(init_bt, true)) ||
508 (is_subword_type(ft) && init_bt == T_INT),
509 "invalid init_value of type %s for field of type %s", type2name(init_bt), type2name(ft));
510 #endif // ASSERT
511
512 return init_value;
513 }
514
515 // Search the last value stored into the object's field.
516 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
517 assert(adr_t->is_known_instance_field(), "instance required");
518 int instance_id = adr_t->instance_id();
519 assert((uint)instance_id == alloc->_idx, "wrong allocation");
520
521 int alias_idx = C->get_alias_index(adr_t);
522 int offset = adr_t->flat_offset();
523 Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
524 Node *alloc_mem = alloc->proj_out_or_null(TypeFunc::Memory, /*io_use:*/false);
525 assert(alloc_mem != nullptr, "Allocation without a memory projection.");
526 VectorSet visited;
527
528 bool done = sfpt_mem == alloc_mem;
529 Node *mem = sfpt_mem;
530 while (!done) {
531 if (visited.test_set(mem->_idx)) {
532 return nullptr; // found a loop, give up
533 }
534 mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
535 if (mem == start_mem || mem == alloc_mem) {
536 done = true; // hit a sentinel, return appropriate 0 value
537 } else if (mem->is_Initialize()) {
538 mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
539 if (mem == nullptr) {
540 done = true; // Something went wrong.
541 } else if (mem->is_Store()) {
542 const TypePtr* atype = mem->as_Store()->adr_type();
543 assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
544 done = true;
545 }
546 } else if (mem->is_Store()) {
547 const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
548 assert(atype != nullptr, "address type must be oopptr");
549 assert(C->get_alias_index(atype) == alias_idx &&
550 atype->is_known_instance_field() && atype->flat_offset() == offset &&
551 atype->instance_id() == instance_id, "store is correct memory slice");
552 done = true;
553 } else if (mem->is_Phi()) {
554 // try to find a phi's unique input
555 Node *unique_input = nullptr;
556 Node *top = C->top();
557 for (uint i = 1; i < mem->req(); i++) {
558 Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
559 if (n == nullptr || n == top || n == mem) {
560 continue;
561 } else if (unique_input == nullptr) {
562 unique_input = n;
563 } else if (unique_input != n) {
564 unique_input = top;
565 break;
566 }
567 }
568 if (unique_input != nullptr && unique_input != top) {
569 mem = unique_input;
570 } else {
571 done = true;
572 }
573 } else if (mem->is_ArrayCopy()) {
574 done = true;
575 } else if (mem->is_top()) {
576 // The slice is on a dead path. Returning nullptr would lead to elimination
577 // bailout, but we want to prevent that. Just forwarding the top is also legal,
578 // and IGVN can just clean things up, and remove whatever receives top.
579 return mem;
580 } else {
581 DEBUG_ONLY( mem->dump(); )
582 assert(false, "unexpected node");
583 }
584 }
585 if (mem != nullptr) {
586 if (mem == start_mem || mem == alloc_mem) {
587 // hit a sentinel, return appropriate value
588 return value_from_alloc(ft, adr_t, alloc);
589 } else if (mem->is_Store()) {
590 Node* n = mem->in(MemNode::ValueIn);
591 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
592 n = bs->step_over_gc_barrier(n);
593 return n;
594 } else if (mem->is_Phi()) {
595 // attempt to produce a Phi reflecting the values on the input paths of the Phi
596 Node_Stack value_phis(8);
597 Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
598 if (phi != nullptr) {
599 return phi;
600 } else {
601 // Kill all new Phis
602 while(value_phis.is_nonempty()) {
603 Node* n = value_phis.node();
604 _igvn.replace_node(n, C->top());
605 value_phis.pop();
606 }
607 }
608 } else if (mem->is_ArrayCopy()) {
609 Node* ctl = mem->in(0);
610 Node* m = mem->in(TypeFunc::Memory);
611 if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj()) {
612 // pin the loads in the uncommon trap path
613 ctl = sfpt_ctl;
614 m = sfpt_mem;
615 }
616 return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
617 }
618 }
619 // Something went wrong.
620 return nullptr;
621 }
622
623 // Search the last value stored into the inline type's fields (for flat arrays).
624 Node* PhaseMacroExpand::inline_type_from_mem(ciInlineKlass* vk, const TypeAryPtr* elem_adr_type, int elem_idx, int offset_in_element, bool null_free, AllocateNode* alloc, SafePointNode* sfpt) {
625 auto report_failure = [&](int field_offset_in_element) {
626 #ifndef PRODUCT
627 if (PrintEliminateAllocations) {
628 ciInlineKlass* elem_klass = elem_adr_type->elem()->inline_klass();
629 int offset = field_offset_in_element + elem_klass->payload_offset();
630 ciField* flattened_field = elem_klass->get_field_by_offset(offset, false);
631 assert(flattened_field != nullptr, "must have a field of type %s at offset %d", elem_klass->name()->as_utf8(), offset);
632 tty->print("=== At SafePoint node %d can't find value of field [%s] of array element [%d]", sfpt->_idx, flattened_field->name()->as_utf8(), elem_idx);
633 tty->print(", which prevents elimination of: ");
634 alloc->dump();
635 }
636 #endif // PRODUCT
637 };
638
639 // Create a new InlineTypeNode and retrieve the field values from memory
640 InlineTypeNode* vt = InlineTypeNode::make_uninitialized(_igvn, vk, false);
641 transform_later(vt);
642 if (null_free) {
643 vt->set_null_marker(_igvn);
644 } else {
645 int nm_offset_in_element = offset_in_element + vk->null_marker_offset_in_payload();
646 const TypeAryPtr* nm_adr_type = elem_adr_type->with_field_offset(nm_offset_in_element);
647 Node* nm_value = value_from_mem(sfpt->memory(), sfpt->control(), T_BOOLEAN, TypeInt::BOOL, nm_adr_type, alloc);
648 if (nm_value != nullptr) {
649 vt->set_null_marker(_igvn, nm_value);
650 } else {
651 report_failure(nm_offset_in_element);
652 return nullptr;
653 }
654 }
655
656 for (int i = 0; i < vk->nof_declared_nonstatic_fields(); ++i) {
657 ciType* field_type = vt->field_type(i);
658 int field_offset_in_element = offset_in_element + vt->field_offset(i) - vk->payload_offset();
659 Node* field_value = nullptr;
660 if (vt->field_is_flat(i)) {
661 field_value = inline_type_from_mem(field_type->as_inline_klass(), elem_adr_type, elem_idx, field_offset_in_element, vt->field_is_null_free(i), alloc, sfpt);
662 } else {
663 const Type* ft = Type::get_const_type(field_type);
664 BasicType bt = type2field[field_type->basic_type()];
665 if (UseCompressedOops && !is_java_primitive(bt)) {
666 ft = ft->make_narrowoop();
667 bt = T_NARROWOOP;
668 }
669 // Each inline type field has its own memory slice
670 const TypeAryPtr* field_adr_type = elem_adr_type->with_field_offset(field_offset_in_element);
671 field_value = value_from_mem(sfpt->memory(), sfpt->control(), bt, ft, field_adr_type, alloc);
672 if (field_value == nullptr) {
673 report_failure(field_offset_in_element);
674 } else if (ft->isa_narrowoop()) {
675 assert(UseCompressedOops, "unexpected narrow oop");
676 if (field_value->is_EncodeP()) {
677 field_value = field_value->in(1);
678 } else if (!field_value->is_InlineType()) {
679 field_value = transform_later(new DecodeNNode(field_value, field_value->get_ptr_type()));
680 }
681 }
682 }
683 if (field_value != nullptr) {
684 vt->set_field_value(i, field_value);
685 } else {
686 return nullptr;
687 }
688 }
689 return vt;
690 }
691
692 // Check the possibility of scalar replacement.
693 bool PhaseMacroExpand::can_eliminate_allocation(PhaseIterGVN* igvn, AllocateNode *alloc, GrowableArray <SafePointNode *>* safepoints) {
694 // Scan the uses of the allocation to check for anything that would
695 // prevent us from eliminating it.
696 NOT_PRODUCT( const char* fail_eliminate = nullptr; )
697 DEBUG_ONLY( Node* disq_node = nullptr; )
698 bool can_eliminate = true;
699 bool reduce_merge_precheck = (safepoints == nullptr);
700
701 Unique_Node_List worklist;
702 Node* res = alloc->result_cast();
703 const TypeOopPtr* res_type = nullptr;
704 if (res == nullptr) {
705 // All users were eliminated.
706 } else if (!res->is_CheckCastPP()) {
707 NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
708 can_eliminate = false;
709 } else {
710 worklist.push(res);
711 res_type = igvn->type(res)->isa_oopptr();
712 if (res_type == nullptr) {
713 NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
714 can_eliminate = false;
715 } else if (!res_type->klass_is_exact()) {
716 NOT_PRODUCT(fail_eliminate = "Not an exact type.";)
717 can_eliminate = false;
718 } else if (res_type->isa_aryptr()) {
719 int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
720 if (length < 0) {
721 NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
722 can_eliminate = false;
723 }
724 }
725 }
726
727 while (can_eliminate && worklist.size() > 0) {
728 BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
729 res = worklist.pop();
730 for (DUIterator_Fast jmax, j = res->fast_outs(jmax); j < jmax && can_eliminate; j++) {
731 Node* use = res->fast_out(j);
732
733 if (use->is_AddP()) {
734 const TypePtr* addp_type = igvn->type(use)->is_ptr();
735 int offset = addp_type->offset();
736
737 if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
738 NOT_PRODUCT(fail_eliminate = "Undefined field reference";)
739 can_eliminate = false;
740 break;
741 }
742 for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
743 k < kmax && can_eliminate; k++) {
744 Node* n = use->fast_out(k);
745 if ((n->is_Mem() && n->as_Mem()->is_mismatched_access()) || n->is_LoadFlat() || n->is_StoreFlat()) {
746 DEBUG_ONLY(disq_node = n);
747 NOT_PRODUCT(fail_eliminate = "Mismatched access");
748 can_eliminate = false;
749 }
750 if (!n->is_Store() && n->Opcode() != Op_CastP2X && !bs->is_gc_pre_barrier_node(n) && !reduce_merge_precheck) {
751 DEBUG_ONLY(disq_node = n;)
752 if (n->is_Load() || n->is_LoadStore()) {
753 NOT_PRODUCT(fail_eliminate = "Field load";)
754 } else {
755 NOT_PRODUCT(fail_eliminate = "Not store field reference";)
756 }
757 can_eliminate = false;
758 }
759 }
760 } else if (use->is_ArrayCopy() &&
761 (use->as_ArrayCopy()->is_clonebasic() ||
762 use->as_ArrayCopy()->is_arraycopy_validated() ||
763 use->as_ArrayCopy()->is_copyof_validated() ||
764 use->as_ArrayCopy()->is_copyofrange_validated()) &&
765 use->in(ArrayCopyNode::Dest) == res) {
766 // ok to eliminate
767 } else if (use->is_SafePoint()) {
768 SafePointNode* sfpt = use->as_SafePoint();
769 if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
770 // Object is passed as argument.
771 DEBUG_ONLY(disq_node = use;)
772 NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
773 can_eliminate = false;
774 }
775 Node* sfptMem = sfpt->memory();
776 if (sfptMem == nullptr || sfptMem->is_top()) {
777 DEBUG_ONLY(disq_node = use;)
778 NOT_PRODUCT(fail_eliminate = "null or TOP memory";)
779 can_eliminate = false;
780 } else if (!reduce_merge_precheck) {
781 assert(!res->is_Phi() || !res->as_Phi()->can_be_inline_type(), "Inline type allocations should not have safepoint uses");
782 safepoints->append_if_missing(sfpt);
783 }
784 } else if (use->is_InlineType() && use->as_InlineType()->get_oop() == res) {
785 // Look at uses
786 for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) {
787 Node* u = use->fast_out(k);
788 if (u->is_InlineType()) {
789 // Use in flat field can be eliminated
790 InlineTypeNode* vt = u->as_InlineType();
791 for (uint i = 0; i < vt->field_count(); ++i) {
792 if (vt->field_value(i) == use && !vt->field_is_flat(i)) {
793 can_eliminate = false; // Use in non-flat field
794 break;
795 }
796 }
797 } else {
798 // Add other uses to the worklist to process individually
799 worklist.push(use);
800 }
801 }
802 } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
803 // Store to mark word of inline type larval buffer
804 assert(res_type->is_inlinetypeptr(), "Unexpected store to mark word");
805 } else if (res_type->is_inlinetypeptr() && (use->Opcode() == Op_MemBarRelease || use->Opcode() == Op_MemBarStoreStore)) {
806 // Inline type buffer allocations are followed by a membar
807 } else if (reduce_merge_precheck &&
808 (use->is_Phi() || use->is_EncodeP() ||
809 use->Opcode() == Op_MemBarRelease ||
810 (UseStoreStoreForCtor && use->Opcode() == Op_MemBarStoreStore))) {
811 // Nothing to do
812 } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
813 if (use->is_Phi()) {
814 if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
815 NOT_PRODUCT(fail_eliminate = "Object is return value";)
816 } else {
817 NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
818 }
819 DEBUG_ONLY(disq_node = use;)
820 } else {
821 if (use->Opcode() == Op_Return) {
822 NOT_PRODUCT(fail_eliminate = "Object is return value";)
823 } else {
824 NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
825 }
826 DEBUG_ONLY(disq_node = use;)
827 }
828 can_eliminate = false;
829 } else {
830 assert(use->Opcode() == Op_CastP2X, "should be");
831 assert(!use->has_out_with(Op_OrL), "should have been removed because oop is never null");
832 }
833 }
834 }
835
836 #ifndef PRODUCT
837 if (PrintEliminateAllocations && safepoints != nullptr) {
838 if (can_eliminate) {
839 tty->print("Scalar ");
840 if (res == nullptr)
841 alloc->dump();
842 else
843 res->dump();
844 } else {
845 tty->print("NotScalar (%s)", fail_eliminate);
846 if (res == nullptr)
847 alloc->dump();
848 else
849 res->dump();
850 #ifdef ASSERT
851 if (disq_node != nullptr) {
852 tty->print(" >>>> ");
853 disq_node->dump();
854 }
855 #endif /*ASSERT*/
856 }
857 }
858
859 if (TraceReduceAllocationMerges && !can_eliminate && reduce_merge_precheck) {
860 tty->print_cr("\tCan't eliminate allocation because '%s': ", fail_eliminate != nullptr ? fail_eliminate : "");
861 DEBUG_ONLY(if (disq_node != nullptr) disq_node->dump();)
862 }
863 #endif
864 return can_eliminate;
865 }
866
867 void PhaseMacroExpand::undo_previous_scalarizations(GrowableArray <SafePointNode *> safepoints_done, AllocateNode* alloc) {
868 Node* res = alloc->result_cast();
869 int nfields = 0;
870 assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
871
872 if (res != nullptr) {
873 const TypeOopPtr* res_type = _igvn.type(res)->isa_oopptr();
874
875 if (res_type->isa_instptr()) {
876 // find the fields of the class which will be needed for safepoint debug information
877 ciInstanceKlass* iklass = res_type->is_instptr()->instance_klass();
878 nfields = iklass->nof_nonstatic_fields();
879 } else {
880 // find the array's elements which will be needed for safepoint debug information
881 nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
882 assert(nfields >= 0, "must be an array klass.");
883 }
884 }
885
886 // rollback processed safepoints
887 while (safepoints_done.length() > 0) {
888 SafePointNode* sfpt_done = safepoints_done.pop();
889 // remove any extra entries we added to the safepoint
890 uint last = sfpt_done->req() - 1;
891 for (int k = 0; k < nfields; k++) {
892 sfpt_done->del_req(last--);
893 }
894 JVMState *jvms = sfpt_done->jvms();
895 jvms->set_endoff(sfpt_done->req());
896 // Now make a pass over the debug information replacing any references
897 // to SafePointScalarObjectNode with the allocated object.
898 int start = jvms->debug_start();
899 int end = jvms->debug_end();
900 for (int i = start; i < end; i++) {
901 if (sfpt_done->in(i)->is_SafePointScalarObject()) {
902 SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
903 if (scobj->first_index(jvms) == sfpt_done->req() &&
904 scobj->n_fields() == (uint)nfields) {
905 assert(scobj->alloc() == alloc, "sanity");
906 sfpt_done->set_req(i, res);
907 }
908 }
909 }
910 _igvn._worklist.push(sfpt_done);
911 }
912 }
913
914 #ifdef ASSERT
915 // Verify if a value can be written into a field.
916 void verify_type_compatability(const Type* value_type, const Type* field_type) {
917 BasicType value_bt = value_type->basic_type();
918 BasicType field_bt = field_type->basic_type();
919
920 // Primitive types must match.
921 if (is_java_primitive(value_bt) && value_bt == field_bt) { return; }
922
923 // I have been struggling to make a similar assert for non-primitive
924 // types. I we can add one in the future. For now, I just let them
925 // pass without checks.
926 // In particular, I was struggling with a value that came from a call,
927 // and had only a non-null check CastPP. There was also a checkcast
928 // in the graph to verify the interface, but the corresponding
929 // CheckCastPP result was not updated in the stack slot, and so
930 // we ended up using the CastPP. That means that the field knows
931 // that it should get an oop from an interface, but the value lost
932 // that information, and so it is not a subtype.
933 // There may be other issues, feel free to investigate further!
934 if (!is_java_primitive(value_bt)) { return; }
935
936 tty->print_cr("value not compatible for field: %s vs %s",
937 type2name(value_bt),
938 type2name(field_bt));
939 tty->print("value_type: ");
940 value_type->dump();
941 tty->cr();
942 tty->print("field_type: ");
943 field_type->dump();
944 tty->cr();
945 assert(false, "value_type does not fit field_type");
946 }
947 #endif
948
949 void PhaseMacroExpand::process_field_value_at_safepoint(const Type* field_type, Node* field_val, SafePointNode* sfpt, Unique_Node_List* value_worklist) {
950 if (UseCompressedOops && field_type->isa_narrowoop()) {
951 // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
952 // to be able scalar replace the allocation.
953 if (field_val->is_EncodeP()) {
954 field_val = field_val->in(1);
955 } else if (!field_val->is_InlineType()) {
956 field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
957 }
958 }
959
960 // Keep track of inline types to scalarize them later
961 if (field_val->is_InlineType()) {
962 value_worklist->push(field_val);
963 } else if (field_val->is_Phi()) {
964 PhiNode* phi = field_val->as_Phi();
965 // Eagerly replace inline type phis now since we could be removing an inline type allocation where we must
966 // scalarize all its fields in safepoints.
967 field_val = phi->try_push_inline_types_down(&_igvn, true);
968 if (field_val->is_InlineType()) {
969 value_worklist->push(field_val);
970 }
971 }
972 DEBUG_ONLY(verify_type_compatability(field_val->bottom_type(), field_type);)
973 sfpt->add_req(field_val);
974 }
975
976 bool PhaseMacroExpand::add_array_elems_to_safepoint(AllocateNode* alloc, const TypeAryPtr* array_type, SafePointNode* sfpt, Unique_Node_List* value_worklist) {
977 const Type* elem_type = array_type->elem();
978 BasicType basic_elem_type = elem_type->array_element_basic_type();
979
980 intptr_t elem_size;
981 uint header_size;
982 if (array_type->is_flat()) {
983 elem_size = array_type->flat_elem_size();
984 header_size = arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT);
985 } else {
986 elem_size = type2aelembytes(basic_elem_type);
987 header_size = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
988 }
989
990 int n_elems = alloc->in(AllocateNode::ALength)->get_int();
991 for (int elem_idx = 0; elem_idx < n_elems; elem_idx++) {
992 intptr_t elem_offset = header_size + elem_idx * elem_size;
993 const TypeAryPtr* elem_adr_type = array_type->with_offset(elem_offset);
994 Node* elem_val;
995 if (array_type->is_flat()) {
996 ciInlineKlass* elem_klass = elem_type->inline_klass();
997 assert(elem_klass->maybe_flat_in_array(), "must be flat in array");
998 elem_val = inline_type_from_mem(elem_klass, elem_adr_type, elem_idx, 0, array_type->is_null_free(), alloc, sfpt);
999 } else {
1000 elem_val = value_from_mem(sfpt->memory(), sfpt->control(), basic_elem_type, elem_type, elem_adr_type, alloc);
1001 #ifndef PRODUCT
1002 if (PrintEliminateAllocations && elem_val == nullptr) {
1003 tty->print("=== At SafePoint node %d can't find value of array element [%d]", sfpt->_idx, elem_idx);
1004 tty->print(", which prevents elimination of: ");
1005 alloc->dump();
1006 }
1007 #endif // PRODUCT
1008 }
1009 if (elem_val == nullptr) {
1010 return false;
1011 }
1012
1013 process_field_value_at_safepoint(elem_type, elem_val, sfpt, value_worklist);
1014 }
1015
1016 return true;
1017 }
1018
1019 // Recursively adds all flattened fields of a type 'iklass' inside 'base' to 'sfpt'.
1020 // 'offset_minus_header' refers to the offset of the payload of 'iklass' inside 'base' minus the
1021 // payload offset of 'iklass'. If 'base' is of type 'iklass' then 'offset_minus_header' == 0.
1022 bool PhaseMacroExpand::add_inst_fields_to_safepoint(ciInstanceKlass* iklass, AllocateNode* alloc, Node* base, int offset_minus_header, SafePointNode* sfpt, Unique_Node_List* value_worklist) {
1023 const TypeInstPtr* base_type = _igvn.type(base)->is_instptr();
1024 auto report_failure = [&](int offset) {
1025 #ifndef PRODUCT
1026 if (PrintEliminateAllocations) {
1027 ciInstanceKlass* base_klass = base_type->instance_klass();
1028 ciField* flattened_field = base_klass->get_field_by_offset(offset, false);
1029 assert(flattened_field != nullptr, "must have a field of type %s at offset %d", base_klass->name()->as_utf8(), offset);
1030 tty->print("=== At SafePoint node %d can't find value of field: ", sfpt->_idx);
1031 flattened_field->print();
1032 int field_idx = C->alias_type(flattened_field)->index();
1033 tty->print(" (alias_idx=%d)", field_idx);
1034 tty->print(", which prevents elimination of: ");
1035 base->dump();
1036 }
1037 #endif // PRODUCT
1038 };
1039
1040 for (int i = 0; i < iklass->nof_declared_nonstatic_fields(); i++) {
1041 ciField* field = iklass->declared_nonstatic_field_at(i);
1042 if (field->is_flat()) {
1043 ciInlineKlass* fvk = field->type()->as_inline_klass();
1044 int field_offset_minus_header = offset_minus_header + field->offset_in_bytes() - fvk->payload_offset();
1045 bool success = add_inst_fields_to_safepoint(fvk, alloc, base, field_offset_minus_header, sfpt, value_worklist);
1046 if (!success) {
1047 return false;
1048 }
1049
1050 // The null marker of a field is added right after we scalarize that field
1051 if (!field->is_null_free()) {
1052 int nm_offset = offset_minus_header + field->null_marker_offset();
1053 Node* null_marker = value_from_mem(sfpt->memory(), sfpt->control(), T_BOOLEAN, TypeInt::BOOL, base_type->with_offset(nm_offset), alloc);
1054 if (null_marker == nullptr) {
1055 report_failure(nm_offset);
1056 return false;
1057 }
1058 process_field_value_at_safepoint(TypeInt::BOOL, null_marker, sfpt, value_worklist);
1059 }
1060
1061 continue;
1062 }
1063
1064 int offset = offset_minus_header + field->offset_in_bytes();
1065 ciType* elem_type = field->type();
1066 BasicType basic_elem_type = field->layout_type();
1067
1068 const Type* field_type;
1069 if (is_reference_type(basic_elem_type)) {
1070 if (!elem_type->is_loaded()) {
1071 field_type = TypeInstPtr::BOTTOM;
1072 } else {
1073 field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
1074 }
1075 if (UseCompressedOops) {
1076 field_type = field_type->make_narrowoop();
1077 basic_elem_type = T_NARROWOOP;
1078 }
1079 } else {
1080 field_type = Type::get_const_basic_type(basic_elem_type);
1081 }
1082
1083 const TypeInstPtr* field_addr_type = base_type->add_offset(offset)->isa_instptr();
1084 Node* field_val = value_from_mem(sfpt->memory(), sfpt->control(), basic_elem_type, field_type, field_addr_type, alloc);
1085 if (field_val == nullptr) {
1086 report_failure(offset);
1087 return false;
1088 }
1089 process_field_value_at_safepoint(field_type, field_val, sfpt, value_worklist);
1090 }
1091
1092 return true;
1093 }
1094
1095 SafePointScalarObjectNode* PhaseMacroExpand::create_scalarized_object_description(AllocateNode* alloc, SafePointNode* sfpt,
1096 Unique_Node_List* value_worklist) {
1097 // Fields of scalar objs are referenced only at the end
1098 // of regular debuginfo at the last (youngest) JVMS.
1099 // Record relative start index.
1100 ciInstanceKlass* iklass = nullptr;
1101 const TypeOopPtr* res_type = nullptr;
1102 int nfields = 0;
1103 uint first_ind = (sfpt->req() - sfpt->jvms()->scloff());
1104 Node* res = alloc->result_cast();
1105
1106 assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
1107 assert(sfpt->jvms() != nullptr, "missed JVMS");
1108 uint before_sfpt_req = sfpt->req();
1109
1110 if (res != nullptr) { // Could be null when there are no users
1111 res_type = _igvn.type(res)->isa_oopptr();
1112
1113 if (res_type->isa_instptr()) {
1114 // find the fields of the class which will be needed for safepoint debug information
1115 iklass = res_type->is_instptr()->instance_klass();
1116 nfields = iklass->nof_nonstatic_fields();
1117 } else {
1118 // find the array's elements which will be needed for safepoint debug information
1119 nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
1120 assert(nfields >= 0, "must be an array klass.");
1121 }
1122
1123 if (res->bottom_type()->is_inlinetypeptr()) {
1124 // Nullable inline types have a null marker field which is added to the safepoint when scalarizing them (see
1125 // InlineTypeNode::make_scalar_in_safepoint()). When having circular inline types, we stop scalarizing at depth 1
1126 // to avoid an endless recursion. Therefore, we do not have a SafePointScalarObjectNode node here, yet.
1127 // We are about to create a SafePointScalarObjectNode as if this is a normal object. Add an additional int input
1128 // with value 1 which sets the null marker to true to indicate that the object is always non-null. This input is checked
1129 // later in PhaseOutput::filLocArray() for inline types.
1130 sfpt->add_req(_igvn.intcon(1));
1131 }
1132 }
1133
1134 SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type, alloc, first_ind, sfpt->jvms()->depth(), nfields);
1135 sobj->init_req(0, C->root());
1136 transform_later(sobj);
1137
1138 if (res == nullptr) {
1139 sfpt->jvms()->set_endoff(sfpt->req());
1140 return sobj;
1141 }
1142
1143 bool success;
1144 if (iklass == nullptr) {
1145 success = add_array_elems_to_safepoint(alloc, res_type->is_aryptr(), sfpt, value_worklist);
1146 } else {
1147 success = add_inst_fields_to_safepoint(iklass, alloc, res, 0, sfpt, value_worklist);
1148 }
1149
1150 // We weren't able to find a value for this field, remove all the fields added to the safepoint
1151 if (!success) {
1152 for (uint i = sfpt->req() - 1; i >= before_sfpt_req; i--) {
1153 sfpt->del_req(i);
1154 }
1155 _igvn._worklist.push(sfpt);
1156 return nullptr;
1157 }
1158
1159 sfpt->jvms()->set_endoff(sfpt->req());
1160 return sobj;
1161 }
1162
1163 // Do scalar replacement.
1164 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
1165 GrowableArray <SafePointNode *> safepoints_done;
1166 Node* res = alloc->result_cast();
1167 assert(res == nullptr || res->is_CheckCastPP(), "unexpected AllocateNode result");
1168 const TypeOopPtr* res_type = nullptr;
1169 if (res != nullptr) { // Could be null when there are no users
1170 res_type = _igvn.type(res)->isa_oopptr();
1171 }
1172
1173 // Process the safepoint uses
1174 Unique_Node_List value_worklist;
1175 while (safepoints.length() > 0) {
1176 SafePointNode* sfpt = safepoints.pop();
1177 SafePointScalarObjectNode* sobj = create_scalarized_object_description(alloc, sfpt, &value_worklist);
1178
1179 if (sobj == nullptr) {
1180 undo_previous_scalarizations(safepoints_done, alloc);
1181 return false;
1182 }
1183
1184 // Now make a pass over the debug information replacing any references
1185 // to the allocated object with "sobj"
1186 JVMState *jvms = sfpt->jvms();
1187 sfpt->replace_edges_in_range(res, sobj, jvms->debug_start(), jvms->debug_end(), &_igvn);
1188 _igvn._worklist.push(sfpt);
1189
1190 // keep it for rollback
1191 safepoints_done.append_if_missing(sfpt);
1192 }
1193 // Scalarize inline types that were added to the safepoint.
1194 // Don't allow linking a constant oop (if available) for flat array elements
1195 // because Deoptimization::reassign_flat_array_elements needs field values.
1196 bool allow_oop = (res_type != nullptr) && !res_type->is_flat();
1197 for (uint i = 0; i < value_worklist.size(); ++i) {
1198 InlineTypeNode* vt = value_worklist.at(i)->as_InlineType();
1199 vt->make_scalar_in_safepoints(&_igvn, allow_oop);
1200 }
1201 return true;
1202 }
1203
1204 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
1205 Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
1206 Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
1207 if (ctl_proj != nullptr) {
1208 igvn.replace_node(ctl_proj, n->in(0));
1209 }
1210 if (mem_proj != nullptr) {
1211 igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
1212 }
1213 }
1214
1215 // Process users of eliminated allocation.
1216 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc, bool inline_alloc) {
1217 Unique_Node_List worklist;
1218 Node* res = alloc->result_cast();
1219 if (res != nullptr) {
1220 worklist.push(res);
1221 }
1222 while (worklist.size() > 0) {
1223 res = worklist.pop();
1224 for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
1225 Node *use = res->last_out(j);
1226 uint oc1 = res->outcnt();
1227
1228 if (use->is_AddP()) {
1229 for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
1230 Node *n = use->last_out(k);
1231 uint oc2 = use->outcnt();
1232 if (n->is_Store()) {
1233 for (DUIterator_Fast pmax, p = n->fast_outs(pmax); p < pmax; p++) {
1234 MemBarNode* mb = n->fast_out(p)->isa_MemBar();
1235 if (mb != nullptr && mb->req() <= MemBarNode::Precedent && mb->in(MemBarNode::Precedent) == n) {
1236 // MemBarVolatiles should have been removed by MemBarNode::Ideal() for non-inline allocations
1237 assert(inline_alloc, "MemBarVolatile should be eliminated for non-escaping object");
1238 mb->remove(&_igvn);
1239 }
1240 }
1241 _igvn.replace_node(n, n->in(MemNode::Memory));
1242 } else {
1243 eliminate_gc_barrier(n);
1244 }
1245 k -= (oc2 - use->outcnt());
1246 }
1247 _igvn.remove_dead_node(use);
1248 } else if (use->is_ArrayCopy()) {
1249 // Disconnect ArrayCopy node
1250 ArrayCopyNode* ac = use->as_ArrayCopy();
1251 if (ac->is_clonebasic()) {
1252 Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
1253 disconnect_projections(ac, _igvn);
1254 assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
1255 Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
1256 disconnect_projections(membar_before->as_MemBar(), _igvn);
1257 if (membar_after->is_MemBar()) {
1258 disconnect_projections(membar_after->as_MemBar(), _igvn);
1259 }
1260 } else {
1261 assert(ac->is_arraycopy_validated() ||
1262 ac->is_copyof_validated() ||
1263 ac->is_copyofrange_validated(), "unsupported");
1264 CallProjections* callprojs = ac->extract_projections(true);
1265
1266 _igvn.replace_node(callprojs->fallthrough_ioproj, ac->in(TypeFunc::I_O));
1267 _igvn.replace_node(callprojs->fallthrough_memproj, ac->in(TypeFunc::Memory));
1268 _igvn.replace_node(callprojs->fallthrough_catchproj, ac->in(TypeFunc::Control));
1269
1270 // Set control to top. IGVN will remove the remaining projections
1271 ac->set_req(0, top());
1272 ac->replace_edge(res, top(), &_igvn);
1273
1274 // Disconnect src right away: it can help find new
1275 // opportunities for allocation elimination
1276 Node* src = ac->in(ArrayCopyNode::Src);
1277 ac->replace_edge(src, top(), &_igvn);
1278 // src can be top at this point if src and dest of the
1279 // arraycopy were the same
1280 if (src->outcnt() == 0 && !src->is_top()) {
1281 _igvn.remove_dead_node(src);
1282 }
1283 }
1284 _igvn._worklist.push(ac);
1285 } else if (use->is_InlineType()) {
1286 assert(use->as_InlineType()->get_oop() == res, "unexpected inline type ptr use");
1287 // Cut off oop input and remove known instance id from type
1288 _igvn.rehash_node_delayed(use);
1289 use->as_InlineType()->set_oop(_igvn, _igvn.zerocon(T_OBJECT));
1290 use->as_InlineType()->set_is_buffered(_igvn, false);
1291 const TypeOopPtr* toop = _igvn.type(use)->is_oopptr()->cast_to_instance_id(TypeOopPtr::InstanceBot);
1292 _igvn.set_type(use, toop);
1293 use->as_InlineType()->set_type(toop);
1294 // Process users
1295 for (DUIterator_Fast kmax, k = use->fast_outs(kmax); k < kmax; k++) {
1296 Node* u = use->fast_out(k);
1297 if (!u->is_InlineType() && !u->is_StoreFlat()) {
1298 worklist.push(u);
1299 }
1300 }
1301 } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
1302 // Store to mark word of inline type larval buffer
1303 assert(inline_alloc, "Unexpected store to mark word");
1304 _igvn.replace_node(use, use->in(MemNode::Memory));
1305 } else if (use->Opcode() == Op_MemBarRelease || use->Opcode() == Op_MemBarStoreStore) {
1306 // Inline type buffer allocations are followed by a membar
1307 assert(inline_alloc, "Unexpected MemBarRelease");
1308 use->as_MemBar()->remove(&_igvn);
1309 } else {
1310 eliminate_gc_barrier(use);
1311 }
1312 j -= (oc1 - res->outcnt());
1313 }
1314 assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1315 _igvn.remove_dead_node(res);
1316 }
1317
1318 //
1319 // Process other users of allocation's projections
1320 //
1321 if (_callprojs->resproj[0] != nullptr && _callprojs->resproj[0]->outcnt() != 0) {
1322 // First disconnect stores captured by Initialize node.
1323 // If Initialize node is eliminated first in the following code,
1324 // it will kill such stores and DUIterator_Last will assert.
1325 for (DUIterator_Fast jmax, j = _callprojs->resproj[0]->fast_outs(jmax); j < jmax; j++) {
1326 Node* use = _callprojs->resproj[0]->fast_out(j);
1327 if (use->is_AddP()) {
1328 // raw memory addresses used only by the initialization
1329 _igvn.replace_node(use, C->top());
1330 --j; --jmax;
1331 }
1332 }
1333 for (DUIterator_Last jmin, j = _callprojs->resproj[0]->last_outs(jmin); j >= jmin; ) {
1334 Node* use = _callprojs->resproj[0]->last_out(j);
1335 uint oc1 = _callprojs->resproj[0]->outcnt();
1336 if (use->is_Initialize()) {
1337 // Eliminate Initialize node.
1338 InitializeNode *init = use->as_Initialize();
1339 Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1340 if (ctrl_proj != nullptr) {
1341 _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1342 #ifdef ASSERT
1343 // If the InitializeNode has no memory out, it will die, and tmp will become null
1344 Node* tmp = init->in(TypeFunc::Control);
1345 assert(tmp == nullptr || tmp == _callprojs->fallthrough_catchproj, "allocation control projection");
1346 #endif
1347 }
1348 Node* mem = init->in(TypeFunc::Memory);
1349 #ifdef ASSERT
1350 if (init->number_of_projs(TypeFunc::Memory) > 0) {
1351 if (mem->is_MergeMem()) {
1352 assert(mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw) == _callprojs->fallthrough_memproj, "allocation memory projection");
1353 } else {
1354 assert(mem == _callprojs->fallthrough_memproj, "allocation memory projection");
1355 }
1356 }
1357 #endif
1358 init->replace_mem_projs_by(mem, &_igvn);
1359 assert(init->outcnt() == 0, "should only have had a control and some memory projections, and we removed them");
1360 } else if (use->Opcode() == Op_MemBarStoreStore) {
1361 // Inline type buffer allocations are followed by a membar
1362 assert(inline_alloc, "Unexpected MemBarStoreStore");
1363 use->as_MemBar()->remove(&_igvn);
1364 } else {
1365 assert(false, "only Initialize or AddP expected");
1366 }
1367 j -= (oc1 - _callprojs->resproj[0]->outcnt());
1368 }
1369 }
1370 if (_callprojs->fallthrough_catchproj != nullptr) {
1371 _igvn.replace_node(_callprojs->fallthrough_catchproj, alloc->in(TypeFunc::Control));
1372 }
1373 if (_callprojs->fallthrough_memproj != nullptr) {
1374 _igvn.replace_node(_callprojs->fallthrough_memproj, alloc->in(TypeFunc::Memory));
1375 }
1376 if (_callprojs->catchall_memproj != nullptr) {
1377 _igvn.replace_node(_callprojs->catchall_memproj, C->top());
1378 }
1379 if (_callprojs->fallthrough_ioproj != nullptr) {
1380 _igvn.replace_node(_callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
1381 }
1382 if (_callprojs->catchall_ioproj != nullptr) {
1383 _igvn.replace_node(_callprojs->catchall_ioproj, C->top());
1384 }
1385 if (_callprojs->catchall_catchproj != nullptr) {
1386 _igvn.replace_node(_callprojs->catchall_catchproj, C->top());
1387 }
1388 }
1389
1390 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1391 // If reallocation fails during deoptimization we'll pop all
1392 // interpreter frames for this compiled frame and that won't play
1393 // nice with JVMTI popframe.
1394 // We avoid this issue by eager reallocation when the popframe request
1395 // is received.
1396 if (!EliminateAllocations) {
1397 return false;
1398 }
1399 Node* klass = alloc->in(AllocateNode::KlassNode);
1400 const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1401
1402 // Attempt to eliminate inline type buffer allocations
1403 // regardless of usage and escape/replaceable status.
1404 bool inline_alloc = tklass->isa_instklassptr() &&
1405 tklass->is_instklassptr()->instance_klass()->is_inlinetype();
1406 if (!alloc->_is_non_escaping && !inline_alloc) {
1407 return false;
1408 }
1409 // Eliminate boxing allocations which are not used
1410 // regardless scalar replaceable status.
1411 Node* res = alloc->result_cast();
1412 bool boxing_alloc = (res == nullptr) && C->eliminate_boxing() &&
1413 tklass->isa_instklassptr() &&
1414 tklass->is_instklassptr()->instance_klass()->is_box_klass();
1415 if (!alloc->_is_scalar_replaceable && !boxing_alloc && !inline_alloc) {
1416 return false;
1417 }
1418
1419 _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1420
1421 GrowableArray <SafePointNode *> safepoints;
1422 if (!can_eliminate_allocation(&_igvn, alloc, &safepoints)) {
1423 return false;
1424 }
1425
1426 if (!alloc->_is_scalar_replaceable) {
1427 assert(res == nullptr || inline_alloc, "sanity");
1428 // We can only eliminate allocation if all debug info references
1429 // are already replaced with SafePointScalarObject because
1430 // we can't search for a fields value without instance_id.
1431 if (safepoints.length() > 0) {
1432 return false;
1433 }
1434 }
1435
1436 if (!scalar_replacement(alloc, safepoints)) {
1437 return false;
1438 }
1439
1440 CompileLog* log = C->log();
1441 if (log != nullptr) {
1442 log->head("eliminate_allocation type='%d'",
1443 log->identify(tklass->exact_klass()));
1444 JVMState* p = alloc->jvms();
1445 while (p != nullptr) {
1446 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1447 p = p->caller();
1448 }
1449 log->tail("eliminate_allocation");
1450 }
1451
1452 process_users_of_allocation(alloc, inline_alloc);
1453
1454 #ifndef PRODUCT
1455 if (PrintEliminateAllocations) {
1456 if (alloc->is_AllocateArray())
1457 tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1458 else
1459 tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1460 }
1461 #endif
1462
1463 return true;
1464 }
1465
1466 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1467 // EA should remove all uses of non-escaping boxing node.
1468 if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != nullptr) {
1469 return false;
1470 }
1471
1472 assert(boxing->result_cast() == nullptr, "unexpected boxing node result");
1473
1474 _callprojs = boxing->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1475
1476 const TypeTuple* r = boxing->tf()->range_sig();
1477 assert(r->cnt() > TypeFunc::Parms, "sanity");
1478 const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1479 assert(t != nullptr, "sanity");
1480
1481 CompileLog* log = C->log();
1482 if (log != nullptr) {
1483 log->head("eliminate_boxing type='%d'",
1484 log->identify(t->instance_klass()));
1485 JVMState* p = boxing->jvms();
1486 while (p != nullptr) {
1487 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1488 p = p->caller();
1489 }
1490 log->tail("eliminate_boxing");
1491 }
1492
1493 process_users_of_allocation(boxing);
1494
1495 #ifndef PRODUCT
1496 if (PrintEliminateAllocations) {
1497 tty->print("++++ Eliminated: %d ", boxing->_idx);
1498 boxing->method()->print_short_name(tty);
1499 tty->cr();
1500 }
1501 #endif
1502
1503 return true;
1504 }
1505
1506
1507 Node* PhaseMacroExpand::make_load(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) {
1508 Node* adr = basic_plus_adr(base, offset);
1509 const TypePtr* adr_type = adr->bottom_type()->is_ptr();
1510 Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt, MemNode::unordered);
1511 transform_later(value);
1512 return value;
1513 }
1514
1515
1516 Node* PhaseMacroExpand::make_store(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) {
1517 Node* adr = basic_plus_adr(base, offset);
1518 mem = StoreNode::make(_igvn, ctl, mem, adr, nullptr, value, bt, MemNode::unordered);
1519 transform_later(mem);
1520 return mem;
1521 }
1522
1523 //=============================================================================
1524 //
1525 // A L L O C A T I O N
1526 //
1527 // Allocation attempts to be fast in the case of frequent small objects.
1528 // It breaks down like this:
1529 //
1530 // 1) Size in doublewords is computed. This is a constant for objects and
1531 // variable for most arrays. Doubleword units are used to avoid size
1532 // overflow of huge doubleword arrays. We need doublewords in the end for
1533 // rounding.
1534 //
1535 // 2) Size is checked for being 'too large'. Too-large allocations will go
1536 // the slow path into the VM. The slow path can throw any required
1537 // exceptions, and does all the special checks for very large arrays. The
1538 // size test can constant-fold away for objects. For objects with
1539 // finalizers it constant-folds the otherway: you always go slow with
1540 // finalizers.
1541 //
1542 // 3) If NOT using TLABs, this is the contended loop-back point.
1543 // Load-Locked the heap top. If using TLABs normal-load the heap top.
1544 //
1545 // 4) Check that heap top + size*8 < max. If we fail go the slow ` route.
1546 // NOTE: "top+size*8" cannot wrap the 4Gig line! Here's why: for largish
1547 // "size*8" we always enter the VM, where "largish" is a constant picked small
1548 // enough that there's always space between the eden max and 4Gig (old space is
1549 // there so it's quite large) and large enough that the cost of entering the VM
1550 // is dwarfed by the cost to initialize the space.
1551 //
1552 // 5) If NOT using TLABs, Store-Conditional the adjusted heap top back
1553 // down. If contended, repeat at step 3. If using TLABs normal-store
1554 // adjusted heap top back down; there is no contention.
1555 //
1556 // 6) If !ZeroTLAB then Bulk-clear the object/array. Fill in klass & mark
1557 // fields.
1558 //
1559 // 7) Merge with the slow-path; cast the raw memory pointer to the correct
1560 // oop flavor.
1561 //
1562 //=============================================================================
1563 // FastAllocateSizeLimit value is in DOUBLEWORDS.
1564 // Allocations bigger than this always go the slow route.
1565 // This value must be small enough that allocation attempts that need to
1566 // trigger exceptions go the slow route. Also, it must be small enough so
1567 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
1568 //=============================================================================j//
1569 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
1570 // The allocator will coalesce int->oop copies away. See comment in
1571 // coalesce.cpp about how this works. It depends critically on the exact
1572 // code shape produced here, so if you are changing this code shape
1573 // make sure the GC info for the heap-top is correct in and around the
1574 // slow-path call.
1575 //
1576
1577 void PhaseMacroExpand::expand_allocate_common(
1578 AllocateNode* alloc, // allocation node to be expanded
1579 Node* length, // array length for an array allocation
1580 Node* init_val, // value to initialize the array with
1581 const TypeFunc* slow_call_type, // Type of slow call
1582 address slow_call_address, // Address of slow call
1583 Node* valid_length_test // whether length is valid or not
1584 )
1585 {
1586 Node* ctrl = alloc->in(TypeFunc::Control);
1587 Node* mem = alloc->in(TypeFunc::Memory);
1588 Node* i_o = alloc->in(TypeFunc::I_O);
1589 Node* size_in_bytes = alloc->in(AllocateNode::AllocSize);
1590 Node* klass_node = alloc->in(AllocateNode::KlassNode);
1591 Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1592 assert(ctrl != nullptr, "must have control");
1593
1594 // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1595 // they will not be used if "always_slow" is set
1596 enum { slow_result_path = 1, fast_result_path = 2 };
1597 Node *result_region = nullptr;
1598 Node *result_phi_rawmem = nullptr;
1599 Node *result_phi_rawoop = nullptr;
1600 Node *result_phi_i_o = nullptr;
1601
1602 // The initial slow comparison is a size check, the comparison
1603 // we want to do is a BoolTest::gt
1604 bool expand_fast_path = true;
1605 int tv = _igvn.find_int_con(initial_slow_test, -1);
1606 if (tv >= 0) {
1607 // InitialTest has constant result
1608 // 0 - can fit in TLAB
1609 // 1 - always too big or negative
1610 assert(tv <= 1, "0 or 1 if a constant");
1611 expand_fast_path = (tv == 0);
1612 initial_slow_test = nullptr;
1613 } else {
1614 initial_slow_test = BoolNode::make_predicate(initial_slow_test, &_igvn);
1615 }
1616
1617 if (!UseTLAB) {
1618 // Force slow-path allocation
1619 expand_fast_path = false;
1620 initial_slow_test = nullptr;
1621 }
1622
1623 bool allocation_has_use = (alloc->result_cast() != nullptr);
1624 if (!allocation_has_use) {
1625 InitializeNode* init = alloc->initialization();
1626 if (init != nullptr) {
1627 init->remove(&_igvn);
1628 }
1629 if (expand_fast_path && (initial_slow_test == nullptr)) {
1630 // Remove allocation node and return.
1631 // Size is a non-negative constant -> no initial check needed -> directly to fast path.
1632 // Also, no usages -> empty fast path -> no fall out to slow path -> nothing left.
1633 #ifndef PRODUCT
1634 if (PrintEliminateAllocations) {
1635 tty->print("NotUsed ");
1636 Node* res = alloc->proj_out_or_null(TypeFunc::Parms);
1637 if (res != nullptr) {
1638 res->dump();
1639 } else {
1640 alloc->dump();
1641 }
1642 }
1643 #endif
1644 yank_alloc_node(alloc);
1645 return;
1646 }
1647 }
1648
1649 enum { too_big_or_final_path = 1, need_gc_path = 2 };
1650 Node *slow_region = nullptr;
1651 Node *toobig_false = ctrl;
1652
1653 // generate the initial test if necessary
1654 if (initial_slow_test != nullptr ) {
1655 assert (expand_fast_path, "Only need test if there is a fast path");
1656 slow_region = new RegionNode(3);
1657
1658 // Now make the initial failure test. Usually a too-big test but
1659 // might be a TRUE for finalizers.
1660 IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1661 transform_later(toobig_iff);
1662 // Plug the failing-too-big test into the slow-path region
1663 Node* toobig_true = new IfTrueNode(toobig_iff);
1664 transform_later(toobig_true);
1665 slow_region ->init_req( too_big_or_final_path, toobig_true );
1666 toobig_false = new IfFalseNode(toobig_iff);
1667 transform_later(toobig_false);
1668 } else {
1669 // No initial test, just fall into next case
1670 assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1671 toobig_false = ctrl;
1672 DEBUG_ONLY(slow_region = NodeSentinel);
1673 }
1674
1675 // If we are here there are several possibilities
1676 // - expand_fast_path is false - then only a slow path is expanded. That's it.
1677 // no_initial_check means a constant allocation.
1678 // - If check always evaluates to false -> expand_fast_path is false (see above)
1679 // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1680 // if !allocation_has_use the fast path is empty
1681 // if !allocation_has_use && no_initial_check
1682 // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1683 // removed by yank_alloc_node above.
1684
1685 Node *slow_mem = mem; // save the current memory state for slow path
1686 // generate the fast allocation code unless we know that the initial test will always go slow
1687 if (expand_fast_path) {
1688 // Fast path modifies only raw memory.
1689 if (mem->is_MergeMem()) {
1690 mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1691 }
1692
1693 // allocate the Region and Phi nodes for the result
1694 result_region = new RegionNode(3);
1695 result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1696 result_phi_i_o = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1697
1698 // Grab regular I/O before optional prefetch may change it.
1699 // Slow-path does no I/O so just set it to the original I/O.
1700 result_phi_i_o->init_req(slow_result_path, i_o);
1701
1702 // Name successful fast-path variables
1703 Node* fast_oop_ctrl;
1704 Node* fast_oop_rawmem;
1705
1706 if (allocation_has_use) {
1707 Node* needgc_ctrl = nullptr;
1708 result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1709
1710 intx prefetch_lines = length != nullptr ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1711 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1712 Node* fast_oop = bs->obj_allocate(this, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1713 fast_oop_ctrl, fast_oop_rawmem,
1714 prefetch_lines);
1715
1716 if (initial_slow_test != nullptr) {
1717 // This completes all paths into the slow merge point
1718 slow_region->init_req(need_gc_path, needgc_ctrl);
1719 transform_later(slow_region);
1720 } else {
1721 // No initial slow path needed!
1722 // Just fall from the need-GC path straight into the VM call.
1723 slow_region = needgc_ctrl;
1724 }
1725
1726 InitializeNode* init = alloc->initialization();
1727 fast_oop_rawmem = initialize_object(alloc,
1728 fast_oop_ctrl, fast_oop_rawmem, fast_oop,
1729 klass_node, length, size_in_bytes);
1730 expand_initialize_membar(alloc, init, fast_oop_ctrl, fast_oop_rawmem);
1731 expand_dtrace_alloc_probe(alloc, fast_oop, fast_oop_ctrl, fast_oop_rawmem);
1732
1733 result_phi_rawoop->init_req(fast_result_path, fast_oop);
1734 } else {
1735 assert (initial_slow_test != nullptr, "sanity");
1736 fast_oop_ctrl = toobig_false;
1737 fast_oop_rawmem = mem;
1738 transform_later(slow_region);
1739 }
1740
1741 // Plug in the successful fast-path into the result merge point
1742 result_region ->init_req(fast_result_path, fast_oop_ctrl);
1743 result_phi_i_o ->init_req(fast_result_path, i_o);
1744 result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1745 } else {
1746 slow_region = ctrl;
1747 result_phi_i_o = i_o; // Rename it to use in the following code.
1748 }
1749
1750 // Generate slow-path call
1751 CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1752 OptoRuntime::stub_name(slow_call_address),
1753 TypePtr::BOTTOM);
1754 call->init_req(TypeFunc::Control, slow_region);
1755 call->init_req(TypeFunc::I_O, top()); // does no i/o
1756 call->init_req(TypeFunc::Memory, slow_mem); // may gc ptrs
1757 call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1758 call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1759
1760 call->init_req(TypeFunc::Parms+0, klass_node);
1761 if (length != nullptr) {
1762 call->init_req(TypeFunc::Parms+1, length);
1763 if (init_val != nullptr) {
1764 call->init_req(TypeFunc::Parms+2, init_val);
1765 }
1766 } else {
1767 // Let the runtime know if this is a larval allocation
1768 call->init_req(TypeFunc::Parms+1, _igvn.intcon(alloc->_larval));
1769 }
1770
1771 // Copy debug information and adjust JVMState information, then replace
1772 // allocate node with the call
1773 call->copy_call_debug_info(&_igvn, alloc);
1774 // For array allocations, copy the valid length check to the call node so Compile::final_graph_reshaping() can verify
1775 // that the call has the expected number of CatchProj nodes (in case the allocation always fails and the fallthrough
1776 // path dies).
1777 if (valid_length_test != nullptr) {
1778 call->add_req(valid_length_test);
1779 }
1780 if (expand_fast_path) {
1781 call->set_cnt(PROB_UNLIKELY_MAG(4)); // Same effect as RC_UNCOMMON.
1782 } else {
1783 // Hook i_o projection to avoid its elimination during allocation
1784 // replacement (when only a slow call is generated).
1785 call->set_req(TypeFunc::I_O, result_phi_i_o);
1786 }
1787 _igvn.replace_node(alloc, call);
1788 transform_later(call);
1789
1790 // Identify the output projections from the allocate node and
1791 // adjust any references to them.
1792 // The control and io projections look like:
1793 //
1794 // v---Proj(ctrl) <-----+ v---CatchProj(ctrl)
1795 // Allocate Catch
1796 // ^---Proj(io) <-------+ ^---CatchProj(io)
1797 //
1798 // We are interested in the CatchProj nodes.
1799 //
1800 _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1801
1802 // An allocate node has separate memory projections for the uses on
1803 // the control and i_o paths. Replace the control memory projection with
1804 // result_phi_rawmem (unless we are only generating a slow call when
1805 // both memory projections are combined)
1806 if (expand_fast_path && _callprojs->fallthrough_memproj != nullptr) {
1807 _igvn.replace_in_uses(_callprojs->fallthrough_memproj, result_phi_rawmem);
1808 }
1809 // Now change uses of catchall_memproj to use fallthrough_memproj and delete
1810 // catchall_memproj so we end up with a call that has only 1 memory projection.
1811 if (_callprojs->catchall_memproj != nullptr) {
1812 if (_callprojs->fallthrough_memproj == nullptr) {
1813 _callprojs->fallthrough_memproj = new ProjNode(call, TypeFunc::Memory);
1814 transform_later(_callprojs->fallthrough_memproj);
1815 }
1816 _igvn.replace_in_uses(_callprojs->catchall_memproj, _callprojs->fallthrough_memproj);
1817 _igvn.remove_dead_node(_callprojs->catchall_memproj);
1818 }
1819
1820 // An allocate node has separate i_o projections for the uses on the control
1821 // and i_o paths. Always replace the control i_o projection with result i_o
1822 // otherwise incoming i_o become dead when only a slow call is generated
1823 // (it is different from memory projections where both projections are
1824 // combined in such case).
1825 if (_callprojs->fallthrough_ioproj != nullptr) {
1826 _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, result_phi_i_o);
1827 }
1828 // Now change uses of catchall_ioproj to use fallthrough_ioproj and delete
1829 // catchall_ioproj so we end up with a call that has only 1 i_o projection.
1830 if (_callprojs->catchall_ioproj != nullptr) {
1831 if (_callprojs->fallthrough_ioproj == nullptr) {
1832 _callprojs->fallthrough_ioproj = new ProjNode(call, TypeFunc::I_O);
1833 transform_later(_callprojs->fallthrough_ioproj);
1834 }
1835 _igvn.replace_in_uses(_callprojs->catchall_ioproj, _callprojs->fallthrough_ioproj);
1836 _igvn.remove_dead_node(_callprojs->catchall_ioproj);
1837 }
1838
1839 // if we generated only a slow call, we are done
1840 if (!expand_fast_path) {
1841 // Now we can unhook i_o.
1842 if (result_phi_i_o->outcnt() > 1) {
1843 call->set_req(TypeFunc::I_O, top());
1844 } else {
1845 assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1846 // Case of new array with negative size known during compilation.
1847 // AllocateArrayNode::Ideal() optimization disconnect unreachable
1848 // following code since call to runtime will throw exception.
1849 // As result there will be no users of i_o after the call.
1850 // Leave i_o attached to this call to avoid problems in preceding graph.
1851 }
1852 return;
1853 }
1854
1855 if (_callprojs->fallthrough_catchproj != nullptr) {
1856 ctrl = _callprojs->fallthrough_catchproj->clone();
1857 transform_later(ctrl);
1858 _igvn.replace_node(_callprojs->fallthrough_catchproj, result_region);
1859 } else {
1860 ctrl = top();
1861 }
1862 Node *slow_result;
1863 if (_callprojs->resproj[0] == nullptr) {
1864 // no uses of the allocation result
1865 slow_result = top();
1866 } else {
1867 slow_result = _callprojs->resproj[0]->clone();
1868 transform_later(slow_result);
1869 _igvn.replace_node(_callprojs->resproj[0], result_phi_rawoop);
1870 }
1871
1872 // Plug slow-path into result merge point
1873 result_region->init_req( slow_result_path, ctrl);
1874 transform_later(result_region);
1875 if (allocation_has_use) {
1876 result_phi_rawoop->init_req(slow_result_path, slow_result);
1877 transform_later(result_phi_rawoop);
1878 }
1879 result_phi_rawmem->init_req(slow_result_path, _callprojs->fallthrough_memproj);
1880 transform_later(result_phi_rawmem);
1881 transform_later(result_phi_i_o);
1882 // This completes all paths into the result merge point
1883 }
1884
1885 // Remove alloc node that has no uses.
1886 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1887 Node* ctrl = alloc->in(TypeFunc::Control);
1888 Node* mem = alloc->in(TypeFunc::Memory);
1889 Node* i_o = alloc->in(TypeFunc::I_O);
1890
1891 _callprojs = alloc->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
1892 if (_callprojs->resproj[0] != nullptr) {
1893 for (DUIterator_Fast imax, i = _callprojs->resproj[0]->fast_outs(imax); i < imax; i++) {
1894 Node* use = _callprojs->resproj[0]->fast_out(i);
1895 use->isa_MemBar()->remove(&_igvn);
1896 --imax;
1897 --i; // back up iterator
1898 }
1899 assert(_callprojs->resproj[0]->outcnt() == 0, "all uses must be deleted");
1900 _igvn.remove_dead_node(_callprojs->resproj[0]);
1901 }
1902 if (_callprojs->fallthrough_catchproj != nullptr) {
1903 _igvn.replace_in_uses(_callprojs->fallthrough_catchproj, ctrl);
1904 _igvn.remove_dead_node(_callprojs->fallthrough_catchproj);
1905 }
1906 if (_callprojs->catchall_catchproj != nullptr) {
1907 _igvn.rehash_node_delayed(_callprojs->catchall_catchproj);
1908 _callprojs->catchall_catchproj->set_req(0, top());
1909 }
1910 if (_callprojs->fallthrough_proj != nullptr) {
1911 Node* catchnode = _callprojs->fallthrough_proj->unique_ctrl_out();
1912 _igvn.remove_dead_node(catchnode);
1913 _igvn.remove_dead_node(_callprojs->fallthrough_proj);
1914 }
1915 if (_callprojs->fallthrough_memproj != nullptr) {
1916 _igvn.replace_in_uses(_callprojs->fallthrough_memproj, mem);
1917 _igvn.remove_dead_node(_callprojs->fallthrough_memproj);
1918 }
1919 if (_callprojs->fallthrough_ioproj != nullptr) {
1920 _igvn.replace_in_uses(_callprojs->fallthrough_ioproj, i_o);
1921 _igvn.remove_dead_node(_callprojs->fallthrough_ioproj);
1922 }
1923 if (_callprojs->catchall_memproj != nullptr) {
1924 _igvn.rehash_node_delayed(_callprojs->catchall_memproj);
1925 _callprojs->catchall_memproj->set_req(0, top());
1926 }
1927 if (_callprojs->catchall_ioproj != nullptr) {
1928 _igvn.rehash_node_delayed(_callprojs->catchall_ioproj);
1929 _callprojs->catchall_ioproj->set_req(0, top());
1930 }
1931 #ifndef PRODUCT
1932 if (PrintEliminateAllocations) {
1933 if (alloc->is_AllocateArray()) {
1934 tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1935 } else {
1936 tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1937 }
1938 }
1939 #endif
1940 _igvn.remove_dead_node(alloc);
1941 }
1942
1943 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1944 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1945 // If initialization is performed by an array copy, any required
1946 // MemBarStoreStore was already added. If the object does not
1947 // escape no need for a MemBarStoreStore. If the object does not
1948 // escape in its initializer and memory barrier (MemBarStoreStore or
1949 // stronger) is already added at exit of initializer, also no need
1950 // for a MemBarStoreStore. Otherwise we need a MemBarStoreStore
1951 // so that stores that initialize this object can't be reordered
1952 // with a subsequent store that makes this object accessible by
1953 // other threads.
1954 // Other threads include java threads and JVM internal threads
1955 // (for example concurrent GC threads). Current concurrent GC
1956 // implementation: G1 will not scan newly created object,
1957 // so it's safe to skip storestore barrier when allocation does
1958 // not escape.
1959 if (!alloc->does_not_escape_thread() &&
1960 !alloc->is_allocation_MemBar_redundant() &&
1961 (init == nullptr || !init->is_complete_with_arraycopy())) {
1962 if (init == nullptr || init->req() < InitializeNode::RawStores) {
1963 // No InitializeNode or no stores captured by zeroing
1964 // elimination. Simply add the MemBarStoreStore after object
1965 // initialization.
1966 // What we want is to prevent the compiler and the CPU from re-ordering the stores that initialize this object
1967 // with subsequent stores to any slice. As a consequence, this MemBar should capture the entire memory state at
1968 // this point in the IR and produce a new memory state that should cover all slices. However, the Initialize node
1969 // only captures/produces a partial memory state making it complicated to insert such a MemBar. Because
1970 // re-ordering by the compiler can't happen by construction (a later Store that publishes the just allocated
1971 // object reference is indirectly control dependent on the Initialize node), preventing reordering by the CPU is
1972 // sufficient. For that a MemBar on the raw memory slice is good enough.
1973 // If init is null, this allocation does have an InitializeNode but this logic can't locate it (see comment in
1974 // PhaseMacroExpand::initialize_object()).
1975 MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxRaw);
1976 transform_later(mb);
1977
1978 mb->init_req(TypeFunc::Memory, fast_oop_rawmem);
1979 mb->init_req(TypeFunc::Control, fast_oop_ctrl);
1980 fast_oop_ctrl = new ProjNode(mb, TypeFunc::Control);
1981 transform_later(fast_oop_ctrl);
1982 fast_oop_rawmem = new ProjNode(mb, TypeFunc::Memory);
1983 transform_later(fast_oop_rawmem);
1984 } else {
1985 // Add the MemBarStoreStore after the InitializeNode so that
1986 // all stores performing the initialization that were moved
1987 // before the InitializeNode happen before the storestore
1988 // barrier.
1989
1990 Node* init_ctrl = init->proj_out_or_null(TypeFunc::Control);
1991
1992 // See comment above that explains why a raw memory MemBar is good enough.
1993 MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxRaw);
1994 transform_later(mb);
1995
1996 Node* ctrl = new ProjNode(init, TypeFunc::Control);
1997 transform_later(ctrl);
1998 Node* old_raw_mem_proj = nullptr;
1999 auto find_raw_mem = [&](ProjNode* proj) {
2000 if (C->get_alias_index(proj->adr_type()) == Compile::AliasIdxRaw) {
2001 assert(old_raw_mem_proj == nullptr, "only one expected");
2002 old_raw_mem_proj = proj;
2003 }
2004 };
2005 init->for_each_proj(find_raw_mem, TypeFunc::Memory);
2006 assert(old_raw_mem_proj != nullptr, "should have found raw mem Proj");
2007 Node* raw_mem_proj = new ProjNode(init, TypeFunc::Memory);
2008 transform_later(raw_mem_proj);
2009
2010 // The MemBarStoreStore depends on control and memory coming
2011 // from the InitializeNode
2012 mb->init_req(TypeFunc::Memory, raw_mem_proj);
2013 mb->init_req(TypeFunc::Control, ctrl);
2014
2015 ctrl = new ProjNode(mb, TypeFunc::Control);
2016 transform_later(ctrl);
2017 Node* mem = new ProjNode(mb, TypeFunc::Memory);
2018 transform_later(mem);
2019
2020 // All nodes that depended on the InitializeNode for control
2021 // and memory must now depend on the MemBarNode that itself
2022 // depends on the InitializeNode
2023 if (init_ctrl != nullptr) {
2024 _igvn.replace_node(init_ctrl, ctrl);
2025 }
2026 _igvn.replace_node(old_raw_mem_proj, mem);
2027 }
2028 }
2029 }
2030
2031 void PhaseMacroExpand::expand_dtrace_alloc_probe(AllocateNode* alloc, Node* oop,
2032 Node*& ctrl, Node*& rawmem) {
2033 if (C->env()->dtrace_alloc_probes()) {
2034 // Slow-path call
2035 int size = TypeFunc::Parms + 2;
2036 CallLeafNode *call = new CallLeafNode(OptoRuntime::dtrace_object_alloc_Type(),
2037 CAST_FROM_FN_PTR(address,
2038 static_cast<int (*)(JavaThread*, oopDesc*)>(SharedRuntime::dtrace_object_alloc)),
2039 "dtrace_object_alloc",
2040 TypeRawPtr::BOTTOM);
2041
2042 // Get base of thread-local storage area
2043 Node* thread = new ThreadLocalNode();
2044 transform_later(thread);
2045
2046 call->init_req(TypeFunc::Parms + 0, thread);
2047 call->init_req(TypeFunc::Parms + 1, oop);
2048 call->init_req(TypeFunc::Control, ctrl);
2049 call->init_req(TypeFunc::I_O , top()); // does no i/o
2050 call->init_req(TypeFunc::Memory , rawmem);
2051 call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
2052 call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
2053 transform_later(call);
2054 ctrl = new ProjNode(call, TypeFunc::Control);
2055 transform_later(ctrl);
2056 rawmem = new ProjNode(call, TypeFunc::Memory);
2057 transform_later(rawmem);
2058 }
2059 }
2060
2061 // Helper for PhaseMacroExpand::expand_allocate_common.
2062 // Initializes the newly-allocated storage.
2063 Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc,
2064 Node* control, Node* rawmem, Node* object,
2065 Node* klass_node, Node* length,
2066 Node* size_in_bytes) {
2067 InitializeNode* init = alloc->initialization();
2068 // Store the klass & mark bits
2069 Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem);
2070 if (!mark_node->is_Con()) {
2071 transform_later(mark_node);
2072 }
2073 rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
2074
2075 if (!UseCompactObjectHeaders) {
2076 rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2077 }
2078 int header_size = alloc->minimum_header_size(); // conservatively small
2079
2080 // Array length
2081 if (length != nullptr) { // Arrays need length field
2082 rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
2083 // conservatively small header size:
2084 header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
2085 if (_igvn.type(klass_node)->isa_aryklassptr()) { // we know the exact header size in most cases:
2086 BasicType elem = _igvn.type(klass_node)->is_klassptr()->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
2087 if (is_reference_type(elem, true)) {
2088 elem = T_OBJECT;
2089 }
2090 header_size = Klass::layout_helper_header_size(Klass::array_layout_helper(elem));
2091 }
2092 }
2093
2094 // Clear the object body, if necessary.
2095 if (init == nullptr) {
2096 // The init has somehow disappeared; be cautious and clear everything.
2097 //
2098 // This can happen if a node is allocated but an uncommon trap occurs
2099 // immediately. In this case, the Initialize gets associated with the
2100 // trap, and may be placed in a different (outer) loop, if the Allocate
2101 // is in a loop. If (this is rare) the inner loop gets unrolled, then
2102 // there can be two Allocates to one Initialize. The answer in all these
2103 // edge cases is safety first. It is always safe to clear immediately
2104 // within an Allocate, and then (maybe or maybe not) clear some more later.
2105 if (!(UseTLAB && ZeroTLAB)) {
2106 rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
2107 alloc->in(AllocateNode::InitValue),
2108 alloc->in(AllocateNode::RawInitValue),
2109 header_size, size_in_bytes,
2110 &_igvn);
2111 }
2112 } else {
2113 if (!init->is_complete()) {
2114 // Try to win by zeroing only what the init does not store.
2115 // We can also try to do some peephole optimizations,
2116 // such as combining some adjacent subword stores.
2117 rawmem = init->complete_stores(control, rawmem, object,
2118 header_size, size_in_bytes, &_igvn);
2119 }
2120 // We have no more use for this link, since the AllocateNode goes away:
2121 init->set_req(InitializeNode::RawAddress, top());
2122 // (If we keep the link, it just confuses the register allocator,
2123 // who thinks he sees a real use of the address by the membar.)
2124 }
2125
2126 return rawmem;
2127 }
2128
2129 // Generate prefetch instructions for next allocations.
2130 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
2131 Node*& contended_phi_rawmem,
2132 Node* old_eden_top, Node* new_eden_top,
2133 intx lines) {
2134 enum { fall_in_path = 1, pf_path = 2 };
2135 if( UseTLAB && AllocatePrefetchStyle == 2 ) {
2136 // Generate prefetch allocation with watermark check.
2137 // As an allocation hits the watermark, we will prefetch starting
2138 // at a "distance" away from watermark.
2139
2140 Node *pf_region = new RegionNode(3);
2141 Node *pf_phi_rawmem = new PhiNode( pf_region, Type::MEMORY,
2142 TypeRawPtr::BOTTOM );
2143 // I/O is used for Prefetch
2144 Node *pf_phi_abio = new PhiNode( pf_region, Type::ABIO );
2145
2146 Node *thread = new ThreadLocalNode();
2147 transform_later(thread);
2148
2149 Node *eden_pf_adr = new AddPNode( top()/*not oop*/, thread,
2150 _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) );
2151 transform_later(eden_pf_adr);
2152
2153 Node *old_pf_wm = new LoadPNode(needgc_false,
2154 contended_phi_rawmem, eden_pf_adr,
2155 TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM,
2156 MemNode::unordered);
2157 transform_later(old_pf_wm);
2158
2159 // check against new_eden_top
2160 Node *need_pf_cmp = new CmpPNode( new_eden_top, old_pf_wm );
2161 transform_later(need_pf_cmp);
2162 Node *need_pf_bol = new BoolNode( need_pf_cmp, BoolTest::ge );
2163 transform_later(need_pf_bol);
2164 IfNode *need_pf_iff = new IfNode( needgc_false, need_pf_bol,
2165 PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
2166 transform_later(need_pf_iff);
2167
2168 // true node, add prefetchdistance
2169 Node *need_pf_true = new IfTrueNode( need_pf_iff );
2170 transform_later(need_pf_true);
2171
2172 Node *need_pf_false = new IfFalseNode( need_pf_iff );
2173 transform_later(need_pf_false);
2174
2175 Node *new_pf_wmt = new AddPNode( top(), old_pf_wm,
2176 _igvn.MakeConX(AllocatePrefetchDistance) );
2177 transform_later(new_pf_wmt );
2178 new_pf_wmt->set_req(0, need_pf_true);
2179
2180 Node *store_new_wmt = new StorePNode(need_pf_true,
2181 contended_phi_rawmem, eden_pf_adr,
2182 TypeRawPtr::BOTTOM, new_pf_wmt,
2183 MemNode::unordered);
2184 transform_later(store_new_wmt);
2185
2186 // adding prefetches
2187 pf_phi_abio->init_req( fall_in_path, i_o );
2188
2189 Node *prefetch_adr;
2190 Node *prefetch;
2191 uint step_size = AllocatePrefetchStepSize;
2192 uint distance = 0;
2193
2194 for ( intx i = 0; i < lines; i++ ) {
2195 prefetch_adr = new AddPNode( old_pf_wm, new_pf_wmt,
2196 _igvn.MakeConX(distance) );
2197 transform_later(prefetch_adr);
2198 prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
2199 transform_later(prefetch);
2200 distance += step_size;
2201 i_o = prefetch;
2202 }
2203 pf_phi_abio->set_req( pf_path, i_o );
2204
2205 pf_region->init_req( fall_in_path, need_pf_false );
2206 pf_region->init_req( pf_path, need_pf_true );
2207
2208 pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem );
2209 pf_phi_rawmem->init_req( pf_path, store_new_wmt );
2210
2211 transform_later(pf_region);
2212 transform_later(pf_phi_rawmem);
2213 transform_later(pf_phi_abio);
2214
2215 needgc_false = pf_region;
2216 contended_phi_rawmem = pf_phi_rawmem;
2217 i_o = pf_phi_abio;
2218 } else if( UseTLAB && AllocatePrefetchStyle == 3 ) {
2219 // Insert a prefetch instruction for each allocation.
2220 // This code is used to generate 1 prefetch instruction per cache line.
2221
2222 // Generate several prefetch instructions.
2223 uint step_size = AllocatePrefetchStepSize;
2224 uint distance = AllocatePrefetchDistance;
2225
2226 // Next cache address.
2227 Node *cache_adr = new AddPNode(old_eden_top, old_eden_top,
2228 _igvn.MakeConX(step_size + distance));
2229 transform_later(cache_adr);
2230 cache_adr = new CastP2XNode(needgc_false, cache_adr);
2231 transform_later(cache_adr);
2232 // Address is aligned to execute prefetch to the beginning of cache line size
2233 // (it is important when BIS instruction is used on SPARC as prefetch).
2234 Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1));
2235 cache_adr = new AndXNode(cache_adr, mask);
2236 transform_later(cache_adr);
2237 cache_adr = new CastX2PNode(cache_adr);
2238 transform_later(cache_adr);
2239
2240 // Prefetch
2241 Node *prefetch = new PrefetchAllocationNode( contended_phi_rawmem, cache_adr );
2242 prefetch->set_req(0, needgc_false);
2243 transform_later(prefetch);
2244 contended_phi_rawmem = prefetch;
2245 Node *prefetch_adr;
2246 distance = step_size;
2247 for ( intx i = 1; i < lines; i++ ) {
2248 prefetch_adr = new AddPNode( cache_adr, cache_adr,
2249 _igvn.MakeConX(distance) );
2250 transform_later(prefetch_adr);
2251 prefetch = new PrefetchAllocationNode( contended_phi_rawmem, prefetch_adr );
2252 transform_later(prefetch);
2253 distance += step_size;
2254 contended_phi_rawmem = prefetch;
2255 }
2256 } else if( AllocatePrefetchStyle > 0 ) {
2257 // Insert a prefetch for each allocation only on the fast-path
2258 Node *prefetch_adr;
2259 Node *prefetch;
2260 // Generate several prefetch instructions.
2261 uint step_size = AllocatePrefetchStepSize;
2262 uint distance = AllocatePrefetchDistance;
2263 for ( intx i = 0; i < lines; i++ ) {
2264 prefetch_adr = new AddPNode( old_eden_top, new_eden_top,
2265 _igvn.MakeConX(distance) );
2266 transform_later(prefetch_adr);
2267 prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
2268 // Do not let it float too high, since if eden_top == eden_end,
2269 // both might be null.
2270 if( i == 0 ) { // Set control for first prefetch, next follows it
2271 prefetch->init_req(0, needgc_false);
2272 }
2273 transform_later(prefetch);
2274 distance += step_size;
2275 i_o = prefetch;
2276 }
2277 }
2278 return i_o;
2279 }
2280
2281
2282 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
2283 expand_allocate_common(alloc, nullptr, nullptr,
2284 OptoRuntime::new_instance_Type(),
2285 OptoRuntime::new_instance_Java(), nullptr);
2286 }
2287
2288 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
2289 Node* length = alloc->in(AllocateNode::ALength);
2290 Node* valid_length_test = alloc->in(AllocateNode::ValidLengthTest);
2291 InitializeNode* init = alloc->initialization();
2292 Node* klass_node = alloc->in(AllocateNode::KlassNode);
2293 Node* init_value = alloc->in(AllocateNode::InitValue);
2294 const TypeAryKlassPtr* ary_klass_t = _igvn.type(klass_node)->isa_aryklassptr();
2295 assert(!ary_klass_t || !ary_klass_t->klass_is_exact() || !ary_klass_t->exact_klass()->is_obj_array_klass() ||
2296 ary_klass_t->is_refined_type(), "Must be a refined array klass");
2297 const TypeFunc* slow_call_type;
2298 address slow_call_address; // Address of slow call
2299 if (init != nullptr && init->is_complete_with_arraycopy() &&
2300 ary_klass_t && ary_klass_t->elem()->isa_klassptr() == nullptr) {
2301 // Don't zero type array during slow allocation in VM since
2302 // it will be initialized later by arraycopy in compiled code.
2303 slow_call_address = OptoRuntime::new_array_nozero_Java();
2304 slow_call_type = OptoRuntime::new_array_nozero_Type();
2305 } else {
2306 slow_call_address = OptoRuntime::new_array_Java();
2307 slow_call_type = OptoRuntime::new_array_Type();
2308
2309 if (init_value == nullptr) {
2310 init_value = _igvn.zerocon(T_OBJECT);
2311 } else if (UseCompressedOops) {
2312 init_value = transform_later(new DecodeNNode(init_value, init_value->bottom_type()->make_ptr()));
2313 }
2314 }
2315 expand_allocate_common(alloc, length, init_value,
2316 slow_call_type,
2317 slow_call_address, valid_length_test);
2318 }
2319
2320 //-------------------mark_eliminated_box----------------------------------
2321 //
2322 // During EA obj may point to several objects but after few ideal graph
2323 // transformations (CCP) it may point to only one non escaping object
2324 // (but still using phi), corresponding locks and unlocks will be marked
2325 // for elimination. Later obj could be replaced with a new node (new phi)
2326 // and which does not have escape information. And later after some graph
2327 // reshape other locks and unlocks (which were not marked for elimination
2328 // before) are connected to this new obj (phi) but they still will not be
2329 // marked for elimination since new obj has no escape information.
2330 // Mark all associated (same box and obj) lock and unlock nodes for
2331 // elimination if some of them marked already.
2332 void PhaseMacroExpand::mark_eliminated_box(Node* box, Node* obj) {
2333 BoxLockNode* oldbox = box->as_BoxLock();
2334 if (oldbox->is_eliminated()) {
2335 return; // This BoxLock node was processed already.
2336 }
2337 assert(!oldbox->is_unbalanced(), "this should not be called for unbalanced region");
2338 // New implementation (EliminateNestedLocks) has separate BoxLock
2339 // node for each locked region so mark all associated locks/unlocks as
2340 // eliminated even if different objects are referenced in one locked region
2341 // (for example, OSR compilation of nested loop inside locked scope).
2342 if (EliminateNestedLocks ||
2343 oldbox->as_BoxLock()->is_simple_lock_region(nullptr, obj, nullptr)) {
2344 // Box is used only in one lock region. Mark this box as eliminated.
2345 oldbox->set_local(); // This verifies correct state of BoxLock
2346 _igvn.hash_delete(oldbox);
2347 oldbox->set_eliminated(); // This changes box's hash value
2348 _igvn.hash_insert(oldbox);
2349
2350 for (uint i = 0; i < oldbox->outcnt(); i++) {
2351 Node* u = oldbox->raw_out(i);
2352 if (u->is_AbstractLock() && !u->as_AbstractLock()->is_non_esc_obj()) {
2353 AbstractLockNode* alock = u->as_AbstractLock();
2354 // Check lock's box since box could be referenced by Lock's debug info.
2355 if (alock->box_node() == oldbox) {
2356 // Mark eliminated all related locks and unlocks.
2357 #ifdef ASSERT
2358 alock->log_lock_optimization(C, "eliminate_lock_set_non_esc4");
2359 #endif
2360 alock->set_non_esc_obj();
2361 }
2362 }
2363 }
2364 return;
2365 }
2366
2367 // Create new "eliminated" BoxLock node and use it in monitor debug info
2368 // instead of oldbox for the same object.
2369 BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
2370
2371 // Note: BoxLock node is marked eliminated only here and it is used
2372 // to indicate that all associated lock and unlock nodes are marked
2373 // for elimination.
2374 newbox->set_local(); // This verifies correct state of BoxLock
2375 newbox->set_eliminated();
2376 transform_later(newbox);
2377
2378 // Replace old box node with new box for all users of the same object.
2379 for (uint i = 0; i < oldbox->outcnt();) {
2380 bool next_edge = true;
2381
2382 Node* u = oldbox->raw_out(i);
2383 if (u->is_AbstractLock()) {
2384 AbstractLockNode* alock = u->as_AbstractLock();
2385 if (alock->box_node() == oldbox && alock->obj_node()->eqv_uncast(obj)) {
2386 // Replace Box and mark eliminated all related locks and unlocks.
2387 #ifdef ASSERT
2388 alock->log_lock_optimization(C, "eliminate_lock_set_non_esc5");
2389 #endif
2390 alock->set_non_esc_obj();
2391 _igvn.rehash_node_delayed(alock);
2392 alock->set_box_node(newbox);
2393 next_edge = false;
2394 }
2395 }
2396 if (u->is_FastLock() && u->as_FastLock()->obj_node()->eqv_uncast(obj)) {
2397 FastLockNode* flock = u->as_FastLock();
2398 assert(flock->box_node() == oldbox, "sanity");
2399 _igvn.rehash_node_delayed(flock);
2400 flock->set_box_node(newbox);
2401 next_edge = false;
2402 }
2403
2404 // Replace old box in monitor debug info.
2405 if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
2406 SafePointNode* sfn = u->as_SafePoint();
2407 JVMState* youngest_jvms = sfn->jvms();
2408 int max_depth = youngest_jvms->depth();
2409 for (int depth = 1; depth <= max_depth; depth++) {
2410 JVMState* jvms = youngest_jvms->of_depth(depth);
2411 int num_mon = jvms->nof_monitors();
2412 // Loop over monitors
2413 for (int idx = 0; idx < num_mon; idx++) {
2414 Node* obj_node = sfn->monitor_obj(jvms, idx);
2415 Node* box_node = sfn->monitor_box(jvms, idx);
2416 if (box_node == oldbox && obj_node->eqv_uncast(obj)) {
2417 int j = jvms->monitor_box_offset(idx);
2418 _igvn.replace_input_of(u, j, newbox);
2419 next_edge = false;
2420 }
2421 }
2422 }
2423 }
2424 if (next_edge) i++;
2425 }
2426 }
2427
2428 //-----------------------mark_eliminated_locking_nodes-----------------------
2429 void PhaseMacroExpand::mark_eliminated_locking_nodes(AbstractLockNode *alock) {
2430 if (!alock->is_balanced()) {
2431 return; // Can't do any more elimination for this locking region
2432 }
2433 if (EliminateNestedLocks) {
2434 if (alock->is_nested()) {
2435 assert(alock->box_node()->as_BoxLock()->is_eliminated(), "sanity");
2436 return;
2437 } else if (!alock->is_non_esc_obj()) { // Not eliminated or coarsened
2438 // Only Lock node has JVMState needed here.
2439 // Not that preceding claim is documented anywhere else.
2440 if (alock->jvms() != nullptr) {
2441 if (alock->as_Lock()->is_nested_lock_region()) {
2442 // Mark eliminated related nested locks and unlocks.
2443 Node* obj = alock->obj_node();
2444 BoxLockNode* box_node = alock->box_node()->as_BoxLock();
2445 assert(!box_node->is_eliminated(), "should not be marked yet");
2446 // Note: BoxLock node is marked eliminated only here
2447 // and it is used to indicate that all associated lock
2448 // and unlock nodes are marked for elimination.
2449 box_node->set_eliminated(); // Box's hash is always NO_HASH here
2450 for (uint i = 0; i < box_node->outcnt(); i++) {
2451 Node* u = box_node->raw_out(i);
2452 if (u->is_AbstractLock()) {
2453 alock = u->as_AbstractLock();
2454 if (alock->box_node() == box_node) {
2455 // Verify that this Box is referenced only by related locks.
2456 assert(alock->obj_node()->eqv_uncast(obj), "");
2457 // Mark all related locks and unlocks.
2458 #ifdef ASSERT
2459 alock->log_lock_optimization(C, "eliminate_lock_set_nested");
2460 #endif
2461 alock->set_nested();
2462 }
2463 }
2464 }
2465 } else {
2466 #ifdef ASSERT
2467 alock->log_lock_optimization(C, "eliminate_lock_NOT_nested_lock_region");
2468 if (C->log() != nullptr)
2469 alock->as_Lock()->is_nested_lock_region(C); // rerun for debugging output
2470 #endif
2471 }
2472 }
2473 return;
2474 }
2475 // Process locks for non escaping object
2476 assert(alock->is_non_esc_obj(), "");
2477 } // EliminateNestedLocks
2478
2479 if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2480 // Look for all locks of this object and mark them and
2481 // corresponding BoxLock nodes as eliminated.
2482 Node* obj = alock->obj_node();
2483 for (uint j = 0; j < obj->outcnt(); j++) {
2484 Node* o = obj->raw_out(j);
2485 if (o->is_AbstractLock() &&
2486 o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2487 alock = o->as_AbstractLock();
2488 Node* box = alock->box_node();
2489 // Replace old box node with new eliminated box for all users
2490 // of the same object and mark related locks as eliminated.
2491 mark_eliminated_box(box, obj);
2492 }
2493 }
2494 }
2495 }
2496
2497 // we have determined that this lock/unlock can be eliminated, we simply
2498 // eliminate the node without expanding it.
2499 //
2500 // Note: The membar's associated with the lock/unlock are currently not
2501 // eliminated. This should be investigated as a future enhancement.
2502 //
2503 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2504
2505 if (!alock->is_eliminated()) {
2506 return false;
2507 }
2508 #ifdef ASSERT
2509 if (!alock->is_coarsened()) {
2510 // Check that new "eliminated" BoxLock node is created.
2511 BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2512 assert(oldbox->is_eliminated(), "should be done already");
2513 }
2514 #endif
2515
2516 alock->log_lock_optimization(C, "eliminate_lock");
2517
2518 #ifndef PRODUCT
2519 if (PrintEliminateLocks) {
2520 tty->print_cr("++++ Eliminated: %d %s '%s'", alock->_idx, (alock->is_Lock() ? "Lock" : "Unlock"), alock->kind_as_string());
2521 }
2522 #endif
2523
2524 Node* mem = alock->in(TypeFunc::Memory);
2525 Node* ctrl = alock->in(TypeFunc::Control);
2526 guarantee(ctrl != nullptr, "missing control projection, cannot replace_node() with null");
2527
2528 _callprojs = alock->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2529 // There are 2 projections from the lock. The lock node will
2530 // be deleted when its last use is subsumed below.
2531 assert(alock->outcnt() == 2 &&
2532 _callprojs->fallthrough_proj != nullptr &&
2533 _callprojs->fallthrough_memproj != nullptr,
2534 "Unexpected projections from Lock/Unlock");
2535
2536 Node* fallthroughproj = _callprojs->fallthrough_proj;
2537 Node* memproj_fallthrough = _callprojs->fallthrough_memproj;
2538
2539 // The memory projection from a lock/unlock is RawMem
2540 // The input to a Lock is merged memory, so extract its RawMem input
2541 // (unless the MergeMem has been optimized away.)
2542 if (alock->is_Lock()) {
2543 // Search for MemBarAcquireLock node and delete it also.
2544 MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2545 assert(membar != nullptr && membar->Opcode() == Op_MemBarAcquireLock, "");
2546 Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2547 Node* memproj = membar->proj_out(TypeFunc::Memory);
2548 _igvn.replace_node(ctrlproj, fallthroughproj);
2549 _igvn.replace_node(memproj, memproj_fallthrough);
2550
2551 // Delete FastLock node also if this Lock node is unique user
2552 // (a loop peeling may clone a Lock node).
2553 Node* flock = alock->as_Lock()->fastlock_node();
2554 if (flock->outcnt() == 1) {
2555 assert(flock->unique_out() == alock, "sanity");
2556 _igvn.replace_node(flock, top());
2557 }
2558 }
2559
2560 // Search for MemBarReleaseLock node and delete it also.
2561 if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2562 MemBarNode* membar = ctrl->in(0)->as_MemBar();
2563 assert(membar->Opcode() == Op_MemBarReleaseLock &&
2564 mem->is_Proj() && membar == mem->in(0), "");
2565 _igvn.replace_node(fallthroughproj, ctrl);
2566 _igvn.replace_node(memproj_fallthrough, mem);
2567 fallthroughproj = ctrl;
2568 memproj_fallthrough = mem;
2569 ctrl = membar->in(TypeFunc::Control);
2570 mem = membar->in(TypeFunc::Memory);
2571 }
2572
2573 _igvn.replace_node(fallthroughproj, ctrl);
2574 _igvn.replace_node(memproj_fallthrough, mem);
2575 return true;
2576 }
2577
2578
2579 //------------------------------expand_lock_node----------------------
2580 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
2581
2582 Node* ctrl = lock->in(TypeFunc::Control);
2583 Node* mem = lock->in(TypeFunc::Memory);
2584 Node* obj = lock->obj_node();
2585 Node* box = lock->box_node();
2586 Node* flock = lock->fastlock_node();
2587
2588 assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2589
2590 // Make the merge point
2591 Node *region;
2592 Node *mem_phi;
2593 Node *slow_path;
2594
2595 region = new RegionNode(3);
2596 // create a Phi for the memory state
2597 mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2598
2599 // Optimize test; set region slot 2
2600 slow_path = opt_bits_test(ctrl, region, 2, flock);
2601 mem_phi->init_req(2, mem);
2602
2603 // Make slow path call
2604 CallNode* call = make_slow_call(lock, OptoRuntime::complete_monitor_enter_Type(),
2605 OptoRuntime::complete_monitor_locking_Java(), nullptr, slow_path,
2606 obj, box, nullptr);
2607
2608 _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2609
2610 // Slow path can only throw asynchronous exceptions, which are always
2611 // de-opted. So the compiler thinks the slow-call can never throw an
2612 // exception. If it DOES throw an exception we would need the debug
2613 // info removed first (since if it throws there is no monitor).
2614 assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr &&
2615 _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock");
2616
2617 // Capture slow path
2618 // disconnect fall-through projection from call and create a new one
2619 // hook up users of fall-through projection to region
2620 Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2621 transform_later(slow_ctrl);
2622 _igvn.hash_delete(_callprojs->fallthrough_proj);
2623 _callprojs->fallthrough_proj->disconnect_inputs(C);
2624 region->init_req(1, slow_ctrl);
2625 // region inputs are now complete
2626 transform_later(region);
2627 _igvn.replace_node(_callprojs->fallthrough_proj, region);
2628
2629 Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2630
2631 mem_phi->init_req(1, memproj);
2632
2633 transform_later(mem_phi);
2634
2635 _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2636 }
2637
2638 //------------------------------expand_unlock_node----------------------
2639 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2640
2641 Node* ctrl = unlock->in(TypeFunc::Control);
2642 Node* mem = unlock->in(TypeFunc::Memory);
2643 Node* obj = unlock->obj_node();
2644 Node* box = unlock->box_node();
2645
2646 assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2647
2648 // No need for a null check on unlock
2649
2650 // Make the merge point
2651 Node *region;
2652 Node *mem_phi;
2653
2654 region = new RegionNode(3);
2655 // create a Phi for the memory state
2656 mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2657
2658 FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2659 funlock = transform_later( funlock )->as_FastUnlock();
2660 // Optimize test; set region slot 2
2661 Node *slow_path = opt_bits_test(ctrl, region, 2, funlock);
2662 Node *thread = transform_later(new ThreadLocalNode());
2663
2664 CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2665 CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2666 "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2667
2668 _callprojs = call->extract_projections(false /*separate_io_proj*/, false /*do_asserts*/);
2669 assert(_callprojs->fallthrough_ioproj == nullptr && _callprojs->catchall_ioproj == nullptr &&
2670 _callprojs->catchall_memproj == nullptr && _callprojs->catchall_catchproj == nullptr, "Unexpected projection from Lock");
2671
2672 // No exceptions for unlocking
2673 // Capture slow path
2674 // disconnect fall-through projection from call and create a new one
2675 // hook up users of fall-through projection to region
2676 Node *slow_ctrl = _callprojs->fallthrough_proj->clone();
2677 transform_later(slow_ctrl);
2678 _igvn.hash_delete(_callprojs->fallthrough_proj);
2679 _callprojs->fallthrough_proj->disconnect_inputs(C);
2680 region->init_req(1, slow_ctrl);
2681 // region inputs are now complete
2682 transform_later(region);
2683 _igvn.replace_node(_callprojs->fallthrough_proj, region);
2684
2685 Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2686 mem_phi->init_req(1, memproj );
2687 mem_phi->init_req(2, mem);
2688 transform_later(mem_phi);
2689
2690 _igvn.replace_node(_callprojs->fallthrough_memproj, mem_phi);
2691 }
2692
2693 // An inline type might be returned from the call but we don't know its
2694 // type. Either we get a buffered inline type (and nothing needs to be done)
2695 // or one of the values being returned is the klass of the inline type
2696 // and we need to allocate an inline type instance of that type and
2697 // initialize it with other values being returned. In that case, we
2698 // first try a fast path allocation and initialize the value with the
2699 // inline klass's pack handler or we fall back to a runtime call.
2700 void PhaseMacroExpand::expand_mh_intrinsic_return(CallStaticJavaNode* call) {
2701 assert(call->method()->is_method_handle_intrinsic(), "must be a method handle intrinsic call");
2702 Node* ret = call->proj_out_or_null(TypeFunc::Parms);
2703 if (ret == nullptr) {
2704 return;
2705 }
2706 const TypeFunc* tf = call->_tf;
2707 const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc();
2708 const TypeFunc* new_tf = TypeFunc::make(tf->domain_sig(), tf->domain_cc(), tf->range_sig(), domain);
2709 call->_tf = new_tf;
2710 // Make sure the change of type is applied before projections are processed by igvn
2711 _igvn.set_type(call, call->Value(&_igvn));
2712 _igvn.set_type(ret, ret->Value(&_igvn));
2713
2714 // Before any new projection is added:
2715 CallProjections* projs = call->extract_projections(true, true);
2716
2717 // Create temporary hook nodes that will be replaced below.
2718 // Add an input to prevent hook nodes from being dead.
2719 Node* ctl = new Node(call);
2720 Node* mem = new Node(ctl);
2721 Node* io = new Node(ctl);
2722 Node* ex_ctl = new Node(ctl);
2723 Node* ex_mem = new Node(ctl);
2724 Node* ex_io = new Node(ctl);
2725 Node* res = new Node(ctl);
2726
2727 // Allocate a new buffered inline type only if a new one is not returned
2728 Node* cast = transform_later(new CastP2XNode(ctl, res));
2729 Node* mask = MakeConX(0x1);
2730 Node* masked = transform_later(new AndXNode(cast, mask));
2731 Node* cmp = transform_later(new CmpXNode(masked, mask));
2732 Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
2733 IfNode* allocation_iff = new IfNode(ctl, bol, PROB_MAX, COUNT_UNKNOWN);
2734 transform_later(allocation_iff);
2735 Node* allocation_ctl = transform_later(new IfTrueNode(allocation_iff));
2736 Node* no_allocation_ctl = transform_later(new IfFalseNode(allocation_iff));
2737 Node* no_allocation_res = transform_later(new CheckCastPPNode(no_allocation_ctl, res, TypeInstPtr::BOTTOM));
2738
2739 // Try to allocate a new buffered inline instance either from TLAB or eden space
2740 Node* needgc_ctrl = nullptr; // needgc means slowcase, i.e. allocation failed
2741 CallLeafNoFPNode* handler_call;
2742 const bool alloc_in_place = UseTLAB;
2743 if (alloc_in_place) {
2744 Node* fast_oop_ctrl = nullptr;
2745 Node* fast_oop_rawmem = nullptr;
2746 Node* mask2 = MakeConX(-2);
2747 Node* masked2 = transform_later(new AndXNode(cast, mask2));
2748 Node* rawklassptr = transform_later(new CastX2PNode(masked2));
2749 Node* klass_node = transform_later(new CheckCastPPNode(allocation_ctl, rawklassptr, TypeInstKlassPtr::OBJECT_OR_NULL));
2750 Node* layout_val = make_load(nullptr, mem, klass_node, in_bytes(Klass::layout_helper_offset()), TypeInt::INT, T_INT);
2751 Node* size_in_bytes = ConvI2X(layout_val);
2752 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2753 Node* fast_oop = bs->obj_allocate(this, mem, allocation_ctl, size_in_bytes, io, needgc_ctrl,
2754 fast_oop_ctrl, fast_oop_rawmem,
2755 AllocateInstancePrefetchLines);
2756 // Allocation succeed, initialize buffered inline instance header firstly,
2757 // and then initialize its fields with an inline class specific handler
2758 Node* mark_word_node;
2759 if (UseCompactObjectHeaders) {
2760 // COH: We need to load the prototype from the klass at runtime since it encodes the klass pointer already.
2761 mark_word_node = make_load(fast_oop_ctrl, fast_oop_rawmem, klass_node, in_bytes(Klass::prototype_header_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2762 } else {
2763 // Otherwise, use the static prototype.
2764 mark_word_node = makecon(TypeRawPtr::make((address)markWord::inline_type_prototype().value()));
2765 }
2766
2767 fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::mark_offset_in_bytes(), mark_word_node, T_ADDRESS);
2768 if (!UseCompactObjectHeaders) {
2769 // COH: Everything is encoded in the mark word, so nothing left to do.
2770 fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2771 if (UseCompressedClassPointers) {
2772 fast_oop_rawmem = make_store(fast_oop_ctrl, fast_oop_rawmem, fast_oop, oopDesc::klass_gap_offset_in_bytes(), intcon(0), T_INT);
2773 }
2774 }
2775 Node* members = make_load(fast_oop_ctrl, fast_oop_rawmem, klass_node, in_bytes(InlineKlass::adr_members_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2776 Node* pack_handler = make_load(fast_oop_ctrl, fast_oop_rawmem, members, in_bytes(InlineKlass::pack_handler_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2777 handler_call = new CallLeafNoFPNode(OptoRuntime::pack_inline_type_Type(),
2778 nullptr,
2779 "pack handler",
2780 TypeRawPtr::BOTTOM);
2781 handler_call->init_req(TypeFunc::Control, fast_oop_ctrl);
2782 handler_call->init_req(TypeFunc::Memory, fast_oop_rawmem);
2783 handler_call->init_req(TypeFunc::I_O, top());
2784 handler_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2785 handler_call->init_req(TypeFunc::ReturnAdr, top());
2786 handler_call->init_req(TypeFunc::Parms, pack_handler);
2787 handler_call->init_req(TypeFunc::Parms+1, fast_oop);
2788 } else {
2789 needgc_ctrl = allocation_ctl;
2790 }
2791
2792 // Allocation failed, fall back to a runtime call
2793 CallStaticJavaNode* slow_call = new CallStaticJavaNode(OptoRuntime::store_inline_type_fields_Type(),
2794 StubRoutines::store_inline_type_fields_to_buf(),
2795 "store_inline_type_fields",
2796 TypePtr::BOTTOM);
2797 slow_call->init_req(TypeFunc::Control, needgc_ctrl);
2798 slow_call->init_req(TypeFunc::Memory, mem);
2799 slow_call->init_req(TypeFunc::I_O, io);
2800 slow_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2801 slow_call->init_req(TypeFunc::ReturnAdr, call->in(TypeFunc::ReturnAdr));
2802 slow_call->init_req(TypeFunc::Parms, res);
2803
2804 Node* slow_ctl = transform_later(new ProjNode(slow_call, TypeFunc::Control));
2805 Node* slow_mem = transform_later(new ProjNode(slow_call, TypeFunc::Memory));
2806 Node* slow_io = transform_later(new ProjNode(slow_call, TypeFunc::I_O));
2807 Node* slow_res = transform_later(new ProjNode(slow_call, TypeFunc::Parms));
2808 Node* slow_catc = transform_later(new CatchNode(slow_ctl, slow_io, 2));
2809 Node* slow_norm = transform_later(new CatchProjNode(slow_catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci));
2810 Node* slow_excp = transform_later(new CatchProjNode(slow_catc, CatchProjNode::catch_all_index, CatchProjNode::no_handler_bci));
2811
2812 Node* ex_r = new RegionNode(3);
2813 Node* ex_mem_phi = new PhiNode(ex_r, Type::MEMORY, TypePtr::BOTTOM);
2814 Node* ex_io_phi = new PhiNode(ex_r, Type::ABIO);
2815 ex_r->init_req(1, slow_excp);
2816 ex_mem_phi->init_req(1, slow_mem);
2817 ex_io_phi->init_req(1, slow_io);
2818 ex_r->init_req(2, ex_ctl);
2819 ex_mem_phi->init_req(2, ex_mem);
2820 ex_io_phi->init_req(2, ex_io);
2821 transform_later(ex_r);
2822 transform_later(ex_mem_phi);
2823 transform_later(ex_io_phi);
2824
2825 // We don't know how many values are returned. This assumes the
2826 // worst case, that all available registers are used.
2827 for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2828 if (domain->field_at(i) == Type::HALF) {
2829 slow_call->init_req(i, top());
2830 if (alloc_in_place) {
2831 handler_call->init_req(i+1, top());
2832 }
2833 continue;
2834 }
2835 Node* proj = transform_later(new ProjNode(call, i));
2836 slow_call->init_req(i, proj);
2837 if (alloc_in_place) {
2838 handler_call->init_req(i+1, proj);
2839 }
2840 }
2841 // We can safepoint at that new call
2842 slow_call->copy_call_debug_info(&_igvn, call);
2843 transform_later(slow_call);
2844 if (alloc_in_place) {
2845 transform_later(handler_call);
2846 }
2847
2848 Node* fast_ctl = nullptr;
2849 Node* fast_res = nullptr;
2850 MergeMemNode* fast_mem = nullptr;
2851 if (alloc_in_place) {
2852 fast_ctl = transform_later(new ProjNode(handler_call, TypeFunc::Control));
2853 Node* rawmem = transform_later(new ProjNode(handler_call, TypeFunc::Memory));
2854 fast_res = transform_later(new ProjNode(handler_call, TypeFunc::Parms));
2855 fast_mem = MergeMemNode::make(mem);
2856 fast_mem->set_memory_at(Compile::AliasIdxRaw, rawmem);
2857 transform_later(fast_mem);
2858 }
2859
2860 Node* r = new RegionNode(alloc_in_place ? 4 : 3);
2861 Node* mem_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM);
2862 Node* io_phi = new PhiNode(r, Type::ABIO);
2863 Node* res_phi = new PhiNode(r, TypeInstPtr::BOTTOM);
2864 r->init_req(1, no_allocation_ctl);
2865 mem_phi->init_req(1, mem);
2866 io_phi->init_req(1, io);
2867 res_phi->init_req(1, no_allocation_res);
2868 r->init_req(2, slow_norm);
2869 mem_phi->init_req(2, slow_mem);
2870 io_phi->init_req(2, slow_io);
2871 res_phi->init_req(2, slow_res);
2872 if (alloc_in_place) {
2873 r->init_req(3, fast_ctl);
2874 mem_phi->init_req(3, fast_mem);
2875 io_phi->init_req(3, io);
2876 res_phi->init_req(3, fast_res);
2877 }
2878 transform_later(r);
2879 transform_later(mem_phi);
2880 transform_later(io_phi);
2881 transform_later(res_phi);
2882
2883 // Do not let stores that initialize this buffer be reordered with a subsequent
2884 // store that would make this buffer accessible by other threads.
2885 MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
2886 transform_later(mb);
2887 mb->init_req(TypeFunc::Memory, mem_phi);
2888 mb->init_req(TypeFunc::Control, r);
2889 r = new ProjNode(mb, TypeFunc::Control);
2890 transform_later(r);
2891 mem_phi = new ProjNode(mb, TypeFunc::Memory);
2892 transform_later(mem_phi);
2893
2894 assert(projs->nb_resproj == 1, "unexpected number of results");
2895 _igvn.replace_in_uses(projs->fallthrough_catchproj, r);
2896 _igvn.replace_in_uses(projs->fallthrough_memproj, mem_phi);
2897 _igvn.replace_in_uses(projs->fallthrough_ioproj, io_phi);
2898 _igvn.replace_in_uses(projs->resproj[0], res_phi);
2899 _igvn.replace_in_uses(projs->catchall_catchproj, ex_r);
2900 _igvn.replace_in_uses(projs->catchall_memproj, ex_mem_phi);
2901 _igvn.replace_in_uses(projs->catchall_ioproj, ex_io_phi);
2902 // The CatchNode should not use the ex_io_phi. Re-connect it to the catchall_ioproj.
2903 Node* cn = projs->fallthrough_catchproj->in(0);
2904 _igvn.replace_input_of(cn, 1, projs->catchall_ioproj);
2905
2906 _igvn.replace_node(ctl, projs->fallthrough_catchproj);
2907 _igvn.replace_node(mem, projs->fallthrough_memproj);
2908 _igvn.replace_node(io, projs->fallthrough_ioproj);
2909 _igvn.replace_node(res, projs->resproj[0]);
2910 _igvn.replace_node(ex_ctl, projs->catchall_catchproj);
2911 _igvn.replace_node(ex_mem, projs->catchall_memproj);
2912 _igvn.replace_node(ex_io, projs->catchall_ioproj);
2913 }
2914
2915 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2916 assert(check->in(SubTypeCheckNode::Control) == nullptr, "should be pinned");
2917 Node* bol = check->unique_out();
2918 Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2919 Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2920 assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2921
2922 for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2923 Node* iff = bol->last_out(i);
2924 assert(iff->is_If(), "where's the if?");
2925
2926 if (iff->in(0)->is_top()) {
2927 _igvn.replace_input_of(iff, 1, C->top());
2928 continue;
2929 }
2930
2931 IfTrueNode* iftrue = iff->as_If()->true_proj();
2932 IfFalseNode* iffalse = iff->as_If()->false_proj();
2933 Node* ctrl = iff->in(0);
2934
2935 Node* subklass = nullptr;
2936 if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2937 subklass = obj_or_subklass;
2938 } else {
2939 Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2940 subklass = _igvn.transform(LoadKlassNode::make(_igvn, C->immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
2941 }
2942
2943 Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, nullptr, _igvn, check->method(), check->bci());
2944
2945 _igvn.replace_input_of(iff, 0, C->top());
2946 _igvn.replace_node(iftrue, not_subtype_ctrl);
2947 _igvn.replace_node(iffalse, ctrl);
2948 }
2949 _igvn.replace_node(check, C->top());
2950 }
2951
2952 // FlatArrayCheckNode (array1 array2 ...) is expanded into:
2953 //
2954 // long mark = array1.mark | array2.mark | ...;
2955 // long locked_bit = markWord::unlocked_value & array1.mark & array2.mark & ...;
2956 // if (locked_bit == 0) {
2957 // // One array is locked, load prototype header from the klass
2958 // mark = array1.klass.proto | array2.klass.proto | ...
2959 // }
2960 // if ((mark & markWord::flat_array_bit_in_place) == 0) {
2961 // ...
2962 // }
2963 void PhaseMacroExpand::expand_flatarraycheck_node(FlatArrayCheckNode* check) {
2964 bool array_inputs = _igvn.type(check->in(FlatArrayCheckNode::ArrayOrKlass))->isa_oopptr() != nullptr;
2965 if (array_inputs) {
2966 Node* mark = MakeConX(0);
2967 Node* locked_bit = MakeConX(markWord::unlocked_value);
2968 Node* mem = check->in(FlatArrayCheckNode::Memory);
2969 for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
2970 Node* ary = check->in(i);
2971 const TypeOopPtr* t = _igvn.type(ary)->isa_oopptr();
2972 assert(t != nullptr, "Mixing array and klass inputs");
2973 assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
2974 Node* mark_adr = basic_plus_adr(ary, oopDesc::mark_offset_in_bytes());
2975 Node* mark_load = _igvn.transform(LoadNode::make(_igvn, nullptr, mem, mark_adr, mark_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered));
2976 mark = _igvn.transform(new OrXNode(mark, mark_load));
2977 locked_bit = _igvn.transform(new AndXNode(locked_bit, mark_load));
2978 }
2979 assert(!mark->is_Con(), "Should have been optimized out");
2980 Node* cmp = _igvn.transform(new CmpXNode(locked_bit, MakeConX(0)));
2981 Node* is_unlocked = _igvn.transform(new BoolNode(cmp, BoolTest::ne));
2982
2983 // BoolNode might be shared, replace each if user
2984 Node* old_bol = check->unique_out();
2985 assert(old_bol->is_Bool() && old_bol->as_Bool()->_test._test == BoolTest::ne, "unexpected condition");
2986 for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) {
2987 IfNode* old_iff = old_bol->last_out(i)->as_If();
2988 Node* ctrl = old_iff->in(0);
2989 RegionNode* region = new RegionNode(3);
2990 Node* mark_phi = new PhiNode(region, TypeX_X);
2991
2992 // Check if array is unlocked
2993 IfNode* iff = _igvn.transform(new IfNode(ctrl, is_unlocked, PROB_MAX, COUNT_UNKNOWN))->as_If();
2994
2995 // Unlocked: Use bits from mark word
2996 region->init_req(1, _igvn.transform(new IfTrueNode(iff)));
2997 mark_phi->init_req(1, mark);
2998
2999 // Locked: Load prototype header from klass
3000 ctrl = _igvn.transform(new IfFalseNode(iff));
3001 Node* proto = MakeConX(0);
3002 for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
3003 Node* ary = check->in(i);
3004 // Make loads control dependent to make sure they are only executed if array is locked
3005 Node* klass_adr = basic_plus_adr(ary, oopDesc::klass_offset_in_bytes());
3006 Node* klass = _igvn.transform(LoadKlassNode::make(_igvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
3007 Node* proto_adr = basic_plus_adr(klass, in_bytes(Klass::prototype_header_offset()));
3008 Node* proto_load = _igvn.transform(LoadNode::make(_igvn, ctrl, C->immutable_memory(), proto_adr, proto_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered));
3009 proto = _igvn.transform(new OrXNode(proto, proto_load));
3010 }
3011 region->init_req(2, ctrl);
3012 mark_phi->init_req(2, proto);
3013
3014 // Check if flat array bits are set
3015 Node* mask = MakeConX(markWord::flat_array_bit_in_place);
3016 Node* masked = _igvn.transform(new AndXNode(_igvn.transform(mark_phi), mask));
3017 cmp = _igvn.transform(new CmpXNode(masked, MakeConX(0)));
3018 Node* is_not_flat = _igvn.transform(new BoolNode(cmp, BoolTest::eq));
3019
3020 ctrl = _igvn.transform(region);
3021 iff = _igvn.transform(new IfNode(ctrl, is_not_flat, PROB_MAX, COUNT_UNKNOWN))->as_If();
3022 _igvn.replace_node(old_iff, iff);
3023 }
3024 _igvn.replace_node(check, C->top());
3025 } else {
3026 // Fall back to layout helper check
3027 Node* lhs = intcon(0);
3028 for (uint i = FlatArrayCheckNode::ArrayOrKlass; i < check->req(); ++i) {
3029 Node* array_or_klass = check->in(i);
3030 Node* klass = nullptr;
3031 const TypePtr* t = _igvn.type(array_or_klass)->is_ptr();
3032 assert(!t->is_flat() && !t->is_not_flat(), "Should have been optimized out");
3033 if (t->isa_oopptr() != nullptr) {
3034 Node* klass_adr = basic_plus_adr(array_or_klass, oopDesc::klass_offset_in_bytes());
3035 klass = transform_later(LoadKlassNode::make(_igvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
3036 } else {
3037 assert(t->isa_klassptr(), "Unexpected input type");
3038 klass = array_or_klass;
3039 }
3040 Node* lh_addr = basic_plus_adr(klass, in_bytes(Klass::layout_helper_offset()));
3041 Node* lh_val = _igvn.transform(LoadNode::make(_igvn, nullptr, C->immutable_memory(), lh_addr, lh_addr->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered));
3042 lhs = _igvn.transform(new OrINode(lhs, lh_val));
3043 }
3044 Node* masked = transform_later(new AndINode(lhs, intcon(Klass::_lh_array_tag_flat_value_bit_inplace)));
3045 Node* cmp = transform_later(new CmpINode(masked, intcon(0)));
3046 Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
3047 Node* m2b = transform_later(new Conv2BNode(masked));
3048 // The matcher expects the input to If/CMove nodes to be produced by a Bool(CmpI..)
3049 // pattern, but the input to other potential users (e.g. Phi) to be some
3050 // other pattern (e.g. a Conv2B node, possibly idealized as a CMoveI).
3051 Node* old_bol = check->unique_out();
3052 for (DUIterator_Last imin, i = old_bol->last_outs(imin); i >= imin; --i) {
3053 Node* user = old_bol->last_out(i);
3054 for (uint j = 0; j < user->req(); j++) {
3055 Node* n = user->in(j);
3056 if (n == old_bol) {
3057 _igvn.replace_input_of(user, j, (user->is_If() || user->is_CMove()) ? bol : m2b);
3058 }
3059 }
3060 }
3061 _igvn.replace_node(check, C->top());
3062 }
3063 }
3064
3065 // Perform refining of strip mined loop nodes in the macro nodes list.
3066 void PhaseMacroExpand::refine_strip_mined_loop_macro_nodes() {
3067 for (int i = C->macro_count(); i > 0; i--) {
3068 Node* n = C->macro_node(i - 1);
3069 if (n->is_OuterStripMinedLoop()) {
3070 n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
3071 }
3072 }
3073 }
3074
3075 //---------------------------eliminate_macro_nodes----------------------
3076 // Eliminate scalar replaced allocations and associated locks.
3077 void PhaseMacroExpand::eliminate_macro_nodes(bool eliminate_locks) {
3078 if (C->macro_count() == 0) {
3079 return;
3080 }
3081
3082 if (StressMacroElimination) {
3083 C->shuffle_macro_nodes();
3084 }
3085 NOT_PRODUCT(int membar_before = count_MemBar(C);)
3086
3087 int iteration = 0;
3088 while (C->macro_count() > 0) {
3089 if (iteration++ > 100) {
3090 assert(false, "Too slow convergence of macro elimination");
3091 break;
3092 }
3093
3094 // Postpone lock elimination to after EA when most allocations are eliminated
3095 // because they might block lock elimination if their escape state isn't
3096 // determined yet and we only got one chance at eliminating the lock.
3097 if (eliminate_locks) {
3098 // Before elimination may re-mark (change to Nested or NonEscObj)
3099 // all associated (same box and obj) lock and unlock nodes.
3100 int cnt = C->macro_count();
3101 for (int i=0; i < cnt; i++) {
3102 Node *n = C->macro_node(i);
3103 if (n->is_AbstractLock()) { // Lock and Unlock nodes
3104 mark_eliminated_locking_nodes(n->as_AbstractLock());
3105 }
3106 }
3107 // Re-marking may break consistency of Coarsened locks.
3108 if (!C->coarsened_locks_consistent()) {
3109 return; // recompile without Coarsened locks if broken
3110 } else {
3111 // After coarsened locks are eliminated locking regions
3112 // become unbalanced. We should not execute any more
3113 // locks elimination optimizations on them.
3114 C->mark_unbalanced_boxes();
3115 }
3116 }
3117
3118 bool progress = false;
3119 for (int i = C->macro_count(); i > 0; i = MIN2(i - 1, C->macro_count())) { // more than 1 element can be eliminated at once
3120 Node* n = C->macro_node(i - 1);
3121 bool success = false;
3122 DEBUG_ONLY(int old_macro_count = C->macro_count();)
3123 switch (n->class_id()) {
3124 case Node::Class_Allocate:
3125 case Node::Class_AllocateArray:
3126 success = eliminate_allocate_node(n->as_Allocate());
3127 #ifndef PRODUCT
3128 if (success && PrintOptoStatistics) {
3129 AtomicAccess::inc(&PhaseMacroExpand::_objs_scalar_replaced_counter);
3130 }
3131 #endif
3132 break;
3133 case Node::Class_CallStaticJava: {
3134 CallStaticJavaNode* call = n->as_CallStaticJava();
3135 if (!call->method()->is_method_handle_intrinsic()) {
3136 success = eliminate_boxing_node(n->as_CallStaticJava());
3137 }
3138 break;
3139 }
3140 case Node::Class_Lock:
3141 case Node::Class_Unlock:
3142 if (eliminate_locks) {
3143 success = eliminate_locking_node(n->as_AbstractLock());
3144 #ifndef PRODUCT
3145 if (success && PrintOptoStatistics) {
3146 AtomicAccess::inc(&PhaseMacroExpand::_monitor_objects_removed_counter);
3147 }
3148 #endif
3149 }
3150 break;
3151 case Node::Class_ArrayCopy:
3152 break;
3153 case Node::Class_OuterStripMinedLoop:
3154 break;
3155 case Node::Class_SubTypeCheck:
3156 break;
3157 case Node::Class_Opaque1:
3158 break;
3159 case Node::Class_FlatArrayCheck:
3160 break;
3161 default:
3162 assert(n->Opcode() == Op_LoopLimit ||
3163 n->Opcode() == Op_ModD ||
3164 n->Opcode() == Op_ModF ||
3165 n->is_OpaqueNotNull() ||
3166 n->is_OpaqueInitializedAssertionPredicate() ||
3167 n->Opcode() == Op_MaxL ||
3168 n->Opcode() == Op_MinL ||
3169 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
3170 "unknown node type in macro list");
3171 }
3172 assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
3173 progress = progress || success;
3174 if (success) {
3175 C->print_method(PHASE_AFTER_MACRO_ELIMINATION_STEP, 5, n);
3176 }
3177 }
3178
3179 // Ensure the graph after PhaseMacroExpand::eliminate_macro_nodes is canonical (no igvn
3180 // transformation is pending). If an allocation is used only in safepoints, elimination of
3181 // other macro nodes can remove all these safepoints, allowing the allocation to be removed.
3182 // Hence after igvn we retry removing macro nodes if some progress that has been made in this
3183 // iteration.
3184 _igvn.set_delay_transform(false);
3185 _igvn.optimize();
3186 if (C->failing()) {
3187 return;
3188 }
3189 _igvn.set_delay_transform(true);
3190
3191 if (!progress) {
3192 break;
3193 }
3194 }
3195 #ifndef PRODUCT
3196 if (PrintOptoStatistics) {
3197 int membar_after = count_MemBar(C);
3198 AtomicAccess::add(&PhaseMacroExpand::_memory_barriers_removed_counter, membar_before - membar_after);
3199 }
3200 #endif
3201 }
3202
3203 void PhaseMacroExpand::eliminate_opaque_looplimit_macro_nodes() {
3204 if (C->macro_count() == 0) {
3205 return;
3206 }
3207 refine_strip_mined_loop_macro_nodes();
3208 // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
3209 bool progress = true;
3210 while (progress) {
3211 progress = false;
3212 for (int i = C->macro_count(); i > 0; i--) {
3213 Node* n = C->macro_node(i-1);
3214 bool success = false;
3215 DEBUG_ONLY(int old_macro_count = C->macro_count();)
3216 if (n->Opcode() == Op_LoopLimit) {
3217 // Remove it from macro list and put on IGVN worklist to optimize.
3218 C->remove_macro_node(n);
3219 _igvn._worklist.push(n);
3220 success = true;
3221 } else if (n->Opcode() == Op_CallStaticJava) {
3222 CallStaticJavaNode* call = n->as_CallStaticJava();
3223 if (!call->method()->is_method_handle_intrinsic()) {
3224 // Remove it from macro list and put on IGVN worklist to optimize.
3225 C->remove_macro_node(n);
3226 _igvn._worklist.push(n);
3227 success = true;
3228 }
3229 } else if (n->is_Opaque1()) {
3230 _igvn.replace_node(n, n->in(1));
3231 success = true;
3232 } else if (n->is_OpaqueNotNull()) {
3233 // Tests with OpaqueNotNull nodes are implicitly known to be true. Replace the node with true. In debug builds,
3234 // we leave the test in the graph to have an additional sanity check at runtime. If the test fails (i.e. a bug),
3235 // we will execute a Halt node.
3236 #ifdef ASSERT
3237 _igvn.replace_node(n, n->in(1));
3238 #else
3239 _igvn.replace_node(n, _igvn.intcon(1));
3240 #endif
3241 success = true;
3242 } else if (n->is_OpaqueInitializedAssertionPredicate()) {
3243 // Initialized Assertion Predicates must always evaluate to true. Therefore, we get rid of them in product
3244 // builds as they are useless. In debug builds we keep them as additional verification code. Even though
3245 // loop opts are already over, we want to keep Initialized Assertion Predicates alive as long as possible to
3246 // enable folding of dead control paths within which cast nodes become top after due to impossible types -
3247 // even after loop opts are over. Therefore, we delay the removal of these opaque nodes until now.
3248 #ifdef ASSERT
3249 _igvn.replace_node(n, n->in(1));
3250 #else
3251 _igvn.replace_node(n, _igvn.intcon(1));
3252 #endif // ASSERT
3253 } else if (n->Opcode() == Op_OuterStripMinedLoop) {
3254 C->remove_macro_node(n);
3255 success = true;
3256 } else if (n->Opcode() == Op_MaxL) {
3257 // Since MaxL and MinL are not implemented in the backend, we expand them to
3258 // a CMoveL construct now. At least until here, the type could be computed
3259 // precisely. CMoveL is not so smart, but we can give it at least the best
3260 // type we know abouot n now.
3261 Node* repl = MaxNode::signed_max(n->in(1), n->in(2), _igvn.type(n), _igvn);
3262 _igvn.replace_node(n, repl);
3263 success = true;
3264 } else if (n->Opcode() == Op_MinL) {
3265 Node* repl = MaxNode::signed_min(n->in(1), n->in(2), _igvn.type(n), _igvn);
3266 _igvn.replace_node(n, repl);
3267 success = true;
3268 }
3269 assert(!success || (C->macro_count() == (old_macro_count - 1)), "elimination must have deleted one node from macro list");
3270 progress = progress || success;
3271 if (success) {
3272 C->print_method(PHASE_AFTER_MACRO_ELIMINATION_STEP, 5, n);
3273 }
3274 }
3275 }
3276 }
3277
3278 //------------------------------expand_macro_nodes----------------------
3279 // Returns true if a failure occurred.
3280 bool PhaseMacroExpand::expand_macro_nodes() {
3281 if (StressMacroExpansion) {
3282 C->shuffle_macro_nodes();
3283 }
3284
3285 // Clean up the graph so we're less likely to hit the maximum node
3286 // limit
3287 _igvn.set_delay_transform(false);
3288 _igvn.optimize();
3289 if (C->failing()) return true;
3290 _igvn.set_delay_transform(true);
3291
3292
3293 // Because we run IGVN after each expansion, some macro nodes may go
3294 // dead and be removed from the list as we iterate over it. Move
3295 // Allocate nodes (processed in a second pass) at the beginning of
3296 // the list and then iterate from the last element of the list until
3297 // an Allocate node is seen. This is robust to random deletion in
3298 // the list due to nodes going dead.
3299 C->sort_macro_nodes();
3300
3301 // expand arraycopy "macro" nodes first
3302 // For ReduceBulkZeroing, we must first process all arraycopy nodes
3303 // before the allocate nodes are expanded.
3304 while (C->macro_count() > 0) {
3305 int macro_count = C->macro_count();
3306 Node * n = C->macro_node(macro_count-1);
3307 assert(n->is_macro(), "only macro nodes expected here");
3308 if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) {
3309 // node is unreachable, so don't try to expand it
3310 C->remove_macro_node(n);
3311 continue;
3312 }
3313 if (n->is_Allocate()) {
3314 break;
3315 }
3316 // Make sure expansion will not cause node limit to be exceeded.
3317 // Worst case is a macro node gets expanded into about 200 nodes.
3318 // Allow 50% more for optimization.
3319 if (C->check_node_count(300, "out of nodes before macro expansion")) {
3320 return true;
3321 }
3322
3323 DEBUG_ONLY(int old_macro_count = C->macro_count();)
3324 switch (n->class_id()) {
3325 case Node::Class_Lock:
3326 expand_lock_node(n->as_Lock());
3327 break;
3328 case Node::Class_Unlock:
3329 expand_unlock_node(n->as_Unlock());
3330 break;
3331 case Node::Class_ArrayCopy:
3332 expand_arraycopy_node(n->as_ArrayCopy());
3333 break;
3334 case Node::Class_SubTypeCheck:
3335 expand_subtypecheck_node(n->as_SubTypeCheck());
3336 break;
3337 case Node::Class_CallStaticJava:
3338 expand_mh_intrinsic_return(n->as_CallStaticJava());
3339 C->remove_macro_node(n);
3340 break;
3341 case Node::Class_FlatArrayCheck:
3342 expand_flatarraycheck_node(n->as_FlatArrayCheck());
3343 break;
3344 default:
3345 switch (n->Opcode()) {
3346 case Op_ModD:
3347 case Op_ModF: {
3348 CallNode* mod_macro = n->as_Call();
3349 CallNode* call = new CallLeafPureNode(mod_macro->tf(), mod_macro->entry_point(), mod_macro->_name);
3350 call->init_req(TypeFunc::Control, mod_macro->in(TypeFunc::Control));
3351 call->init_req(TypeFunc::I_O, C->top());
3352 call->init_req(TypeFunc::Memory, C->top());
3353 call->init_req(TypeFunc::ReturnAdr, C->top());
3354 call->init_req(TypeFunc::FramePtr, C->top());
3355 for (unsigned int i = 0; i < mod_macro->tf()->domain_cc()->cnt() - TypeFunc::Parms; i++) {
3356 call->init_req(TypeFunc::Parms + i, mod_macro->in(TypeFunc::Parms + i));
3357 }
3358 _igvn.replace_node(mod_macro, call);
3359 transform_later(call);
3360 break;
3361 }
3362 default:
3363 assert(false, "unknown node type in macro list");
3364 }
3365 }
3366 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3367 if (C->failing()) return true;
3368 C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
3369
3370 // Clean up the graph so we're less likely to hit the maximum node
3371 // limit
3372 _igvn.set_delay_transform(false);
3373 _igvn.optimize();
3374 if (C->failing()) return true;
3375 _igvn.set_delay_transform(true);
3376 }
3377
3378 // All nodes except Allocate nodes are expanded now. There could be
3379 // new optimization opportunities (such as folding newly created
3380 // load from a just allocated object). Run IGVN.
3381
3382 // expand "macro" nodes
3383 // nodes are removed from the macro list as they are processed
3384 while (C->macro_count() > 0) {
3385 int macro_count = C->macro_count();
3386 Node * n = C->macro_node(macro_count-1);
3387 assert(n->is_macro(), "only macro nodes expected here");
3388 if (_igvn.type(n) == Type::TOP || (n->in(0) != nullptr && n->in(0)->is_top())) {
3389 // node is unreachable, so don't try to expand it
3390 C->remove_macro_node(n);
3391 continue;
3392 }
3393 // Make sure expansion will not cause node limit to be exceeded.
3394 // Worst case is a macro node gets expanded into about 200 nodes.
3395 // Allow 50% more for optimization.
3396 if (C->check_node_count(300, "out of nodes before macro expansion")) {
3397 return true;
3398 }
3399 switch (n->class_id()) {
3400 case Node::Class_Allocate:
3401 expand_allocate(n->as_Allocate());
3402 break;
3403 case Node::Class_AllocateArray:
3404 expand_allocate_array(n->as_AllocateArray());
3405 break;
3406 default:
3407 assert(false, "unknown node type in macro list");
3408 }
3409 assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
3410 if (C->failing()) return true;
3411 C->print_method(PHASE_AFTER_MACRO_EXPANSION_STEP, 5, n);
3412
3413 // Clean up the graph so we're less likely to hit the maximum node
3414 // limit
3415 _igvn.set_delay_transform(false);
3416 _igvn.optimize();
3417 if (C->failing()) return true;
3418 _igvn.set_delay_transform(true);
3419 }
3420
3421 _igvn.set_delay_transform(false);
3422 return false;
3423 }
3424
3425 #ifndef PRODUCT
3426 int PhaseMacroExpand::_objs_scalar_replaced_counter = 0;
3427 int PhaseMacroExpand::_monitor_objects_removed_counter = 0;
3428 int PhaseMacroExpand::_GC_barriers_removed_counter = 0;
3429 int PhaseMacroExpand::_memory_barriers_removed_counter = 0;
3430
3431 void PhaseMacroExpand::print_statistics() {
3432 tty->print("Objects scalar replaced = %d, ", AtomicAccess::load(&_objs_scalar_replaced_counter));
3433 tty->print("Monitor objects removed = %d, ", AtomicAccess::load(&_monitor_objects_removed_counter));
3434 tty->print("GC barriers removed = %d, ", AtomicAccess::load(&_GC_barriers_removed_counter));
3435 tty->print_cr("Memory barriers removed = %d", AtomicAccess::load(&_memory_barriers_removed_counter));
3436 }
3437
3438 int PhaseMacroExpand::count_MemBar(Compile *C) {
3439 if (!PrintOptoStatistics) {
3440 return 0;
3441 }
3442 Unique_Node_List ideal_nodes;
3443 int total = 0;
3444 ideal_nodes.map(C->live_nodes(), nullptr);
3445 ideal_nodes.push(C->root());
3446 for (uint next = 0; next < ideal_nodes.size(); ++next) {
3447 Node* n = ideal_nodes.at(next);
3448 if (n->is_MemBar()) {
3449 total++;
3450 }
3451 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3452 Node* m = n->fast_out(i);
3453 ideal_nodes.push(m);
3454 }
3455 }
3456 return total;
3457 }
3458 #endif