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