1 /*
2 * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "compiler/compileLog.hpp"
27 #include "gc/shared/collectedHeap.inline.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 "runtime/sharedRuntime.hpp"
53 #include "utilities/macros.hpp"
54 #include "utilities/powerOfTwo.hpp"
55 #if INCLUDE_G1GC
56 #include "gc/g1/g1ThreadLocalData.hpp"
57 #endif // INCLUDE_G1GC
65 // Returns the number of replacements made.
66 //
67 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
68 int nreplacements = 0;
69 uint req = use->req();
70 for (uint j = 0; j < use->len(); j++) {
71 Node *uin = use->in(j);
72 if (uin == oldref) {
73 if (j < req)
74 use->set_req(j, newref);
75 else
76 use->set_prec(j, newref);
77 nreplacements++;
78 } else if (j >= req && uin == NULL) {
79 break;
80 }
81 }
82 return nreplacements;
83 }
84
85 void PhaseMacroExpand::migrate_outs(Node *old, Node *target) {
86 assert(old != NULL, "sanity");
87 for (DUIterator_Fast imax, i = old->fast_outs(imax); i < imax; i++) {
88 Node* use = old->fast_out(i);
89 _igvn.rehash_node_delayed(use);
90 imax -= replace_input(use, old, target);
91 // back up iterator
92 --i;
93 }
94 assert(old->outcnt() == 0, "all uses must be deleted");
95 }
96
97 void PhaseMacroExpand::copy_call_debug_info(CallNode *oldcall, CallNode * newcall) {
98 // Copy debug information and adjust JVMState information
99 uint old_dbg_start = oldcall->tf()->domain()->cnt();
100 uint new_dbg_start = newcall->tf()->domain()->cnt();
101 int jvms_adj = new_dbg_start - old_dbg_start;
102 assert (new_dbg_start == newcall->req(), "argument count mismatch");
103
104 // SafePointScalarObject node could be referenced several times in debug info.
105 // Use Dict to record cloned nodes.
106 Dict* sosn_map = new Dict(cmpkey,hashkey);
107 for (uint i = old_dbg_start; i < oldcall->req(); i++) {
108 Node* old_in = oldcall->in(i);
109 // Clone old SafePointScalarObjectNodes, adjusting their field contents.
110 if (old_in != NULL && old_in->is_SafePointScalarObject()) {
111 SafePointScalarObjectNode* old_sosn = old_in->as_SafePointScalarObject();
112 uint old_unique = C->unique();
113 Node* new_in = old_sosn->clone(sosn_map);
114 if (old_unique != C->unique()) { // New node?
115 new_in->set_req(0, C->root()); // reset control edge
116 new_in = transform_later(new_in); // Register new node.
117 }
118 old_in = new_in;
119 }
120 newcall->add_req(old_in);
121 }
122
123 // JVMS may be shared so clone it before we modify it
124 newcall->set_jvms(oldcall->jvms() != NULL ? oldcall->jvms()->clone_deep(C) : NULL);
125 for (JVMState *jvms = newcall->jvms(); jvms != NULL; jvms = jvms->caller()) {
126 jvms->set_map(newcall);
127 jvms->set_locoff(jvms->locoff()+jvms_adj);
128 jvms->set_stkoff(jvms->stkoff()+jvms_adj);
129 jvms->set_monoff(jvms->monoff()+jvms_adj);
130 jvms->set_scloff(jvms->scloff()+jvms_adj);
131 jvms->set_endoff(jvms->endoff()+jvms_adj);
132 }
133 }
134
135 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word, int mask, int bits, bool return_fast_path) {
136 Node* cmp;
137 if (mask != 0) {
138 Node* and_node = transform_later(new AndXNode(word, MakeConX(mask)));
139 cmp = transform_later(new CmpXNode(and_node, MakeConX(bits)));
140 } else {
141 cmp = word;
142 }
143 Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
144 IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
145 transform_later(iff);
146
147 // Fast path taken.
148 Node *fast_taken = transform_later(new IfFalseNode(iff));
149
150 // Fast path not-taken, i.e. slow path
151 Node *slow_taken = transform_later(new IfTrueNode(iff));
152
153 if (return_fast_path) {
154 region->init_req(edge, slow_taken); // Capture slow-control
167 call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ?????
168 call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) );
169 call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) );
170 }
171
172 //------------------------------make_slow_call---------------------------------
173 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type,
174 address slow_call, const char* leaf_name, Node* slow_path,
175 Node* parm0, Node* parm1, Node* parm2) {
176
177 // Slow-path call
178 CallNode *call = leaf_name
179 ? (CallNode*)new CallLeafNode ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
180 : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), oldcall->jvms()->bci(), TypeRawPtr::BOTTOM );
181
182 // Slow path call has no side-effects, uses few values
183 copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
184 if (parm0 != NULL) call->init_req(TypeFunc::Parms+0, parm0);
185 if (parm1 != NULL) call->init_req(TypeFunc::Parms+1, parm1);
186 if (parm2 != NULL) call->init_req(TypeFunc::Parms+2, parm2);
187 copy_call_debug_info(oldcall, call);
188 call->set_cnt(PROB_UNLIKELY_MAG(4)); // Same effect as RC_UNCOMMON.
189 _igvn.replace_node(oldcall, call);
190 transform_later(call);
191
192 return call;
193 }
194
195 void PhaseMacroExpand::extract_call_projections(CallNode *call) {
196 _fallthroughproj = NULL;
197 _fallthroughcatchproj = NULL;
198 _ioproj_fallthrough = NULL;
199 _ioproj_catchall = NULL;
200 _catchallcatchproj = NULL;
201 _memproj_fallthrough = NULL;
202 _memproj_catchall = NULL;
203 _resproj = NULL;
204 for (DUIterator_Fast imax, i = call->fast_outs(imax); i < imax; i++) {
205 ProjNode *pn = call->fast_out(i)->as_Proj();
206 switch (pn->_con) {
207 case TypeFunc::Control:
275 if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
276 return in;
277 }
278 }
279 mem = in->in(TypeFunc::Memory);
280 } else if (in->is_MemBar()) {
281 ArrayCopyNode* ac = NULL;
282 if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
283 assert(ac != NULL && ac->is_clonebasic(), "Only basic clone is a non escaping clone");
284 return ac;
285 }
286 mem = in->in(TypeFunc::Memory);
287 } else {
288 assert(false, "unexpected projection");
289 }
290 } else if (mem->is_Store()) {
291 const TypePtr* atype = mem->as_Store()->adr_type();
292 int adr_idx = phase->C->get_alias_index(atype);
293 if (adr_idx == alias_idx) {
294 assert(atype->isa_oopptr(), "address type must be oopptr");
295 int adr_offset = atype->offset();
296 uint adr_iid = atype->is_oopptr()->instance_id();
297 // Array elements references have the same alias_idx
298 // but different offset and different instance_id.
299 if (adr_offset == offset && adr_iid == alloc->_idx)
300 return mem;
301 } else {
302 assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
303 }
304 mem = mem->in(MemNode::Memory);
305 } else if (mem->is_ClearArray()) {
306 if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
307 // Can not bypass initialization of the instance
308 // we are looking.
309 debug_only(intptr_t offset;)
310 assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
311 InitializeNode* init = alloc->as_Allocate()->initialization();
312 // We are looking for stored value, return Initialize node
313 // or memory edge from Allocate node.
314 if (init != NULL)
315 return init;
318 }
319 // Otherwise skip it (the call updated 'mem' value).
320 } else if (mem->Opcode() == Op_SCMemProj) {
321 mem = mem->in(0);
322 Node* adr = NULL;
323 if (mem->is_LoadStore()) {
324 adr = mem->in(MemNode::Address);
325 } else {
326 assert(mem->Opcode() == Op_EncodeISOArray ||
327 mem->Opcode() == Op_StrCompressedCopy, "sanity");
328 adr = mem->in(3); // Destination array
329 }
330 const TypePtr* atype = adr->bottom_type()->is_ptr();
331 int adr_idx = phase->C->get_alias_index(atype);
332 if (adr_idx == alias_idx) {
333 DEBUG_ONLY(mem->dump();)
334 assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
335 return NULL;
336 }
337 mem = mem->in(MemNode::Memory);
338 } else if (mem->Opcode() == Op_StrInflatedCopy) {
339 Node* adr = mem->in(3); // Destination array
340 const TypePtr* atype = adr->bottom_type()->is_ptr();
341 int adr_idx = phase->C->get_alias_index(atype);
342 if (adr_idx == alias_idx) {
343 DEBUG_ONLY(mem->dump();)
344 assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
345 return NULL;
346 }
347 mem = mem->in(MemNode::Memory);
348 } else {
349 return mem;
350 }
351 assert(mem != orig_mem, "dead memory loop");
352 }
353 }
354
355 // Generate loads from source of the arraycopy for fields of
356 // destination needed at a deoptimization point
357 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
358 BasicType bt = ft;
363 }
364 Node* res = NULL;
365 if (ac->is_clonebasic()) {
366 assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
367 Node* base = ac->in(ArrayCopyNode::Src);
368 Node* adr = _igvn.transform(new AddPNode(base, base, MakeConX(offset)));
369 const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
370 MergeMemNode* mergemen = MergeMemNode::make(mem);
371 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
372 res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
373 } else {
374 if (ac->modifies(offset, offset, &_igvn, true)) {
375 assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
376 uint shift = exact_log2(type2aelembytes(bt));
377 Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
378 Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
379 const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
380 const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
381
382 Node* adr = NULL;
383 const TypePtr* adr_type = NULL;
384 if (src_pos_t->is_con() && dest_pos_t->is_con()) {
385 intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
386 Node* base = ac->in(ArrayCopyNode::Src);
387 adr = _igvn.transform(new AddPNode(base, base, MakeConX(off)));
388 adr_type = _igvn.type(base)->is_ptr()->add_offset(off);
389 if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
390 // Don't emit a new load from src if src == dst but try to get the value from memory instead
391 return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type->isa_oopptr(), alloc);
392 }
393 } else {
394 Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
395 #ifdef _LP64
396 diff = _igvn.transform(new ConvI2LNode(diff));
397 #endif
398 diff = _igvn.transform(new LShiftXNode(diff, intcon(shift)));
399
400 Node* off = _igvn.transform(new AddXNode(MakeConX(offset), diff));
401 Node* base = ac->in(ArrayCopyNode::Src);
402 adr = _igvn.transform(new AddPNode(base, base, off));
403 adr_type = _igvn.type(base)->is_ptr()->add_offset(Type::OffsetBot);
404 if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
405 // Non constant offset in the array: we can't statically
406 // determine the value
407 return NULL;
408 }
409 }
410 MergeMemNode* mergemen = MergeMemNode::make(mem);
411 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
412 res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
413 }
414 }
415 if (res != NULL) {
416 if (ftype->isa_narrowoop()) {
417 // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
418 res = _igvn.transform(new EncodePNode(res, ftype));
419 }
420 return res;
421 }
422 return NULL;
423 }
424
425 //
426 // Given a Memory Phi, compute a value Phi containing the values from stores
427 // on the input paths.
428 // Note: this function is recursive, its depth is limited by the "level" argument
429 // Returns the computed Phi, or NULL if it cannot compute it.
430 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) {
431 assert(mem->is_Phi(), "sanity");
432 int alias_idx = C->get_alias_index(adr_t);
433 int offset = adr_t->offset();
434 int instance_id = adr_t->instance_id();
435
436 // Check if an appropriate value phi already exists.
437 Node* region = mem->in(0);
438 for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
439 Node* phi = region->fast_out(k);
440 if (phi->is_Phi() && phi != mem &&
441 phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
442 return phi;
443 }
444 }
445 // Check if an appropriate new value phi already exists.
446 Node* new_phi = value_phis->find(mem->_idx);
447 if (new_phi != NULL)
448 return new_phi;
449
450 if (level <= 0) {
451 return NULL; // Give up: phi tree too deep
452 }
453 Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
454 Node *alloc_mem = alloc->in(TypeFunc::Memory);
455
456 uint length = mem->req();
457 GrowableArray <Node *> values(length, length, NULL);
458
459 // create a new Phi for the value
460 PhiNode *phi = new PhiNode(mem->in(0), phi_type, NULL, mem->_idx, instance_id, alias_idx, offset);
461 transform_later(phi);
462 value_phis->push(phi, mem->_idx);
463
464 for (uint j = 1; j < length; j++) {
465 Node *in = mem->in(j);
466 if (in == NULL || in->is_top()) {
467 values.at_put(j, in);
468 } else {
469 Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
470 if (val == start_mem || val == alloc_mem) {
471 // hit a sentinel, return appropriate 0 value
472 values.at_put(j, _igvn.zerocon(ft));
473 continue;
474 }
475 if (val->is_Initialize()) {
476 val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
477 }
478 if (val == NULL) {
479 return NULL; // can't find a value on this path
480 }
481 if (val == mem) {
482 values.at_put(j, mem);
483 } else if (val->is_Store()) {
484 Node* n = val->in(MemNode::ValueIn);
485 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
486 n = bs->step_over_gc_barrier(n);
487 values.at_put(j, n);
488 } else if(val->is_Proj() && val->in(0) == alloc) {
489 values.at_put(j, _igvn.zerocon(ft));
490 } else if (val->is_Phi()) {
491 val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
492 if (val == NULL) {
493 return NULL;
494 }
495 values.at_put(j, val);
496 } else if (val->Opcode() == Op_SCMemProj) {
497 assert(val->in(0)->is_LoadStore() ||
498 val->in(0)->Opcode() == Op_EncodeISOArray ||
499 val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
500 assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
501 return NULL;
502 } else if (val->is_ArrayCopy()) {
503 Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
504 if (res == NULL) {
505 return NULL;
506 }
507 values.at_put(j, res);
508 } else {
509 #ifdef ASSERT
515 }
516 }
517 // Set Phi's inputs
518 for (uint j = 1; j < length; j++) {
519 if (values.at(j) == mem) {
520 phi->init_req(j, phi);
521 } else {
522 phi->init_req(j, values.at(j));
523 }
524 }
525 return phi;
526 }
527
528 // Search the last value stored into the object's field.
529 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
530 assert(adr_t->is_known_instance_field(), "instance required");
531 int instance_id = adr_t->instance_id();
532 assert((uint)instance_id == alloc->_idx, "wrong allocation");
533
534 int alias_idx = C->get_alias_index(adr_t);
535 int offset = adr_t->offset();
536 Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
537 Node *alloc_ctrl = alloc->in(TypeFunc::Control);
538 Node *alloc_mem = alloc->in(TypeFunc::Memory);
539 VectorSet visited;
540
541 bool done = sfpt_mem == alloc_mem;
542 Node *mem = sfpt_mem;
543 while (!done) {
544 if (visited.test_set(mem->_idx)) {
545 return NULL; // found a loop, give up
546 }
547 mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
548 if (mem == start_mem || mem == alloc_mem) {
549 done = true; // hit a sentinel, return appropriate 0 value
550 } else if (mem->is_Initialize()) {
551 mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
552 if (mem == NULL) {
553 done = true; // Something go wrong.
554 } else if (mem->is_Store()) {
555 const TypePtr* atype = mem->as_Store()->adr_type();
556 assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
557 done = true;
558 }
559 } else if (mem->is_Store()) {
560 const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
561 assert(atype != NULL, "address type must be oopptr");
562 assert(C->get_alias_index(atype) == alias_idx &&
563 atype->is_known_instance_field() && atype->offset() == offset &&
564 atype->instance_id() == instance_id, "store is correct memory slice");
565 done = true;
566 } else if (mem->is_Phi()) {
567 // try to find a phi's unique input
568 Node *unique_input = NULL;
569 Node *top = C->top();
570 for (uint i = 1; i < mem->req(); i++) {
571 Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
572 if (n == NULL || n == top || n == mem) {
573 continue;
574 } else if (unique_input == NULL) {
575 unique_input = n;
576 } else if (unique_input != n) {
577 unique_input = top;
578 break;
579 }
580 }
581 if (unique_input != NULL && unique_input != top) {
582 mem = unique_input;
583 } else {
584 done = true;
585 }
586 } else if (mem->is_ArrayCopy()) {
587 done = true;
588 } else {
589 assert(false, "unexpected node");
590 }
591 }
592 if (mem != NULL) {
593 if (mem == start_mem || mem == alloc_mem) {
594 // hit a sentinel, return appropriate 0 value
595 return _igvn.zerocon(ft);
596 } else if (mem->is_Store()) {
597 Node* n = mem->in(MemNode::ValueIn);
598 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
599 n = bs->step_over_gc_barrier(n);
600 return n;
601 } else if (mem->is_Phi()) {
602 // attempt to produce a Phi reflecting the values on the input paths of the Phi
603 Node_Stack value_phis(8);
604 Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
605 if (phi != NULL) {
606 return phi;
607 } else {
608 // Kill all new Phis
609 while(value_phis.is_nonempty()) {
610 Node* n = value_phis.node();
611 _igvn.replace_node(n, C->top());
612 value_phis.pop();
613 }
614 }
615 } else if (mem->is_ArrayCopy()) {
616 Node* ctl = mem->in(0);
617 Node* m = mem->in(TypeFunc::Memory);
618 if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
619 // pin the loads in the uncommon trap path
620 ctl = sfpt_ctl;
621 m = sfpt_mem;
622 }
623 return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
624 }
625 }
626 // Something go wrong.
627 return NULL;
628 }
629
630 // Check the possibility of scalar replacement.
631 bool PhaseMacroExpand::can_eliminate_allocation(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
632 // Scan the uses of the allocation to check for anything that would
633 // prevent us from eliminating it.
634 NOT_PRODUCT( const char* fail_eliminate = NULL; )
635 DEBUG_ONLY( Node* disq_node = NULL; )
636 bool can_eliminate = true;
637
638 Node* res = alloc->result_cast();
639 const TypeOopPtr* res_type = NULL;
640 if (res == NULL) {
641 // All users were eliminated.
642 } else if (!res->is_CheckCastPP()) {
643 NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
644 can_eliminate = false;
645 } else {
646 res_type = _igvn.type(res)->isa_oopptr();
647 if (res_type == NULL) {
648 NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
649 can_eliminate = false;
662 Node* use = res->fast_out(j);
663
664 if (use->is_AddP()) {
665 const TypePtr* addp_type = _igvn.type(use)->is_ptr();
666 int offset = addp_type->offset();
667
668 if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
669 NOT_PRODUCT(fail_eliminate = "Undefined field referrence";)
670 can_eliminate = false;
671 break;
672 }
673 for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
674 k < kmax && can_eliminate; k++) {
675 Node* n = use->fast_out(k);
676 if (!n->is_Store() && n->Opcode() != Op_CastP2X
677 SHENANDOAHGC_ONLY(&& (!UseShenandoahGC || !ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(n))) ) {
678 DEBUG_ONLY(disq_node = n;)
679 if (n->is_Load() || n->is_LoadStore()) {
680 NOT_PRODUCT(fail_eliminate = "Field load";)
681 } else {
682 NOT_PRODUCT(fail_eliminate = "Not store field referrence";)
683 }
684 can_eliminate = false;
685 }
686 }
687 } else if (use->is_ArrayCopy() &&
688 (use->as_ArrayCopy()->is_clonebasic() ||
689 use->as_ArrayCopy()->is_arraycopy_validated() ||
690 use->as_ArrayCopy()->is_copyof_validated() ||
691 use->as_ArrayCopy()->is_copyofrange_validated()) &&
692 use->in(ArrayCopyNode::Dest) == res) {
693 // ok to eliminate
694 } else if (use->is_SafePoint()) {
695 SafePointNode* sfpt = use->as_SafePoint();
696 if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
697 // Object is passed as argument.
698 DEBUG_ONLY(disq_node = use;)
699 NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
700 can_eliminate = false;
701 }
702 Node* sfptMem = sfpt->memory();
703 if (sfptMem == NULL || sfptMem->is_top()) {
704 DEBUG_ONLY(disq_node = use;)
705 NOT_PRODUCT(fail_eliminate = "NULL or TOP memory";)
706 can_eliminate = false;
707 } else {
708 safepoints.append_if_missing(sfpt);
709 }
710 } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
711 if (use->is_Phi()) {
712 if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
713 NOT_PRODUCT(fail_eliminate = "Object is return value";)
714 } else {
715 NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
716 }
717 DEBUG_ONLY(disq_node = use;)
718 } else {
719 if (use->Opcode() == Op_Return) {
720 NOT_PRODUCT(fail_eliminate = "Object is return value";)
721 }else {
722 NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
723 }
724 DEBUG_ONLY(disq_node = use;)
725 }
726 can_eliminate = false;
727 }
728 }
729 }
730
731 #ifndef PRODUCT
732 if (PrintEliminateAllocations) {
733 if (can_eliminate) {
734 tty->print("Scalar ");
735 if (res == NULL)
736 alloc->dump();
737 else
738 res->dump();
739 } else if (alloc->_is_scalar_replaceable) {
740 tty->print("NotScalar (%s)", fail_eliminate);
741 if (res == NULL)
742 alloc->dump();
743 else
744 res->dump();
745 #ifdef ASSERT
746 if (disq_node != NULL) {
769 Node* res = alloc->result_cast();
770 assert(res == NULL || res->is_CheckCastPP(), "unexpected AllocateNode result");
771 const TypeOopPtr* res_type = NULL;
772 if (res != NULL) { // Could be NULL when there are no users
773 res_type = _igvn.type(res)->isa_oopptr();
774 }
775
776 if (res != NULL) {
777 klass = res_type->klass();
778 if (res_type->isa_instptr()) {
779 // find the fields of the class which will be needed for safepoint debug information
780 assert(klass->is_instance_klass(), "must be an instance klass.");
781 iklass = klass->as_instance_klass();
782 nfields = iklass->nof_nonstatic_fields();
783 } else {
784 // find the array's elements which will be needed for safepoint debug information
785 nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
786 assert(klass->is_array_klass() && nfields >= 0, "must be an array klass.");
787 elem_type = klass->as_array_klass()->element_type();
788 basic_elem_type = elem_type->basic_type();
789 array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
790 element_size = type2aelembytes(basic_elem_type);
791 }
792 }
793 //
794 // Process the safepoint uses
795 //
796 while (safepoints.length() > 0) {
797 SafePointNode* sfpt = safepoints.pop();
798 Node* mem = sfpt->memory();
799 Node* ctl = sfpt->control();
800 assert(sfpt->jvms() != NULL, "missed JVMS");
801 // Fields of scalar objs are referenced only at the end
802 // of regular debuginfo at the last (youngest) JVMS.
803 // Record relative start index.
804 uint first_ind = (sfpt->req() - sfpt->jvms()->scloff());
805 SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type,
806 #ifdef ASSERT
807 alloc,
808 #endif
809 first_ind, nfields);
810 sobj->init_req(0, C->root());
811 transform_later(sobj);
812
813 // Scan object's fields adding an input to the safepoint for each field.
814 for (int j = 0; j < nfields; j++) {
815 intptr_t offset;
816 ciField* field = NULL;
817 if (iklass != NULL) {
818 field = iklass->nonstatic_field_at(j);
819 offset = field->offset();
820 elem_type = field->type();
821 basic_elem_type = field->layout_type();
822 } else {
823 offset = array_base + j * (intptr_t)element_size;
824 }
825
826 const Type *field_type;
827 // The next code is taken from Parse::do_get_xxx().
828 if (is_reference_type(basic_elem_type)) {
829 if (!elem_type->is_loaded()) {
830 field_type = TypeInstPtr::BOTTOM;
831 } else if (field != NULL && field->is_static_constant()) {
832 // This can happen if the constant oop is non-perm.
833 ciObject* con = field->constant_value().as_object();
834 // Do not "join" in the previous type; it doesn't add value,
835 // and may yield a vacuous result if the field is of interface type.
836 field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
837 assert(field_type != NULL, "field singleton type must be consistent");
838 } else {
839 field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
840 }
841 if (UseCompressedOops) {
842 field_type = field_type->make_narrowoop();
843 basic_elem_type = T_NARROWOOP;
844 }
845 } else {
846 field_type = Type::get_const_basic_type(basic_elem_type);
847 }
848
849 const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
850
851 Node *field_val = value_from_mem(mem, ctl, basic_elem_type, field_type, field_addr_type, alloc);
852 if (field_val == NULL) {
853 // We weren't able to find a value for this field,
854 // give up on eliminating this allocation.
855
856 // Remove any extra entries we added to the safepoint.
857 uint last = sfpt->req() - 1;
858 for (int k = 0; k < j; k++) {
859 sfpt->del_req(last--);
860 }
861 _igvn._worklist.push(sfpt);
862 // rollback processed safepoints
863 while (safepoints_done.length() > 0) {
864 SafePointNode* sfpt_done = safepoints_done.pop();
865 // remove any extra entries we added to the safepoint
866 last = sfpt_done->req() - 1;
867 for (int k = 0; k < nfields; k++) {
868 sfpt_done->del_req(last--);
869 }
870 JVMState *jvms = sfpt_done->jvms();
871 jvms->set_endoff(sfpt_done->req());
889 if (PrintEliminateAllocations) {
890 if (field != NULL) {
891 tty->print("=== At SafePoint node %d can't find value of Field: ",
892 sfpt->_idx);
893 field->print();
894 int field_idx = C->get_alias_index(field_addr_type);
895 tty->print(" (alias_idx=%d)", field_idx);
896 } else { // Array's element
897 tty->print("=== At SafePoint node %d can't find value of array element [%d]",
898 sfpt->_idx, j);
899 }
900 tty->print(", which prevents elimination of: ");
901 if (res == NULL)
902 alloc->dump();
903 else
904 res->dump();
905 }
906 #endif
907 return false;
908 }
909 if (UseCompressedOops && field_type->isa_narrowoop()) {
910 // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
911 // to be able scalar replace the allocation.
912 if (field_val->is_EncodeP()) {
913 field_val = field_val->in(1);
914 } else {
915 field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
916 }
917 }
918 sfpt->add_req(field_val);
919 }
920 JVMState *jvms = sfpt->jvms();
921 jvms->set_endoff(sfpt->req());
922 // Now make a pass over the debug information replacing any references
923 // to the allocated object with "sobj"
924 int start = jvms->debug_start();
925 int end = jvms->debug_end();
926 sfpt->replace_edges_in_range(res, sobj, start, end);
927 _igvn._worklist.push(sfpt);
928 safepoints_done.append_if_missing(sfpt); // keep it for rollback
929 }
930 return true;
931 }
932
933 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
934 Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
935 Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
936 if (ctl_proj != NULL) {
937 igvn.replace_node(ctl_proj, n->in(0));
938 }
939 if (mem_proj != NULL) {
940 igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
941 }
942 }
943
944 // Process users of eliminated allocation.
945 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc) {
946 Node* res = alloc->result_cast();
947 if (res != NULL) {
948 for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
949 Node *use = res->last_out(j);
950 uint oc1 = res->outcnt();
951
952 if (use->is_AddP()) {
953 for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
954 Node *n = use->last_out(k);
955 uint oc2 = use->outcnt();
956 if (n->is_Store()) {
957 #ifdef ASSERT
958 // Verify that there is no dependent MemBarVolatile nodes,
959 // they should be removed during IGVN, see MemBarNode::Ideal().
960 for (DUIterator_Fast pmax, p = n->fast_outs(pmax);
961 p < pmax; p++) {
962 Node* mb = n->fast_out(p);
963 assert(mb->is_Initialize() || !mb->is_MemBar() ||
964 mb->req() <= MemBarNode::Precedent ||
965 mb->in(MemBarNode::Precedent) != n,
966 "MemBarVolatile should be eliminated for non-escaping object");
967 }
968 #endif
969 _igvn.replace_node(n, n->in(MemNode::Memory));
970 } else {
971 eliminate_gc_barrier(n);
972 }
973 k -= (oc2 - use->outcnt());
974 }
975 _igvn.remove_dead_node(use);
976 } else if (use->is_ArrayCopy()) {
977 // Disconnect ArrayCopy node
978 ArrayCopyNode* ac = use->as_ArrayCopy();
979 if (ac->is_clonebasic()) {
980 Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
981 disconnect_projections(ac, _igvn);
982 assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
983 Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
984 disconnect_projections(membar_before->as_MemBar(), _igvn);
985 if (membar_after->is_MemBar()) {
986 disconnect_projections(membar_after->as_MemBar(), _igvn);
987 }
988 } else {
989 assert(ac->is_arraycopy_validated() ||
990 ac->is_copyof_validated() ||
991 ac->is_copyofrange_validated(), "unsupported");
992 CallProjections callprojs;
993 ac->extract_projections(&callprojs, true);
994
995 _igvn.replace_node(callprojs.fallthrough_ioproj, ac->in(TypeFunc::I_O));
996 _igvn.replace_node(callprojs.fallthrough_memproj, ac->in(TypeFunc::Memory));
997 _igvn.replace_node(callprojs.fallthrough_catchproj, ac->in(TypeFunc::Control));
998
999 // Set control to top. IGVN will remove the remaining projections
1000 ac->set_req(0, top());
1001 ac->replace_edge(res, top());
1002
1003 // Disconnect src right away: it can help find new
1004 // opportunities for allocation elimination
1005 Node* src = ac->in(ArrayCopyNode::Src);
1006 ac->replace_edge(src, top());
1007 // src can be top at this point if src and dest of the
1008 // arraycopy were the same
1009 if (src->outcnt() == 0 && !src->is_top()) {
1010 _igvn.remove_dead_node(src);
1011 }
1012 }
1013 _igvn._worklist.push(ac);
1014 } else {
1015 eliminate_gc_barrier(use);
1016 }
1017 j -= (oc1 - res->outcnt());
1018 }
1019 assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1020 _igvn.remove_dead_node(res);
1021 }
1022
1023 //
1024 // Process other users of allocation's projections
1025 //
1026 if (_resproj != NULL && _resproj->outcnt() != 0) {
1027 // First disconnect stores captured by Initialize node.
1028 // If Initialize node is eliminated first in the following code,
1029 // it will kill such stores and DUIterator_Last will assert.
1030 for (DUIterator_Fast jmax, j = _resproj->fast_outs(jmax); j < jmax; j++) {
1031 Node *use = _resproj->fast_out(j);
1032 if (use->is_AddP()) {
1033 // raw memory addresses used only by the initialization
1034 _igvn.replace_node(use, C->top());
1035 --j; --jmax;
1036 }
1037 }
1038 for (DUIterator_Last jmin, j = _resproj->last_outs(jmin); j >= jmin; ) {
1039 Node *use = _resproj->last_out(j);
1040 uint oc1 = _resproj->outcnt();
1041 if (use->is_Initialize()) {
1042 // Eliminate Initialize node.
1043 InitializeNode *init = use->as_Initialize();
1044 assert(init->outcnt() <= 2, "only a control and memory projection expected");
1045 Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1046 if (ctrl_proj != NULL) {
1047 _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1048 #ifdef ASSERT
1049 Node* tmp = init->in(TypeFunc::Control);
1050 assert(tmp == _fallthroughcatchproj, "allocation control projection");
1051 #endif
1052 }
1053 Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
1054 if (mem_proj != NULL) {
1055 Node *mem = init->in(TypeFunc::Memory);
1056 #ifdef ASSERT
1057 if (mem->is_MergeMem()) {
1058 assert(mem->in(TypeFunc::Memory) == _memproj_fallthrough, "allocation memory projection");
1059 } else {
1060 assert(mem == _memproj_fallthrough, "allocation memory projection");
1061 }
1062 #endif
1063 _igvn.replace_node(mem_proj, mem);
1064 }
1065 } else {
1066 assert(false, "only Initialize or AddP expected");
1067 }
1068 j -= (oc1 - _resproj->outcnt());
1069 }
1070 }
1071 if (_fallthroughcatchproj != NULL) {
1072 _igvn.replace_node(_fallthroughcatchproj, alloc->in(TypeFunc::Control));
1073 }
1074 if (_memproj_fallthrough != NULL) {
1075 _igvn.replace_node(_memproj_fallthrough, alloc->in(TypeFunc::Memory));
1076 }
1077 if (_memproj_catchall != NULL) {
1078 _igvn.replace_node(_memproj_catchall, C->top());
1079 }
1080 if (_ioproj_fallthrough != NULL) {
1081 _igvn.replace_node(_ioproj_fallthrough, alloc->in(TypeFunc::I_O));
1082 }
1083 if (_ioproj_catchall != NULL) {
1084 _igvn.replace_node(_ioproj_catchall, C->top());
1085 }
1086 if (_catchallcatchproj != NULL) {
1087 _igvn.replace_node(_catchallcatchproj, C->top());
1088 }
1089 }
1090
1091 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1092 // Don't do scalar replacement if the frame can be popped by JVMTI:
1093 // if reallocation fails during deoptimization we'll pop all
1094 // interpreter frames for this compiled frame and that won't play
1095 // nice with JVMTI popframe.
1096 if (!EliminateAllocations || JvmtiExport::can_pop_frame() || !alloc->_is_non_escaping) {
1097 return false;
1098 }
1099 Node* klass = alloc->in(AllocateNode::KlassNode);
1100 const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1101 Node* res = alloc->result_cast();
1102 // Eliminate boxing allocations which are not used
1103 // regardless scalar replacable status.
1104 bool boxing_alloc = C->eliminate_boxing() &&
1105 tklass->klass()->is_instance_klass() &&
1106 tklass->klass()->as_instance_klass()->is_box_klass();
1107 if (!alloc->_is_scalar_replaceable && (!boxing_alloc || (res != NULL))) {
1108 return false;
1109 }
1110
1111 extract_call_projections(alloc);
1112
1113 GrowableArray <SafePointNode *> safepoints;
1114 if (!can_eliminate_allocation(alloc, safepoints)) {
1115 return false;
1116 }
1117
1118 if (!alloc->_is_scalar_replaceable) {
1119 assert(res == NULL, "sanity");
1120 // We can only eliminate allocation if all debug info references
1121 // are already replaced with SafePointScalarObject because
1122 // we can't search for a fields value without instance_id.
1123 if (safepoints.length() > 0) {
1124 return false;
1125 }
1126 }
1127
1128 if (!scalar_replacement(alloc, safepoints)) {
1129 return false;
1130 }
1131
1132 CompileLog* log = C->log();
1133 if (log != NULL) {
1134 log->head("eliminate_allocation type='%d'",
1135 log->identify(tklass->klass()));
1136 JVMState* p = alloc->jvms();
1137 while (p != NULL) {
1138 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1139 p = p->caller();
1140 }
1141 log->tail("eliminate_allocation");
1142 }
1143
1144 process_users_of_allocation(alloc);
1145
1146 #ifndef PRODUCT
1147 if (PrintEliminateAllocations) {
1148 if (alloc->is_AllocateArray())
1149 tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1150 else
1151 tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1152 }
1153 #endif
1154
1155 return true;
1156 }
1157
1158 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1159 // EA should remove all uses of non-escaping boxing node.
1160 if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != NULL) {
1161 return false;
1162 }
1163
1164 assert(boxing->result_cast() == NULL, "unexpected boxing node result");
1165
1166 extract_call_projections(boxing);
1167
1168 const TypeTuple* r = boxing->tf()->range();
1169 assert(r->cnt() > TypeFunc::Parms, "sanity");
1170 const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1171 assert(t != NULL, "sanity");
1172
1173 CompileLog* log = C->log();
1174 if (log != NULL) {
1175 log->head("eliminate_boxing type='%d'",
1176 log->identify(t->klass()));
1177 JVMState* p = boxing->jvms();
1178 while (p != NULL) {
1179 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1180 p = p->caller();
1181 }
1182 log->tail("eliminate_boxing");
1183 }
1184
1185 process_users_of_allocation(boxing);
1186
1187 #ifndef PRODUCT
1188 if (PrintEliminateAllocations) {
1349 }
1350 }
1351 #endif
1352 yank_alloc_node(alloc);
1353 return;
1354 }
1355 }
1356
1357 enum { too_big_or_final_path = 1, need_gc_path = 2 };
1358 Node *slow_region = NULL;
1359 Node *toobig_false = ctrl;
1360
1361 // generate the initial test if necessary
1362 if (initial_slow_test != NULL ) {
1363 assert (expand_fast_path, "Only need test if there is a fast path");
1364 slow_region = new RegionNode(3);
1365
1366 // Now make the initial failure test. Usually a too-big test but
1367 // might be a TRUE for finalizers or a fancy class check for
1368 // newInstance0.
1369 IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1370 transform_later(toobig_iff);
1371 // Plug the failing-too-big test into the slow-path region
1372 Node *toobig_true = new IfTrueNode( toobig_iff );
1373 transform_later(toobig_true);
1374 slow_region ->init_req( too_big_or_final_path, toobig_true );
1375 toobig_false = new IfFalseNode( toobig_iff );
1376 transform_later(toobig_false);
1377 } else {
1378 // No initial test, just fall into next case
1379 assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1380 toobig_false = ctrl;
1381 debug_only(slow_region = NodeSentinel);
1382 }
1383
1384 // If we are here there are several possibilities
1385 // - expand_fast_path is false - then only a slow path is expanded. That's it.
1386 // no_initial_check means a constant allocation.
1387 // - If check always evaluates to false -> expand_fast_path is false (see above)
1388 // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1389 // if !allocation_has_use the fast path is empty
1390 // if !allocation_has_use && no_initial_check
1391 // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1392 // removed by yank_alloc_node above.
1393
1394 Node *slow_mem = mem; // save the current memory state for slow path
1395 // generate the fast allocation code unless we know that the initial test will always go slow
1396 if (expand_fast_path) {
1397 // Fast path modifies only raw memory.
1398 if (mem->is_MergeMem()) {
1399 mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1400 }
1401
1402 // allocate the Region and Phi nodes for the result
1403 result_region = new RegionNode(3);
1404 result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1405 result_phi_i_o = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1406
1407 // Grab regular I/O before optional prefetch may change it.
1408 // Slow-path does no I/O so just set it to the original I/O.
1409 result_phi_i_o->init_req(slow_result_path, i_o);
1410
1411 // Name successful fast-path variables
1412 Node* fast_oop_ctrl;
1413 Node* fast_oop_rawmem;
1414 if (allocation_has_use) {
1415 Node* needgc_ctrl = NULL;
1416 result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1417
1418 intx prefetch_lines = length != NULL ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1419 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1420 Node* fast_oop = bs->obj_allocate(this, ctrl, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1421 fast_oop_ctrl, fast_oop_rawmem,
1422 prefetch_lines);
1423
1424 if (initial_slow_test != NULL) {
1425 // This completes all paths into the slow merge point
1426 slow_region->init_req(need_gc_path, needgc_ctrl);
1427 transform_later(slow_region);
1428 } else {
1429 // No initial slow path needed!
1430 // Just fall from the need-GC path straight into the VM call.
1431 slow_region = needgc_ctrl;
1432 }
1433
1452 result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1453 } else {
1454 slow_region = ctrl;
1455 result_phi_i_o = i_o; // Rename it to use in the following code.
1456 }
1457
1458 // Generate slow-path call
1459 CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1460 OptoRuntime::stub_name(slow_call_address),
1461 alloc->jvms()->bci(),
1462 TypePtr::BOTTOM);
1463 call->init_req(TypeFunc::Control, slow_region);
1464 call->init_req(TypeFunc::I_O, top()); // does no i/o
1465 call->init_req(TypeFunc::Memory, slow_mem); // may gc ptrs
1466 call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1467 call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1468
1469 call->init_req(TypeFunc::Parms+0, klass_node);
1470 if (length != NULL) {
1471 call->init_req(TypeFunc::Parms+1, length);
1472 }
1473
1474 // Copy debug information and adjust JVMState information, then replace
1475 // allocate node with the call
1476 copy_call_debug_info((CallNode *) alloc, call);
1477 if (expand_fast_path) {
1478 call->set_cnt(PROB_UNLIKELY_MAG(4)); // Same effect as RC_UNCOMMON.
1479 } else {
1480 // Hook i_o projection to avoid its elimination during allocation
1481 // replacement (when only a slow call is generated).
1482 call->set_req(TypeFunc::I_O, result_phi_i_o);
1483 }
1484 _igvn.replace_node(alloc, call);
1485 transform_later(call);
1486
1487 // Identify the output projections from the allocate node and
1488 // adjust any references to them.
1489 // The control and io projections look like:
1490 //
1491 // v---Proj(ctrl) <-----+ v---CatchProj(ctrl)
1492 // Allocate Catch
1493 // ^---Proj(io) <-------+ ^---CatchProj(io)
1494 //
1495 // We are interested in the CatchProj nodes.
1496 //
1497 extract_call_projections(call);
1498
1499 // An allocate node has separate memory projections for the uses on
1500 // the control and i_o paths. Replace the control memory projection with
1501 // result_phi_rawmem (unless we are only generating a slow call when
1502 // both memory projections are combined)
1503 if (expand_fast_path && _memproj_fallthrough != NULL) {
1504 migrate_outs(_memproj_fallthrough, result_phi_rawmem);
1505 }
1506 // Now change uses of _memproj_catchall to use _memproj_fallthrough and delete
1507 // _memproj_catchall so we end up with a call that has only 1 memory projection.
1508 if (_memproj_catchall != NULL ) {
1509 if (_memproj_fallthrough == NULL) {
1510 _memproj_fallthrough = new ProjNode(call, TypeFunc::Memory);
1511 transform_later(_memproj_fallthrough);
1512 }
1513 migrate_outs(_memproj_catchall, _memproj_fallthrough);
1514 _igvn.remove_dead_node(_memproj_catchall);
1515 }
1516
1517 // An allocate node has separate i_o projections for the uses on the control
1518 // and i_o paths. Always replace the control i_o projection with result i_o
1519 // otherwise incoming i_o become dead when only a slow call is generated
1520 // (it is different from memory projections where both projections are
1521 // combined in such case).
1522 if (_ioproj_fallthrough != NULL) {
1523 migrate_outs(_ioproj_fallthrough, result_phi_i_o);
1524 }
1525 // Now change uses of _ioproj_catchall to use _ioproj_fallthrough and delete
1526 // _ioproj_catchall so we end up with a call that has only 1 i_o projection.
1527 if (_ioproj_catchall != NULL ) {
1528 if (_ioproj_fallthrough == NULL) {
1529 _ioproj_fallthrough = new ProjNode(call, TypeFunc::I_O);
1530 transform_later(_ioproj_fallthrough);
1531 }
1532 migrate_outs(_ioproj_catchall, _ioproj_fallthrough);
1533 _igvn.remove_dead_node(_ioproj_catchall);
1534 }
1535
1536 // if we generated only a slow call, we are done
1537 if (!expand_fast_path) {
1538 // Now we can unhook i_o.
1539 if (result_phi_i_o->outcnt() > 1) {
1540 call->set_req(TypeFunc::I_O, top());
1541 } else {
1542 assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1543 // Case of new array with negative size known during compilation.
1544 // AllocateArrayNode::Ideal() optimization disconnect unreachable
1545 // following code since call to runtime will throw exception.
1546 // As result there will be no users of i_o after the call.
1547 // Leave i_o attached to this call to avoid problems in preceding graph.
1548 }
1549 return;
1550 }
1551
1552 if (_fallthroughcatchproj != NULL) {
1580 }
1581
1582 // Remove alloc node that has no uses.
1583 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1584 Node* ctrl = alloc->in(TypeFunc::Control);
1585 Node* mem = alloc->in(TypeFunc::Memory);
1586 Node* i_o = alloc->in(TypeFunc::I_O);
1587
1588 extract_call_projections(alloc);
1589 if (_resproj != NULL) {
1590 for (DUIterator_Fast imax, i = _resproj->fast_outs(imax); i < imax; i++) {
1591 Node* use = _resproj->fast_out(i);
1592 use->isa_MemBar()->remove(&_igvn);
1593 --imax;
1594 --i; // back up iterator
1595 }
1596 assert(_resproj->outcnt() == 0, "all uses must be deleted");
1597 _igvn.remove_dead_node(_resproj);
1598 }
1599 if (_fallthroughcatchproj != NULL) {
1600 migrate_outs(_fallthroughcatchproj, ctrl);
1601 _igvn.remove_dead_node(_fallthroughcatchproj);
1602 }
1603 if (_catchallcatchproj != NULL) {
1604 _igvn.rehash_node_delayed(_catchallcatchproj);
1605 _catchallcatchproj->set_req(0, top());
1606 }
1607 if (_fallthroughproj != NULL) {
1608 Node* catchnode = _fallthroughproj->unique_ctrl_out();
1609 _igvn.remove_dead_node(catchnode);
1610 _igvn.remove_dead_node(_fallthroughproj);
1611 }
1612 if (_memproj_fallthrough != NULL) {
1613 migrate_outs(_memproj_fallthrough, mem);
1614 _igvn.remove_dead_node(_memproj_fallthrough);
1615 }
1616 if (_ioproj_fallthrough != NULL) {
1617 migrate_outs(_ioproj_fallthrough, i_o);
1618 _igvn.remove_dead_node(_ioproj_fallthrough);
1619 }
1620 if (_memproj_catchall != NULL) {
1621 _igvn.rehash_node_delayed(_memproj_catchall);
1622 _memproj_catchall->set_req(0, top());
1623 }
1624 if (_ioproj_catchall != NULL) {
1625 _igvn.rehash_node_delayed(_ioproj_catchall);
1626 _ioproj_catchall->set_req(0, top());
1627 }
1628 #ifndef PRODUCT
1629 if (PrintEliminateAllocations) {
1630 if (alloc->is_AllocateArray()) {
1631 tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1632 } else {
1633 tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1634 }
1635 }
1636 #endif
1637 _igvn.remove_dead_node(alloc);
1723 Node* thread = new ThreadLocalNode();
1724 transform_later(thread);
1725
1726 call->init_req(TypeFunc::Parms + 0, thread);
1727 call->init_req(TypeFunc::Parms + 1, oop);
1728 call->init_req(TypeFunc::Control, ctrl);
1729 call->init_req(TypeFunc::I_O , top()); // does no i/o
1730 call->init_req(TypeFunc::Memory , ctrl);
1731 call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1732 call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1733 transform_later(call);
1734 ctrl = new ProjNode(call, TypeFunc::Control);
1735 transform_later(ctrl);
1736 rawmem = new ProjNode(call, TypeFunc::Memory);
1737 transform_later(rawmem);
1738 }
1739 }
1740
1741 // Helper for PhaseMacroExpand::expand_allocate_common.
1742 // Initializes the newly-allocated storage.
1743 Node*
1744 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1745 Node* control, Node* rawmem, Node* object,
1746 Node* klass_node, Node* length,
1747 Node* size_in_bytes) {
1748 InitializeNode* init = alloc->initialization();
1749 // Store the klass & mark bits
1750 Node* mark_node = alloc->make_ideal_mark(&_igvn, object, control, rawmem);
1751 if (!mark_node->is_Con()) {
1752 transform_later(mark_node);
1753 }
1754 rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1755
1756 rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1757 int header_size = alloc->minimum_header_size(); // conservatively small
1758
1759 // Array length
1760 if (length != NULL) { // Arrays need length field
1761 rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1762 // conservatively small header size:
1763 header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1764 ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1765 if (k->is_array_klass()) // we know the exact header size in most cases:
1766 header_size = Klass::layout_helper_header_size(k->layout_helper());
1767 }
1768
1769 // Clear the object body, if necessary.
1770 if (init == NULL) {
1771 // The init has somehow disappeared; be cautious and clear everything.
1772 //
1773 // This can happen if a node is allocated but an uncommon trap occurs
1774 // immediately. In this case, the Initialize gets associated with the
1775 // trap, and may be placed in a different (outer) loop, if the Allocate
1776 // is in a loop. If (this is rare) the inner loop gets unrolled, then
1777 // there can be two Allocates to one Initialize. The answer in all these
1778 // edge cases is safety first. It is always safe to clear immediately
1779 // within an Allocate, and then (maybe or maybe not) clear some more later.
1780 if (!(UseTLAB && ZeroTLAB)) {
1781 rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1782 header_size, size_in_bytes,
1783 &_igvn);
1784 }
1785 } else {
1786 if (!init->is_complete()) {
1787 // Try to win by zeroing only what the init does not store.
1788 // We can also try to do some peephole optimizations,
1789 // such as combining some adjacent subword stores.
1790 rawmem = init->complete_stores(control, rawmem, object,
1791 header_size, size_in_bytes, &_igvn);
1792 }
1793 // We have no more use for this link, since the AllocateNode goes away:
1794 init->set_req(InitializeNode::RawAddress, top());
1795 // (If we keep the link, it just confuses the register allocator,
1796 // who thinks he sees a real use of the address by the membar.)
1797 }
1798
1799 return rawmem;
1800 }
1801
2142 // Replace old box node with new eliminated box for all users
2143 // of the same object and mark related locks as eliminated.
2144 mark_eliminated_box(box, obj);
2145 }
2146 }
2147 }
2148 }
2149
2150 // we have determined that this lock/unlock can be eliminated, we simply
2151 // eliminate the node without expanding it.
2152 //
2153 // Note: The membar's associated with the lock/unlock are currently not
2154 // eliminated. This should be investigated as a future enhancement.
2155 //
2156 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2157
2158 if (!alock->is_eliminated()) {
2159 return false;
2160 }
2161 #ifdef ASSERT
2162 if (!alock->is_coarsened()) {
2163 // Check that new "eliminated" BoxLock node is created.
2164 BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2165 assert(oldbox->is_eliminated(), "should be done already");
2166 }
2167 #endif
2168
2169 alock->log_lock_optimization(C, "eliminate_lock");
2170
2171 #ifndef PRODUCT
2172 if (PrintEliminateLocks) {
2173 if (alock->is_Lock()) {
2174 tty->print_cr("++++ Eliminated: %d Lock", alock->_idx);
2175 } else {
2176 tty->print_cr("++++ Eliminated: %d Unlock", alock->_idx);
2177 }
2178 }
2179 #endif
2180
2181 Node* mem = alock->in(TypeFunc::Memory);
2423 // region->in(2) is set to fast path - the object is locked to the current thread.
2424
2425 slow_path->init_req(2, ctrl); // Capture slow-control
2426 slow_mem->init_req(2, fast_lock_mem_phi);
2427
2428 transform_later(slow_path);
2429 transform_later(slow_mem);
2430 // Reset lock's memory edge.
2431 lock->set_req(TypeFunc::Memory, slow_mem);
2432
2433 } else {
2434 region = new RegionNode(3);
2435 // create a Phi for the memory state
2436 mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2437
2438 // Optimize test; set region slot 2
2439 slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2440 mem_phi->init_req(2, mem);
2441 }
2442
2443 // Make slow path call
2444 CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2445 OptoRuntime::complete_monitor_locking_Java(), NULL, slow_path,
2446 obj, box, NULL);
2447
2448 extract_call_projections(call);
2449
2450 // Slow path can only throw asynchronous exceptions, which are always
2451 // de-opted. So the compiler thinks the slow-call can never throw an
2452 // exception. If it DOES throw an exception we would need the debug
2453 // info removed first (since if it throws there is no monitor).
2454 assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
2455 _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
2456
2457 // Capture slow path
2458 // disconnect fall-through projection from call and create a new one
2459 // hook up users of fall-through projection to region
2460 Node *slow_ctrl = _fallthroughproj->clone();
2461 transform_later(slow_ctrl);
2462 _igvn.hash_delete(_fallthroughproj);
2524 // No exceptions for unlocking
2525 // Capture slow path
2526 // disconnect fall-through projection from call and create a new one
2527 // hook up users of fall-through projection to region
2528 Node *slow_ctrl = _fallthroughproj->clone();
2529 transform_later(slow_ctrl);
2530 _igvn.hash_delete(_fallthroughproj);
2531 _fallthroughproj->disconnect_inputs(NULL, C);
2532 region->init_req(1, slow_ctrl);
2533 // region inputs are now complete
2534 transform_later(region);
2535 _igvn.replace_node(_fallthroughproj, region);
2536
2537 Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2538 mem_phi->init_req(1, memproj );
2539 mem_phi->init_req(2, mem);
2540 transform_later(mem_phi);
2541 _igvn.replace_node(_memproj_fallthrough, mem_phi);
2542 }
2543
2544 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2545 assert(check->in(SubTypeCheckNode::Control) == NULL, "should be pinned");
2546 Node* bol = check->unique_out();
2547 Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2548 Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2549 assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2550
2551 for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2552 Node* iff = bol->last_out(i);
2553 assert(iff->is_If(), "where's the if?");
2554
2555 if (iff->in(0)->is_top()) {
2556 _igvn.replace_input_of(iff, 1, C->top());
2557 continue;
2558 }
2559
2560 Node* iftrue = iff->as_If()->proj_out(1);
2561 Node* iffalse = iff->as_If()->proj_out(0);
2562 Node* ctrl = iff->in(0);
2563
2564 Node* subklass = NULL;
2565 if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2566 subklass = obj_or_subklass;
2567 } else {
2568 Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2569 subklass = _igvn.transform(LoadKlassNode::make(_igvn, NULL, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2570 }
2571
2572 Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, NULL, _igvn);
2573
2574 _igvn.replace_input_of(iff, 0, C->top());
2575 _igvn.replace_node(iftrue, not_subtype_ctrl);
2576 _igvn.replace_node(iffalse, ctrl);
2577 }
2578 _igvn.replace_node(check, C->top());
2579 }
2580
2581 //---------------------------eliminate_macro_nodes----------------------
2582 // Eliminate scalar replaced allocations and associated locks.
2583 void PhaseMacroExpand::eliminate_macro_nodes() {
2584 if (C->macro_count() == 0)
2585 return;
2586
2587 // First, attempt to eliminate locks
2588 int cnt = C->macro_count();
2589 for (int i=0; i < cnt; i++) {
2605 success = eliminate_locking_node(n->as_AbstractLock());
2606 }
2607 assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2608 progress = progress || success;
2609 }
2610 }
2611 // Next, attempt to eliminate allocations
2612 _has_locks = false;
2613 progress = true;
2614 while (progress) {
2615 progress = false;
2616 for (int i = C->macro_count(); i > 0; i--) {
2617 Node * n = C->macro_node(i-1);
2618 bool success = false;
2619 debug_only(int old_macro_count = C->macro_count(););
2620 switch (n->class_id()) {
2621 case Node::Class_Allocate:
2622 case Node::Class_AllocateArray:
2623 success = eliminate_allocate_node(n->as_Allocate());
2624 break;
2625 case Node::Class_CallStaticJava:
2626 success = eliminate_boxing_node(n->as_CallStaticJava());
2627 break;
2628 case Node::Class_Lock:
2629 case Node::Class_Unlock:
2630 assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2631 _has_locks = true;
2632 break;
2633 case Node::Class_ArrayCopy:
2634 break;
2635 case Node::Class_OuterStripMinedLoop:
2636 break;
2637 case Node::Class_SubTypeCheck:
2638 break;
2639 default:
2640 assert(n->Opcode() == Op_LoopLimit ||
2641 n->Opcode() == Op_Opaque1 ||
2642 n->Opcode() == Op_Opaque2 ||
2643 n->Opcode() == Op_Opaque3 ||
2644 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2645 "unknown node type in macro list");
2646 }
2647 assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2653 //------------------------------expand_macro_nodes----------------------
2654 // Returns true if a failure occurred.
2655 bool PhaseMacroExpand::expand_macro_nodes() {
2656 // Last attempt to eliminate macro nodes.
2657 eliminate_macro_nodes();
2658
2659 // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2660 bool progress = true;
2661 while (progress) {
2662 progress = false;
2663 for (int i = C->macro_count(); i > 0; i--) {
2664 Node* n = C->macro_node(i-1);
2665 bool success = false;
2666 debug_only(int old_macro_count = C->macro_count(););
2667 if (n->Opcode() == Op_LoopLimit) {
2668 // Remove it from macro list and put on IGVN worklist to optimize.
2669 C->remove_macro_node(n);
2670 _igvn._worklist.push(n);
2671 success = true;
2672 } else if (n->Opcode() == Op_CallStaticJava) {
2673 // Remove it from macro list and put on IGVN worklist to optimize.
2674 C->remove_macro_node(n);
2675 _igvn._worklist.push(n);
2676 success = true;
2677 } else if (n->Opcode() == Op_Opaque1 || n->Opcode() == Op_Opaque2) {
2678 _igvn.replace_node(n, n->in(1));
2679 success = true;
2680 #if INCLUDE_RTM_OPT
2681 } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2682 assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2683 assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2684 Node* cmp = n->unique_out();
2685 #ifdef ASSERT
2686 // Validate graph.
2687 assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2688 BoolNode* bol = cmp->unique_out()->as_Bool();
2689 assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2690 (bol->_test._test == BoolTest::ne), "");
2691 IfNode* ifn = bol->unique_out()->as_If();
2692 assert((ifn->outcnt() == 2) &&
2693 ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != NULL, "");
2694 #endif
2695 Node* repl = n->in(1);
2696 if (!_has_locks) {
2750 }
2751
2752 debug_only(int old_macro_count = C->macro_count(););
2753 switch (n->class_id()) {
2754 case Node::Class_Lock:
2755 expand_lock_node(n->as_Lock());
2756 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2757 break;
2758 case Node::Class_Unlock:
2759 expand_unlock_node(n->as_Unlock());
2760 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2761 break;
2762 case Node::Class_ArrayCopy:
2763 expand_arraycopy_node(n->as_ArrayCopy());
2764 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2765 break;
2766 case Node::Class_SubTypeCheck:
2767 expand_subtypecheck_node(n->as_SubTypeCheck());
2768 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2769 break;
2770 default:
2771 assert(false, "unknown node type in macro list");
2772 }
2773 assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2774 if (C->failing()) return true;
2775
2776 // Clean up the graph so we're less likely to hit the maximum node
2777 // limit
2778 _igvn.set_delay_transform(false);
2779 _igvn.optimize();
2780 if (C->failing()) return true;
2781 _igvn.set_delay_transform(true);
2782 }
2783
2784 // All nodes except Allocate nodes are expanded now. There could be
2785 // new optimization opportunities (such as folding newly created
2786 // load from a just allocated object). Run IGVN.
2787
2788 // expand "macro" nodes
2789 // nodes are removed from the macro list as they are processed
|
1 /*
2 * Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "ci/ciFlatArrayKlass.hpp"
27 #include "compiler/compileLog.hpp"
28 #include "gc/shared/collectedHeap.inline.hpp"
29 #include "libadt/vectset.hpp"
30 #include "memory/universe.hpp"
31 #include "opto/addnode.hpp"
32 #include "opto/arraycopynode.hpp"
33 #include "opto/callnode.hpp"
34 #include "opto/castnode.hpp"
35 #include "opto/cfgnode.hpp"
36 #include "opto/compile.hpp"
37 #include "opto/convertnode.hpp"
38 #include "opto/graphKit.hpp"
39 #include "opto/inlinetypenode.hpp"
40 #include "opto/intrinsicnode.hpp"
41 #include "opto/locknode.hpp"
42 #include "opto/loopnode.hpp"
43 #include "opto/macro.hpp"
44 #include "opto/memnode.hpp"
45 #include "opto/narrowptrnode.hpp"
46 #include "opto/node.hpp"
47 #include "opto/opaquenode.hpp"
48 #include "opto/phaseX.hpp"
49 #include "opto/rootnode.hpp"
50 #include "opto/runtime.hpp"
51 #include "opto/subnode.hpp"
52 #include "opto/subtypenode.hpp"
53 #include "opto/type.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
67 // Returns the number of replacements made.
68 //
69 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
70 int nreplacements = 0;
71 uint req = use->req();
72 for (uint j = 0; j < use->len(); j++) {
73 Node *uin = use->in(j);
74 if (uin == oldref) {
75 if (j < req)
76 use->set_req(j, newref);
77 else
78 use->set_prec(j, newref);
79 nreplacements++;
80 } else if (j >= req && uin == NULL) {
81 break;
82 }
83 }
84 return nreplacements;
85 }
86
87 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word, int mask, int bits, bool return_fast_path) {
88 Node* cmp;
89 if (mask != 0) {
90 Node* and_node = transform_later(new AndXNode(word, MakeConX(mask)));
91 cmp = transform_later(new CmpXNode(and_node, MakeConX(bits)));
92 } else {
93 cmp = word;
94 }
95 Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
96 IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
97 transform_later(iff);
98
99 // Fast path taken.
100 Node *fast_taken = transform_later(new IfFalseNode(iff));
101
102 // Fast path not-taken, i.e. slow path
103 Node *slow_taken = transform_later(new IfTrueNode(iff));
104
105 if (return_fast_path) {
106 region->init_req(edge, slow_taken); // Capture slow-control
119 call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ?????
120 call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) );
121 call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) );
122 }
123
124 //------------------------------make_slow_call---------------------------------
125 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type,
126 address slow_call, const char* leaf_name, Node* slow_path,
127 Node* parm0, Node* parm1, Node* parm2) {
128
129 // Slow-path call
130 CallNode *call = leaf_name
131 ? (CallNode*)new CallLeafNode ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
132 : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), oldcall->jvms()->bci(), TypeRawPtr::BOTTOM );
133
134 // Slow path call has no side-effects, uses few values
135 copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
136 if (parm0 != NULL) call->init_req(TypeFunc::Parms+0, parm0);
137 if (parm1 != NULL) call->init_req(TypeFunc::Parms+1, parm1);
138 if (parm2 != NULL) call->init_req(TypeFunc::Parms+2, parm2);
139 call->copy_call_debug_info(&_igvn, oldcall);
140 call->set_cnt(PROB_UNLIKELY_MAG(4)); // Same effect as RC_UNCOMMON.
141 _igvn.replace_node(oldcall, call);
142 transform_later(call);
143
144 return call;
145 }
146
147 void PhaseMacroExpand::extract_call_projections(CallNode *call) {
148 _fallthroughproj = NULL;
149 _fallthroughcatchproj = NULL;
150 _ioproj_fallthrough = NULL;
151 _ioproj_catchall = NULL;
152 _catchallcatchproj = NULL;
153 _memproj_fallthrough = NULL;
154 _memproj_catchall = NULL;
155 _resproj = NULL;
156 for (DUIterator_Fast imax, i = call->fast_outs(imax); i < imax; i++) {
157 ProjNode *pn = call->fast_out(i)->as_Proj();
158 switch (pn->_con) {
159 case TypeFunc::Control:
227 if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
228 return in;
229 }
230 }
231 mem = in->in(TypeFunc::Memory);
232 } else if (in->is_MemBar()) {
233 ArrayCopyNode* ac = NULL;
234 if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
235 assert(ac != NULL && ac->is_clonebasic(), "Only basic clone is a non escaping clone");
236 return ac;
237 }
238 mem = in->in(TypeFunc::Memory);
239 } else {
240 assert(false, "unexpected projection");
241 }
242 } else if (mem->is_Store()) {
243 const TypePtr* atype = mem->as_Store()->adr_type();
244 int adr_idx = phase->C->get_alias_index(atype);
245 if (adr_idx == alias_idx) {
246 assert(atype->isa_oopptr(), "address type must be oopptr");
247 int adr_offset = atype->flattened_offset();
248 uint adr_iid = atype->is_oopptr()->instance_id();
249 // Array elements references have the same alias_idx
250 // but different offset and different instance_id.
251 if (adr_offset == offset && adr_iid == alloc->_idx)
252 return mem;
253 } else {
254 assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
255 }
256 mem = mem->in(MemNode::Memory);
257 } else if (mem->is_ClearArray()) {
258 if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
259 // Can not bypass initialization of the instance
260 // we are looking.
261 debug_only(intptr_t offset;)
262 assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
263 InitializeNode* init = alloc->as_Allocate()->initialization();
264 // We are looking for stored value, return Initialize node
265 // or memory edge from Allocate node.
266 if (init != NULL)
267 return init;
270 }
271 // Otherwise skip it (the call updated 'mem' value).
272 } else if (mem->Opcode() == Op_SCMemProj) {
273 mem = mem->in(0);
274 Node* adr = NULL;
275 if (mem->is_LoadStore()) {
276 adr = mem->in(MemNode::Address);
277 } else {
278 assert(mem->Opcode() == Op_EncodeISOArray ||
279 mem->Opcode() == Op_StrCompressedCopy, "sanity");
280 adr = mem->in(3); // Destination array
281 }
282 const TypePtr* atype = adr->bottom_type()->is_ptr();
283 int adr_idx = phase->C->get_alias_index(atype);
284 if (adr_idx == alias_idx) {
285 DEBUG_ONLY(mem->dump();)
286 assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
287 return NULL;
288 }
289 mem = mem->in(MemNode::Memory);
290 } else if (mem->Opcode() == Op_StrInflatedCopy) {
291 Node* adr = mem->in(3); // Destination array
292 const TypePtr* atype = adr->bottom_type()->is_ptr();
293 int adr_idx = phase->C->get_alias_index(atype);
294 if (adr_idx == alias_idx) {
295 DEBUG_ONLY(mem->dump();)
296 assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
297 return NULL;
298 }
299 mem = mem->in(MemNode::Memory);
300 } else {
301 return mem;
302 }
303 assert(mem != orig_mem, "dead memory loop");
304 }
305 }
306
307 // Generate loads from source of the arraycopy for fields of
308 // destination needed at a deoptimization point
309 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
310 BasicType bt = ft;
315 }
316 Node* res = NULL;
317 if (ac->is_clonebasic()) {
318 assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
319 Node* base = ac->in(ArrayCopyNode::Src);
320 Node* adr = _igvn.transform(new AddPNode(base, base, MakeConX(offset)));
321 const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
322 MergeMemNode* mergemen = MergeMemNode::make(mem);
323 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
324 res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
325 } else {
326 if (ac->modifies(offset, offset, &_igvn, true)) {
327 assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
328 uint shift = exact_log2(type2aelembytes(bt));
329 Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
330 Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
331 const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
332 const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
333
334 Node* adr = NULL;
335 Node* base = ac->in(ArrayCopyNode::Src);
336 const TypePtr* adr_type = _igvn.type(base)->is_ptr();
337 assert(adr_type->isa_aryptr(), "only arrays here");
338 if (src_pos_t->is_con() && dest_pos_t->is_con()) {
339 intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
340 adr = _igvn.transform(new AddPNode(base, base, MakeConX(off)));
341 adr_type = _igvn.type(adr)->is_ptr();
342 assert(adr_type == _igvn.type(base)->is_aryptr()->add_field_offset_and_offset(off), "incorrect address type");
343 if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
344 // Don't emit a new load from src if src == dst but try to get the value from memory instead
345 return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type->isa_oopptr(), alloc);
346 }
347 } else {
348 if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
349 // Non constant offset in the array: we can't statically
350 // determine the value
351 return NULL;
352 }
353 Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
354 #ifdef _LP64
355 diff = _igvn.transform(new ConvI2LNode(diff));
356 #endif
357 diff = _igvn.transform(new LShiftXNode(diff, intcon(shift)));
358
359 Node* off = _igvn.transform(new AddXNode(MakeConX(offset), diff));
360 adr = _igvn.transform(new AddPNode(base, base, off));
361 // In the case of a flattened inline type array, each field has its
362 // own slice so we need to extract the field being accessed from
363 // the address computation
364 adr_type = adr_type->is_aryptr()->add_field_offset_and_offset(offset)->add_offset(Type::OffsetBot);
365 adr = _igvn.transform(new CastPPNode(adr, adr_type));
366 }
367 MergeMemNode* mergemen = MergeMemNode::make(mem);
368 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
369 res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
370 }
371 }
372 if (res != NULL) {
373 if (ftype->isa_narrowoop()) {
374 // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
375 assert(res->isa_DecodeN(), "should be narrow oop");
376 res = _igvn.transform(new EncodePNode(res, ftype));
377 }
378 return res;
379 }
380 return NULL;
381 }
382
383 //
384 // Given a Memory Phi, compute a value Phi containing the values from stores
385 // on the input paths.
386 // Note: this function is recursive, its depth is limited by the "level" argument
387 // Returns the computed Phi, or NULL if it cannot compute it.
388 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) {
389 assert(mem->is_Phi(), "sanity");
390 int alias_idx = C->get_alias_index(adr_t);
391 int offset = adr_t->flattened_offset();
392 int instance_id = adr_t->instance_id();
393
394 // Check if an appropriate value phi already exists.
395 Node* region = mem->in(0);
396 for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
397 Node* phi = region->fast_out(k);
398 if (phi->is_Phi() && phi != mem &&
399 phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
400 return phi;
401 }
402 }
403 // Check if an appropriate new value phi already exists.
404 Node* new_phi = value_phis->find(mem->_idx);
405 if (new_phi != NULL)
406 return new_phi;
407
408 if (level <= 0) {
409 return NULL; // Give up: phi tree too deep
410 }
411 Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
412 Node *alloc_mem = alloc->in(TypeFunc::Memory);
413
414 uint length = mem->req();
415 GrowableArray <Node *> values(length, length, NULL);
416
417 // create a new Phi for the value
418 PhiNode *phi = new PhiNode(mem->in(0), phi_type, NULL, mem->_idx, instance_id, alias_idx, offset);
419 transform_later(phi);
420 value_phis->push(phi, mem->_idx);
421
422 for (uint j = 1; j < length; j++) {
423 Node *in = mem->in(j);
424 if (in == NULL || in->is_top()) {
425 values.at_put(j, in);
426 } else {
427 Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
428 if (val == start_mem || val == alloc_mem) {
429 // hit a sentinel, return appropriate 0 value
430 Node* default_value = alloc->in(AllocateNode::DefaultValue);
431 if (default_value != NULL) {
432 values.at_put(j, default_value);
433 } else {
434 assert(alloc->in(AllocateNode::RawDefaultValue) == NULL, "default value may not be null");
435 values.at_put(j, _igvn.zerocon(ft));
436 }
437 continue;
438 }
439 if (val->is_Initialize()) {
440 val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
441 }
442 if (val == NULL) {
443 return NULL; // can't find a value on this path
444 }
445 if (val == mem) {
446 values.at_put(j, mem);
447 } else if (val->is_Store()) {
448 Node* n = val->in(MemNode::ValueIn);
449 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
450 n = bs->step_over_gc_barrier(n);
451 values.at_put(j, n);
452 } else if(val->is_Proj() && val->in(0) == alloc) {
453 Node* default_value = alloc->in(AllocateNode::DefaultValue);
454 if (default_value != NULL) {
455 values.at_put(j, default_value);
456 } else {
457 assert(alloc->in(AllocateNode::RawDefaultValue) == NULL, "default value may not be null");
458 values.at_put(j, _igvn.zerocon(ft));
459 }
460 } else if (val->is_Phi()) {
461 val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
462 if (val == NULL) {
463 return NULL;
464 }
465 values.at_put(j, val);
466 } else if (val->Opcode() == Op_SCMemProj) {
467 assert(val->in(0)->is_LoadStore() ||
468 val->in(0)->Opcode() == Op_EncodeISOArray ||
469 val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
470 assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
471 return NULL;
472 } else if (val->is_ArrayCopy()) {
473 Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
474 if (res == NULL) {
475 return NULL;
476 }
477 values.at_put(j, res);
478 } else {
479 #ifdef ASSERT
485 }
486 }
487 // Set Phi's inputs
488 for (uint j = 1; j < length; j++) {
489 if (values.at(j) == mem) {
490 phi->init_req(j, phi);
491 } else {
492 phi->init_req(j, values.at(j));
493 }
494 }
495 return phi;
496 }
497
498 // Search the last value stored into the object's field.
499 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
500 assert(adr_t->is_known_instance_field(), "instance required");
501 int instance_id = adr_t->instance_id();
502 assert((uint)instance_id == alloc->_idx, "wrong allocation");
503
504 int alias_idx = C->get_alias_index(adr_t);
505 int offset = adr_t->flattened_offset();
506 Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
507 Node *alloc_mem = alloc->in(TypeFunc::Memory);
508 VectorSet visited;
509
510 bool done = sfpt_mem == alloc_mem;
511 Node *mem = sfpt_mem;
512 while (!done) {
513 if (visited.test_set(mem->_idx)) {
514 return NULL; // found a loop, give up
515 }
516 mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
517 if (mem == start_mem || mem == alloc_mem) {
518 done = true; // hit a sentinel, return appropriate 0 value
519 } else if (mem->is_Initialize()) {
520 mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
521 if (mem == NULL) {
522 done = true; // Something went wrong.
523 } else if (mem->is_Store()) {
524 const TypePtr* atype = mem->as_Store()->adr_type();
525 assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
526 done = true;
527 }
528 } else if (mem->is_Store()) {
529 const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
530 assert(atype != NULL, "address type must be oopptr");
531 assert(C->get_alias_index(atype) == alias_idx &&
532 atype->is_known_instance_field() && atype->flattened_offset() == offset &&
533 atype->instance_id() == instance_id, "store is correct memory slice");
534 done = true;
535 } else if (mem->is_Phi()) {
536 // try to find a phi's unique input
537 Node *unique_input = NULL;
538 Node *top = C->top();
539 for (uint i = 1; i < mem->req(); i++) {
540 Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
541 if (n == NULL || n == top || n == mem) {
542 continue;
543 } else if (unique_input == NULL) {
544 unique_input = n;
545 } else if (unique_input != n) {
546 unique_input = top;
547 break;
548 }
549 }
550 if (unique_input != NULL && unique_input != top) {
551 mem = unique_input;
552 } else {
553 done = true;
554 }
555 } else if (mem->is_ArrayCopy()) {
556 done = true;
557 } else {
558 assert(false, "unexpected node");
559 }
560 }
561 if (mem != NULL) {
562 if (mem == start_mem || mem == alloc_mem) {
563 // hit a sentinel, return appropriate 0 value
564 Node* default_value = alloc->in(AllocateNode::DefaultValue);
565 if (default_value != NULL) {
566 return default_value;
567 }
568 assert(alloc->in(AllocateNode::RawDefaultValue) == NULL, "default value may not be null");
569 return _igvn.zerocon(ft);
570 } else if (mem->is_Store()) {
571 Node* n = mem->in(MemNode::ValueIn);
572 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
573 n = bs->step_over_gc_barrier(n);
574 return n;
575 } else if (mem->is_Phi()) {
576 // attempt to produce a Phi reflecting the values on the input paths of the Phi
577 Node_Stack value_phis(8);
578 Node* phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
579 if (phi != NULL) {
580 return phi;
581 } else {
582 // Kill all new Phis
583 while(value_phis.is_nonempty()) {
584 Node* n = value_phis.node();
585 _igvn.replace_node(n, C->top());
586 value_phis.pop();
587 }
588 }
589 } else if (mem->is_ArrayCopy()) {
590 Node* ctl = mem->in(0);
591 Node* m = mem->in(TypeFunc::Memory);
592 if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
593 // pin the loads in the uncommon trap path
594 ctl = sfpt_ctl;
595 m = sfpt_mem;
596 }
597 return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
598 }
599 }
600 // Something went wrong.
601 return NULL;
602 }
603
604 // Search the last value stored into the inline type's fields.
605 Node* PhaseMacroExpand::inline_type_from_mem(Node* mem, Node* ctl, ciInlineKlass* vk, const TypeAryPtr* adr_type, int offset, AllocateNode* alloc) {
606 // Subtract the offset of the first field to account for the missing oop header
607 offset -= vk->first_field_offset();
608 // Create a new InlineTypeNode and retrieve the field values from memory
609 InlineTypeNode* vt = InlineTypeNode::make_uninitialized(_igvn, vk)->as_InlineType();
610 for (int i = 0; i < vk->nof_declared_nonstatic_fields(); ++i) {
611 ciType* field_type = vt->field_type(i);
612 int field_offset = offset + vt->field_offset(i);
613 // Each inline type field has its own memory slice
614 adr_type = adr_type->with_field_offset(field_offset);
615 Node* value = NULL;
616 if (vt->field_is_flattened(i)) {
617 value = inline_type_from_mem(mem, ctl, field_type->as_inline_klass(), adr_type, field_offset, alloc);
618 } else {
619 const Type* ft = Type::get_const_type(field_type);
620 BasicType bt = field_type->basic_type();
621 if (UseCompressedOops && !is_java_primitive(bt)) {
622 ft = ft->make_narrowoop();
623 bt = T_NARROWOOP;
624 }
625 value = value_from_mem(mem, ctl, bt, ft, adr_type, alloc);
626 if (value != NULL && ft->isa_narrowoop()) {
627 assert(UseCompressedOops, "unexpected narrow oop");
628 value = transform_later(new DecodeNNode(value, value->get_ptr_type()));
629 }
630 }
631 if (value != NULL) {
632 vt->set_field_value(i, value);
633 } else {
634 // We might have reached the TrackedInitializationLimit
635 return NULL;
636 }
637 }
638 return transform_later(vt);
639 }
640
641 // Check the possibility of scalar replacement.
642 bool PhaseMacroExpand::can_eliminate_allocation(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
643 // Scan the uses of the allocation to check for anything that would
644 // prevent us from eliminating it.
645 NOT_PRODUCT( const char* fail_eliminate = NULL; )
646 DEBUG_ONLY( Node* disq_node = NULL; )
647 bool can_eliminate = true;
648
649 Node* res = alloc->result_cast();
650 const TypeOopPtr* res_type = NULL;
651 if (res == NULL) {
652 // All users were eliminated.
653 } else if (!res->is_CheckCastPP()) {
654 NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
655 can_eliminate = false;
656 } else {
657 res_type = _igvn.type(res)->isa_oopptr();
658 if (res_type == NULL) {
659 NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
660 can_eliminate = false;
673 Node* use = res->fast_out(j);
674
675 if (use->is_AddP()) {
676 const TypePtr* addp_type = _igvn.type(use)->is_ptr();
677 int offset = addp_type->offset();
678
679 if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
680 NOT_PRODUCT(fail_eliminate = "Undefined field referrence";)
681 can_eliminate = false;
682 break;
683 }
684 for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
685 k < kmax && can_eliminate; k++) {
686 Node* n = use->fast_out(k);
687 if (!n->is_Store() && n->Opcode() != Op_CastP2X
688 SHENANDOAHGC_ONLY(&& (!UseShenandoahGC || !ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(n))) ) {
689 DEBUG_ONLY(disq_node = n;)
690 if (n->is_Load() || n->is_LoadStore()) {
691 NOT_PRODUCT(fail_eliminate = "Field load";)
692 } else {
693 NOT_PRODUCT(fail_eliminate = "Not store field reference";)
694 }
695 can_eliminate = false;
696 }
697 }
698 } else if (use->is_ArrayCopy() &&
699 (use->as_ArrayCopy()->is_clonebasic() ||
700 use->as_ArrayCopy()->is_arraycopy_validated() ||
701 use->as_ArrayCopy()->is_copyof_validated() ||
702 use->as_ArrayCopy()->is_copyofrange_validated()) &&
703 use->in(ArrayCopyNode::Dest) == res) {
704 // ok to eliminate
705 } else if (use->is_SafePoint()) {
706 SafePointNode* sfpt = use->as_SafePoint();
707 if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
708 // Object is passed as argument.
709 DEBUG_ONLY(disq_node = use;)
710 NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
711 can_eliminate = false;
712 }
713 Node* sfptMem = sfpt->memory();
714 if (sfptMem == NULL || sfptMem->is_top()) {
715 DEBUG_ONLY(disq_node = use;)
716 NOT_PRODUCT(fail_eliminate = "NULL or TOP memory";)
717 can_eliminate = false;
718 } else {
719 safepoints.append_if_missing(sfpt);
720 }
721 } else if (use->is_InlineType() && use->isa_InlineType()->get_oop() == res) {
722 // ok to eliminate
723 } else if (use->Opcode() == Op_StoreX && use->in(MemNode::Address) == res) {
724 // store to mark work
725 } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
726 if (use->is_Phi()) {
727 if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
728 NOT_PRODUCT(fail_eliminate = "Object is return value";)
729 } else {
730 NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
731 }
732 DEBUG_ONLY(disq_node = use;)
733 } else {
734 if (use->Opcode() == Op_Return) {
735 NOT_PRODUCT(fail_eliminate = "Object is return value";)
736 } else {
737 NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
738 }
739 DEBUG_ONLY(disq_node = use;)
740 }
741 can_eliminate = false;
742 } else {
743 assert(use->Opcode() == Op_CastP2X, "should be");
744 assert(!use->has_out_with(Op_OrL), "should have been removed because oop is never null");
745 }
746 }
747 }
748
749 #ifndef PRODUCT
750 if (PrintEliminateAllocations) {
751 if (can_eliminate) {
752 tty->print("Scalar ");
753 if (res == NULL)
754 alloc->dump();
755 else
756 res->dump();
757 } else if (alloc->_is_scalar_replaceable) {
758 tty->print("NotScalar (%s)", fail_eliminate);
759 if (res == NULL)
760 alloc->dump();
761 else
762 res->dump();
763 #ifdef ASSERT
764 if (disq_node != NULL) {
787 Node* res = alloc->result_cast();
788 assert(res == NULL || res->is_CheckCastPP(), "unexpected AllocateNode result");
789 const TypeOopPtr* res_type = NULL;
790 if (res != NULL) { // Could be NULL when there are no users
791 res_type = _igvn.type(res)->isa_oopptr();
792 }
793
794 if (res != NULL) {
795 klass = res_type->klass();
796 if (res_type->isa_instptr()) {
797 // find the fields of the class which will be needed for safepoint debug information
798 assert(klass->is_instance_klass(), "must be an instance klass.");
799 iklass = klass->as_instance_klass();
800 nfields = iklass->nof_nonstatic_fields();
801 } else {
802 // find the array's elements which will be needed for safepoint debug information
803 nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
804 assert(klass->is_array_klass() && nfields >= 0, "must be an array klass.");
805 elem_type = klass->as_array_klass()->element_type();
806 basic_elem_type = elem_type->basic_type();
807 if (elem_type->is_inlinetype() && !klass->is_flat_array_klass()) {
808 assert(basic_elem_type == T_INLINE_TYPE, "unexpected element basic type");
809 basic_elem_type = T_OBJECT;
810 }
811 array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
812 element_size = type2aelembytes(basic_elem_type);
813 if (klass->is_flat_array_klass()) {
814 // Flattened inline type array
815 element_size = klass->as_flat_array_klass()->element_byte_size();
816 }
817 }
818 }
819 //
820 // Process the safepoint uses
821 //
822 Unique_Node_List value_worklist;
823 while (safepoints.length() > 0) {
824 SafePointNode* sfpt = safepoints.pop();
825 Node* mem = sfpt->memory();
826 Node* ctl = sfpt->control();
827 assert(sfpt->jvms() != NULL, "missed JVMS");
828 // Fields of scalar objs are referenced only at the end
829 // of regular debuginfo at the last (youngest) JVMS.
830 // Record relative start index.
831 uint first_ind = (sfpt->req() - sfpt->jvms()->scloff());
832 SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type,
833 #ifdef ASSERT
834 alloc,
835 #endif
836 first_ind, nfields);
837 sobj->init_req(0, C->root());
838 transform_later(sobj);
839
840 // Scan object's fields adding an input to the safepoint for each field.
841 for (int j = 0; j < nfields; j++) {
842 intptr_t offset;
843 ciField* field = NULL;
844 if (iklass != NULL) {
845 field = iklass->nonstatic_field_at(j);
846 offset = field->offset();
847 elem_type = field->type();
848 basic_elem_type = field->layout_type();
849 assert(!field->is_flattened(), "flattened inline type fields should not have safepoint uses");
850 } else {
851 offset = array_base + j * (intptr_t)element_size;
852 }
853
854 const Type *field_type;
855 // The next code is taken from Parse::do_get_xxx().
856 if (is_reference_type(basic_elem_type)) {
857 if (!elem_type->is_loaded()) {
858 field_type = TypeInstPtr::BOTTOM;
859 } else if (field != NULL && field->is_static_constant()) {
860 // This can happen if the constant oop is non-perm.
861 ciObject* con = field->constant_value().as_object();
862 // Do not "join" in the previous type; it doesn't add value,
863 // and may yield a vacuous result if the field is of interface type.
864 field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
865 assert(field_type != NULL, "field singleton type must be consistent");
866 } else {
867 field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
868 }
869 if (UseCompressedOops) {
870 field_type = field_type->make_narrowoop();
871 basic_elem_type = T_NARROWOOP;
872 }
873 } else {
874 field_type = Type::get_const_basic_type(basic_elem_type);
875 }
876
877 Node* field_val = NULL;
878 const TypeOopPtr* field_addr_type = res_type->add_offset(offset)->isa_oopptr();
879 if (klass->is_flat_array_klass()) {
880 ciInlineKlass* vk = elem_type->as_inline_klass();
881 assert(vk->flatten_array(), "must be flattened");
882 field_val = inline_type_from_mem(mem, ctl, vk, field_addr_type->isa_aryptr(), 0, alloc);
883 } else {
884 field_val = value_from_mem(mem, ctl, basic_elem_type, field_type, field_addr_type, alloc);
885 }
886 if (field_val == NULL) {
887 // We weren't able to find a value for this field,
888 // give up on eliminating this allocation.
889
890 // Remove any extra entries we added to the safepoint.
891 uint last = sfpt->req() - 1;
892 for (int k = 0; k < j; k++) {
893 sfpt->del_req(last--);
894 }
895 _igvn._worklist.push(sfpt);
896 // rollback processed safepoints
897 while (safepoints_done.length() > 0) {
898 SafePointNode* sfpt_done = safepoints_done.pop();
899 // remove any extra entries we added to the safepoint
900 last = sfpt_done->req() - 1;
901 for (int k = 0; k < nfields; k++) {
902 sfpt_done->del_req(last--);
903 }
904 JVMState *jvms = sfpt_done->jvms();
905 jvms->set_endoff(sfpt_done->req());
923 if (PrintEliminateAllocations) {
924 if (field != NULL) {
925 tty->print("=== At SafePoint node %d can't find value of Field: ",
926 sfpt->_idx);
927 field->print();
928 int field_idx = C->get_alias_index(field_addr_type);
929 tty->print(" (alias_idx=%d)", field_idx);
930 } else { // Array's element
931 tty->print("=== At SafePoint node %d can't find value of array element [%d]",
932 sfpt->_idx, j);
933 }
934 tty->print(", which prevents elimination of: ");
935 if (res == NULL)
936 alloc->dump();
937 else
938 res->dump();
939 }
940 #endif
941 return false;
942 }
943 if (field_val->is_InlineType()) {
944 // Keep track of inline types to scalarize them later
945 value_worklist.push(field_val);
946 } else if (UseCompressedOops && field_type->isa_narrowoop()) {
947 // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
948 // to be able scalar replace the allocation.
949 if (field_val->is_EncodeP()) {
950 field_val = field_val->in(1);
951 } else {
952 field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
953 }
954 }
955 sfpt->add_req(field_val);
956 }
957 JVMState *jvms = sfpt->jvms();
958 jvms->set_endoff(sfpt->req());
959 // Now make a pass over the debug information replacing any references
960 // to the allocated object with "sobj"
961 int start = jvms->debug_start();
962 int end = jvms->debug_end();
963 sfpt->replace_edges_in_range(res, sobj, start, end);
964 _igvn._worklist.push(sfpt);
965 safepoints_done.append_if_missing(sfpt); // keep it for rollback
966 }
967 // Scalarize inline types that were added to the safepoint
968 for (uint i = 0; i < value_worklist.size(); ++i) {
969 Node* vt = value_worklist.at(i);
970 vt->as_InlineType()->make_scalar_in_safepoints(&_igvn);
971 }
972 return true;
973 }
974
975 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
976 Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
977 Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
978 if (ctl_proj != NULL) {
979 igvn.replace_node(ctl_proj, n->in(0));
980 }
981 if (mem_proj != NULL) {
982 igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
983 }
984 }
985
986 // Process users of eliminated allocation.
987 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc, bool inline_alloc) {
988 Node* res = alloc->result_cast();
989 if (res != NULL) {
990 for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
991 Node *use = res->last_out(j);
992 uint oc1 = res->outcnt();
993
994 if (use->is_AddP()) {
995 for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
996 Node *n = use->last_out(k);
997 uint oc2 = use->outcnt();
998 if (n->is_Store()) {
999 for (DUIterator_Fast pmax, p = n->fast_outs(pmax); p < pmax; p++) {
1000 MemBarNode* mb = n->fast_out(p)->isa_MemBar();
1001 if (mb != NULL && mb->req() <= MemBarNode::Precedent && mb->in(MemBarNode::Precedent) == n) {
1002 // MemBarVolatiles should have been removed by MemBarNode::Ideal() for non-inline allocations
1003 assert(inline_alloc, "MemBarVolatile should be eliminated for non-escaping object");
1004 mb->remove(&_igvn);
1005 }
1006 }
1007 _igvn.replace_node(n, n->in(MemNode::Memory));
1008 } else {
1009 eliminate_gc_barrier(n);
1010 }
1011 k -= (oc2 - use->outcnt());
1012 }
1013 _igvn.remove_dead_node(use);
1014 } else if (use->is_ArrayCopy()) {
1015 // Disconnect ArrayCopy node
1016 ArrayCopyNode* ac = use->as_ArrayCopy();
1017 if (ac->is_clonebasic()) {
1018 Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
1019 disconnect_projections(ac, _igvn);
1020 assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
1021 Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
1022 disconnect_projections(membar_before->as_MemBar(), _igvn);
1023 if (membar_after->is_MemBar()) {
1024 disconnect_projections(membar_after->as_MemBar(), _igvn);
1025 }
1026 } else {
1027 assert(ac->is_arraycopy_validated() ||
1028 ac->is_copyof_validated() ||
1029 ac->is_copyofrange_validated(), "unsupported");
1030 CallProjections* callprojs = ac->extract_projections(true);
1031
1032 _igvn.replace_node(callprojs->fallthrough_ioproj, ac->in(TypeFunc::I_O));
1033 _igvn.replace_node(callprojs->fallthrough_memproj, ac->in(TypeFunc::Memory));
1034 _igvn.replace_node(callprojs->fallthrough_catchproj, ac->in(TypeFunc::Control));
1035
1036 // Set control to top. IGVN will remove the remaining projections
1037 ac->set_req(0, top());
1038 ac->replace_edge(res, top());
1039
1040 // Disconnect src right away: it can help find new
1041 // opportunities for allocation elimination
1042 Node* src = ac->in(ArrayCopyNode::Src);
1043 ac->replace_edge(src, top());
1044 // src can be top at this point if src and dest of the
1045 // arraycopy were the same
1046 if (src->outcnt() == 0 && !src->is_top()) {
1047 _igvn.remove_dead_node(src);
1048 }
1049 }
1050 _igvn._worklist.push(ac);
1051 } else if (use->is_InlineType()) {
1052 assert(use->isa_InlineType()->get_oop() == res, "unexpected inline type use");
1053 _igvn.rehash_node_delayed(use);
1054 use->isa_InlineType()->set_oop(_igvn.zerocon(T_INLINE_TYPE));
1055 } else if (use->is_Store()) {
1056 _igvn.replace_node(use, use->in(MemNode::Memory));
1057 } else {
1058 eliminate_gc_barrier(use);
1059 }
1060 j -= (oc1 - res->outcnt());
1061 }
1062 assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1063 _igvn.remove_dead_node(res);
1064 }
1065
1066 //
1067 // Process other users of allocation's projections
1068 //
1069 if (_resproj != NULL && _resproj->outcnt() != 0) {
1070 // First disconnect stores captured by Initialize node.
1071 // If Initialize node is eliminated first in the following code,
1072 // it will kill such stores and DUIterator_Last will assert.
1073 for (DUIterator_Fast jmax, j = _resproj->fast_outs(jmax); j < jmax; j++) {
1074 Node *use = _resproj->fast_out(j);
1075 if (use->is_AddP()) {
1076 // raw memory addresses used only by the initialization
1077 _igvn.replace_node(use, C->top());
1078 --j; --jmax;
1079 }
1080 }
1081 for (DUIterator_Last jmin, j = _resproj->last_outs(jmin); j >= jmin; ) {
1082 Node *use = _resproj->last_out(j);
1083 uint oc1 = _resproj->outcnt();
1084 if (use->is_Initialize()) {
1085 // Eliminate Initialize node.
1086 InitializeNode *init = use->as_Initialize();
1087 assert(init->outcnt() <= 2, "only a control and memory projection expected");
1088 Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1089 if (ctrl_proj != NULL) {
1090 // Inline type buffer allocations are followed by a membar
1091 Node* membar_after = ctrl_proj->unique_ctrl_out();
1092 if (inline_alloc && membar_after->Opcode() == Op_MemBarCPUOrder) {
1093 membar_after->as_MemBar()->remove(&_igvn);
1094 }
1095 _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1096 #ifdef ASSERT
1097 Node* tmp = init->in(TypeFunc::Control);
1098 assert(tmp == _fallthroughcatchproj, "allocation control projection");
1099 #endif
1100 }
1101 Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
1102 if (mem_proj != NULL) {
1103 Node *mem = init->in(TypeFunc::Memory);
1104 #ifdef ASSERT
1105 if (mem->is_MergeMem()) {
1106 assert(mem->in(TypeFunc::Memory) == _memproj_fallthrough, "allocation memory projection");
1107 } else {
1108 assert(mem == _memproj_fallthrough, "allocation memory projection");
1109 }
1110 #endif
1111 _igvn.replace_node(mem_proj, mem);
1112 }
1113 } else if (use->Opcode() == Op_MemBarStoreStore) {
1114 // Inline type buffer allocations are followed by a membar
1115 assert(inline_alloc, "Unexpected MemBarStoreStore");
1116 use->as_MemBar()->remove(&_igvn);
1117 } else {
1118 assert(false, "only Initialize or AddP expected");
1119 }
1120 j -= (oc1 - _resproj->outcnt());
1121 }
1122 }
1123 if (_fallthroughcatchproj != NULL) {
1124 _igvn.replace_node(_fallthroughcatchproj, alloc->in(TypeFunc::Control));
1125 }
1126 if (_memproj_fallthrough != NULL) {
1127 _igvn.replace_node(_memproj_fallthrough, alloc->in(TypeFunc::Memory));
1128 }
1129 if (_memproj_catchall != NULL) {
1130 _igvn.replace_node(_memproj_catchall, C->top());
1131 }
1132 if (_ioproj_fallthrough != NULL) {
1133 _igvn.replace_node(_ioproj_fallthrough, alloc->in(TypeFunc::I_O));
1134 }
1135 if (_ioproj_catchall != NULL) {
1136 _igvn.replace_node(_ioproj_catchall, C->top());
1137 }
1138 if (_catchallcatchproj != NULL) {
1139 _igvn.replace_node(_catchallcatchproj, C->top());
1140 }
1141 }
1142
1143 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1144 // Don't do scalar replacement if the frame can be popped by JVMTI:
1145 // if reallocation fails during deoptimization we'll pop all
1146 // interpreter frames for this compiled frame and that won't play
1147 // nice with JVMTI popframe.
1148 if (!EliminateAllocations || JvmtiExport::can_pop_frame()) {
1149 return false;
1150 }
1151 Node* klass = alloc->in(AllocateNode::KlassNode);
1152 const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1153
1154 // Attempt to eliminate inline type buffer allocations
1155 // regardless of usage and escape/replaceable status.
1156 bool inline_alloc = tklass->klass()->is_inlinetype();
1157 if (!alloc->_is_non_escaping && !inline_alloc) {
1158 return false;
1159 }
1160 // Eliminate boxing allocations which are not used
1161 // regardless of scalar replaceable status.
1162 Node* res = alloc->result_cast();
1163 bool boxing_alloc = (res == NULL) && C->eliminate_boxing() &&
1164 tklass->klass()->is_instance_klass() &&
1165 tklass->klass()->as_instance_klass()->is_box_klass();
1166 if (!alloc->_is_scalar_replaceable && !boxing_alloc && !inline_alloc) {
1167 return false;
1168 }
1169
1170 extract_call_projections(alloc);
1171
1172 GrowableArray <SafePointNode *> safepoints;
1173 if (!can_eliminate_allocation(alloc, safepoints)) {
1174 return false;
1175 }
1176
1177 if (!alloc->_is_scalar_replaceable) {
1178 assert(res == NULL || inline_alloc, "sanity");
1179 // We can only eliminate allocation if all debug info references
1180 // are already replaced with SafePointScalarObject because
1181 // we can't search for a fields value without instance_id.
1182 if (safepoints.length() > 0) {
1183 assert(!inline_alloc, "Inline type allocations should not have safepoint uses");
1184 return false;
1185 }
1186 }
1187
1188 if (!scalar_replacement(alloc, safepoints)) {
1189 return false;
1190 }
1191
1192 CompileLog* log = C->log();
1193 if (log != NULL) {
1194 log->head("eliminate_allocation type='%d'",
1195 log->identify(tklass->klass()));
1196 JVMState* p = alloc->jvms();
1197 while (p != NULL) {
1198 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1199 p = p->caller();
1200 }
1201 log->tail("eliminate_allocation");
1202 }
1203
1204 process_users_of_allocation(alloc, inline_alloc);
1205
1206 #ifndef PRODUCT
1207 if (PrintEliminateAllocations) {
1208 if (alloc->is_AllocateArray())
1209 tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1210 else
1211 tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1212 }
1213 #endif
1214
1215 return true;
1216 }
1217
1218 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1219 // EA should remove all uses of non-escaping boxing node.
1220 if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != NULL) {
1221 return false;
1222 }
1223
1224 assert(boxing->result_cast() == NULL, "unexpected boxing node result");
1225
1226 extract_call_projections(boxing);
1227
1228 const TypeTuple* r = boxing->tf()->range_sig();
1229 assert(r->cnt() > TypeFunc::Parms, "sanity");
1230 const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1231 assert(t != NULL, "sanity");
1232
1233 CompileLog* log = C->log();
1234 if (log != NULL) {
1235 log->head("eliminate_boxing type='%d'",
1236 log->identify(t->klass()));
1237 JVMState* p = boxing->jvms();
1238 while (p != NULL) {
1239 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1240 p = p->caller();
1241 }
1242 log->tail("eliminate_boxing");
1243 }
1244
1245 process_users_of_allocation(boxing);
1246
1247 #ifndef PRODUCT
1248 if (PrintEliminateAllocations) {
1409 }
1410 }
1411 #endif
1412 yank_alloc_node(alloc);
1413 return;
1414 }
1415 }
1416
1417 enum { too_big_or_final_path = 1, need_gc_path = 2 };
1418 Node *slow_region = NULL;
1419 Node *toobig_false = ctrl;
1420
1421 // generate the initial test if necessary
1422 if (initial_slow_test != NULL ) {
1423 assert (expand_fast_path, "Only need test if there is a fast path");
1424 slow_region = new RegionNode(3);
1425
1426 // Now make the initial failure test. Usually a too-big test but
1427 // might be a TRUE for finalizers or a fancy class check for
1428 // newInstance0.
1429 IfNode* toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1430 transform_later(toobig_iff);
1431 // Plug the failing-too-big test into the slow-path region
1432 Node* toobig_true = new IfTrueNode(toobig_iff);
1433 transform_later(toobig_true);
1434 slow_region ->init_req( too_big_or_final_path, toobig_true );
1435 toobig_false = new IfFalseNode(toobig_iff);
1436 transform_later(toobig_false);
1437 } else {
1438 // No initial test, just fall into next case
1439 assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1440 toobig_false = ctrl;
1441 debug_only(slow_region = NodeSentinel);
1442 }
1443
1444 // If we are here there are several possibilities
1445 // - expand_fast_path is false - then only a slow path is expanded. That's it.
1446 // no_initial_check means a constant allocation.
1447 // - If check always evaluates to false -> expand_fast_path is false (see above)
1448 // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1449 // if !allocation_has_use the fast path is empty
1450 // if !allocation_has_use && no_initial_check
1451 // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1452 // removed by yank_alloc_node above.
1453
1454 Node *slow_mem = mem; // save the current memory state for slow path
1455 // generate the fast allocation code unless we know that the initial test will always go slow
1456 if (expand_fast_path) {
1457 // Fast path modifies only raw memory.
1458 if (mem->is_MergeMem()) {
1459 mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1460 }
1461
1462 // allocate the Region and Phi nodes for the result
1463 result_region = new RegionNode(3);
1464 result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1465 result_phi_i_o = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1466
1467 // Grab regular I/O before optional prefetch may change it.
1468 // Slow-path does no I/O so just set it to the original I/O.
1469 result_phi_i_o->init_req(slow_result_path, i_o);
1470
1471 // Name successful fast-path variables
1472 Node* fast_oop_ctrl;
1473 Node* fast_oop_rawmem;
1474
1475 if (allocation_has_use) {
1476 Node* needgc_ctrl = NULL;
1477 result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1478
1479 intx prefetch_lines = length != NULL ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1480 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1481 Node* fast_oop = bs->obj_allocate(this, ctrl, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1482 fast_oop_ctrl, fast_oop_rawmem,
1483 prefetch_lines);
1484
1485 if (initial_slow_test != NULL) {
1486 // This completes all paths into the slow merge point
1487 slow_region->init_req(need_gc_path, needgc_ctrl);
1488 transform_later(slow_region);
1489 } else {
1490 // No initial slow path needed!
1491 // Just fall from the need-GC path straight into the VM call.
1492 slow_region = needgc_ctrl;
1493 }
1494
1513 result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1514 } else {
1515 slow_region = ctrl;
1516 result_phi_i_o = i_o; // Rename it to use in the following code.
1517 }
1518
1519 // Generate slow-path call
1520 CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1521 OptoRuntime::stub_name(slow_call_address),
1522 alloc->jvms()->bci(),
1523 TypePtr::BOTTOM);
1524 call->init_req(TypeFunc::Control, slow_region);
1525 call->init_req(TypeFunc::I_O, top()); // does no i/o
1526 call->init_req(TypeFunc::Memory, slow_mem); // may gc ptrs
1527 call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1528 call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1529
1530 call->init_req(TypeFunc::Parms+0, klass_node);
1531 if (length != NULL) {
1532 call->init_req(TypeFunc::Parms+1, length);
1533 } else {
1534 // Let the runtime know if this is a larval allocation
1535 call->init_req(TypeFunc::Parms+1, _igvn.intcon(alloc->_larval));
1536 }
1537
1538 // Copy debug information and adjust JVMState information, then replace
1539 // allocate node with the call
1540 call->copy_call_debug_info(&_igvn, alloc);
1541 if (expand_fast_path) {
1542 call->set_cnt(PROB_UNLIKELY_MAG(4)); // Same effect as RC_UNCOMMON.
1543 } else {
1544 // Hook i_o projection to avoid its elimination during allocation
1545 // replacement (when only a slow call is generated).
1546 call->set_req(TypeFunc::I_O, result_phi_i_o);
1547 }
1548 _igvn.replace_node(alloc, call);
1549 transform_later(call);
1550
1551 // Identify the output projections from the allocate node and
1552 // adjust any references to them.
1553 // The control and io projections look like:
1554 //
1555 // v---Proj(ctrl) <-----+ v---CatchProj(ctrl)
1556 // Allocate Catch
1557 // ^---Proj(io) <-------+ ^---CatchProj(io)
1558 //
1559 // We are interested in the CatchProj nodes.
1560 //
1561 extract_call_projections(call);
1562
1563 // An allocate node has separate memory projections for the uses on
1564 // the control and i_o paths. Replace the control memory projection with
1565 // result_phi_rawmem (unless we are only generating a slow call when
1566 // both memory projections are combined)
1567 if (expand_fast_path && _memproj_fallthrough != NULL) {
1568 _igvn.replace_in_uses(_memproj_fallthrough, result_phi_rawmem);
1569 }
1570 // Now change uses of _memproj_catchall to use _memproj_fallthrough and delete
1571 // _memproj_catchall so we end up with a call that has only 1 memory projection.
1572 if (_memproj_catchall != NULL) {
1573 if (_memproj_fallthrough == NULL) {
1574 _memproj_fallthrough = new ProjNode(call, TypeFunc::Memory);
1575 transform_later(_memproj_fallthrough);
1576 }
1577 _igvn.replace_in_uses(_memproj_catchall, _memproj_fallthrough);
1578 _igvn.remove_dead_node(_memproj_catchall);
1579 }
1580
1581 // An allocate node has separate i_o projections for the uses on the control
1582 // and i_o paths. Always replace the control i_o projection with result i_o
1583 // otherwise incoming i_o become dead when only a slow call is generated
1584 // (it is different from memory projections where both projections are
1585 // combined in such case).
1586 if (_ioproj_fallthrough != NULL) {
1587 _igvn.replace_in_uses(_ioproj_fallthrough, result_phi_i_o);
1588 }
1589 // Now change uses of _ioproj_catchall to use _ioproj_fallthrough and delete
1590 // _ioproj_catchall so we end up with a call that has only 1 i_o projection.
1591 if (_ioproj_catchall != NULL) {
1592 if (_ioproj_fallthrough == NULL) {
1593 _ioproj_fallthrough = new ProjNode(call, TypeFunc::I_O);
1594 transform_later(_ioproj_fallthrough);
1595 }
1596 _igvn.replace_in_uses(_ioproj_catchall, _ioproj_fallthrough);
1597 _igvn.remove_dead_node(_ioproj_catchall);
1598 }
1599
1600 // if we generated only a slow call, we are done
1601 if (!expand_fast_path) {
1602 // Now we can unhook i_o.
1603 if (result_phi_i_o->outcnt() > 1) {
1604 call->set_req(TypeFunc::I_O, top());
1605 } else {
1606 assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1607 // Case of new array with negative size known during compilation.
1608 // AllocateArrayNode::Ideal() optimization disconnect unreachable
1609 // following code since call to runtime will throw exception.
1610 // As result there will be no users of i_o after the call.
1611 // Leave i_o attached to this call to avoid problems in preceding graph.
1612 }
1613 return;
1614 }
1615
1616 if (_fallthroughcatchproj != NULL) {
1644 }
1645
1646 // Remove alloc node that has no uses.
1647 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1648 Node* ctrl = alloc->in(TypeFunc::Control);
1649 Node* mem = alloc->in(TypeFunc::Memory);
1650 Node* i_o = alloc->in(TypeFunc::I_O);
1651
1652 extract_call_projections(alloc);
1653 if (_resproj != NULL) {
1654 for (DUIterator_Fast imax, i = _resproj->fast_outs(imax); i < imax; i++) {
1655 Node* use = _resproj->fast_out(i);
1656 use->isa_MemBar()->remove(&_igvn);
1657 --imax;
1658 --i; // back up iterator
1659 }
1660 assert(_resproj->outcnt() == 0, "all uses must be deleted");
1661 _igvn.remove_dead_node(_resproj);
1662 }
1663 if (_fallthroughcatchproj != NULL) {
1664 _igvn.replace_in_uses(_fallthroughcatchproj, ctrl);
1665 _igvn.remove_dead_node(_fallthroughcatchproj);
1666 }
1667 if (_catchallcatchproj != NULL) {
1668 _igvn.rehash_node_delayed(_catchallcatchproj);
1669 _catchallcatchproj->set_req(0, top());
1670 }
1671 if (_fallthroughproj != NULL) {
1672 Node* catchnode = _fallthroughproj->unique_ctrl_out();
1673 _igvn.remove_dead_node(catchnode);
1674 _igvn.remove_dead_node(_fallthroughproj);
1675 }
1676 if (_memproj_fallthrough != NULL) {
1677 _igvn.replace_in_uses(_memproj_fallthrough, mem);
1678 _igvn.remove_dead_node(_memproj_fallthrough);
1679 }
1680 if (_ioproj_fallthrough != NULL) {
1681 _igvn.replace_in_uses(_ioproj_fallthrough, i_o);
1682 _igvn.remove_dead_node(_ioproj_fallthrough);
1683 }
1684 if (_memproj_catchall != NULL) {
1685 _igvn.rehash_node_delayed(_memproj_catchall);
1686 _memproj_catchall->set_req(0, top());
1687 }
1688 if (_ioproj_catchall != NULL) {
1689 _igvn.rehash_node_delayed(_ioproj_catchall);
1690 _ioproj_catchall->set_req(0, top());
1691 }
1692 #ifndef PRODUCT
1693 if (PrintEliminateAllocations) {
1694 if (alloc->is_AllocateArray()) {
1695 tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1696 } else {
1697 tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1698 }
1699 }
1700 #endif
1701 _igvn.remove_dead_node(alloc);
1787 Node* thread = new ThreadLocalNode();
1788 transform_later(thread);
1789
1790 call->init_req(TypeFunc::Parms + 0, thread);
1791 call->init_req(TypeFunc::Parms + 1, oop);
1792 call->init_req(TypeFunc::Control, ctrl);
1793 call->init_req(TypeFunc::I_O , top()); // does no i/o
1794 call->init_req(TypeFunc::Memory , ctrl);
1795 call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1796 call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1797 transform_later(call);
1798 ctrl = new ProjNode(call, TypeFunc::Control);
1799 transform_later(ctrl);
1800 rawmem = new ProjNode(call, TypeFunc::Memory);
1801 transform_later(rawmem);
1802 }
1803 }
1804
1805 // Helper for PhaseMacroExpand::expand_allocate_common.
1806 // Initializes the newly-allocated storage.
1807 Node* PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1808 Node* control, Node* rawmem, Node* object,
1809 Node* klass_node, Node* length,
1810 Node* size_in_bytes) {
1811 InitializeNode* init = alloc->initialization();
1812 // Store the klass & mark bits
1813 Node* mark_node = alloc->make_ideal_mark(&_igvn, control, rawmem);
1814 if (!mark_node->is_Con()) {
1815 transform_later(mark_node);
1816 }
1817 rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1818
1819 rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1820 int header_size = alloc->minimum_header_size(); // conservatively small
1821
1822 // Array length
1823 if (length != NULL) { // Arrays need length field
1824 rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1825 // conservatively small header size:
1826 header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1827 ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1828 if (k->is_array_klass()) // we know the exact header size in most cases:
1829 header_size = Klass::layout_helper_header_size(k->layout_helper());
1830 }
1831
1832 // Clear the object body, if necessary.
1833 if (init == NULL) {
1834 // The init has somehow disappeared; be cautious and clear everything.
1835 //
1836 // This can happen if a node is allocated but an uncommon trap occurs
1837 // immediately. In this case, the Initialize gets associated with the
1838 // trap, and may be placed in a different (outer) loop, if the Allocate
1839 // is in a loop. If (this is rare) the inner loop gets unrolled, then
1840 // there can be two Allocates to one Initialize. The answer in all these
1841 // edge cases is safety first. It is always safe to clear immediately
1842 // within an Allocate, and then (maybe or maybe not) clear some more later.
1843 if (!(UseTLAB && ZeroTLAB)) {
1844 rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1845 alloc->in(AllocateNode::DefaultValue),
1846 alloc->in(AllocateNode::RawDefaultValue),
1847 header_size, size_in_bytes,
1848 &_igvn);
1849 }
1850 } else {
1851 if (!init->is_complete()) {
1852 // Try to win by zeroing only what the init does not store.
1853 // We can also try to do some peephole optimizations,
1854 // such as combining some adjacent subword stores.
1855 rawmem = init->complete_stores(control, rawmem, object,
1856 header_size, size_in_bytes, &_igvn);
1857 }
1858 // We have no more use for this link, since the AllocateNode goes away:
1859 init->set_req(InitializeNode::RawAddress, top());
1860 // (If we keep the link, it just confuses the register allocator,
1861 // who thinks he sees a real use of the address by the membar.)
1862 }
1863
1864 return rawmem;
1865 }
1866
2207 // Replace old box node with new eliminated box for all users
2208 // of the same object and mark related locks as eliminated.
2209 mark_eliminated_box(box, obj);
2210 }
2211 }
2212 }
2213 }
2214
2215 // we have determined that this lock/unlock can be eliminated, we simply
2216 // eliminate the node without expanding it.
2217 //
2218 // Note: The membar's associated with the lock/unlock are currently not
2219 // eliminated. This should be investigated as a future enhancement.
2220 //
2221 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2222
2223 if (!alock->is_eliminated()) {
2224 return false;
2225 }
2226 #ifdef ASSERT
2227 const Type* obj_type = _igvn.type(alock->obj_node());
2228 assert(!obj_type->isa_inlinetype() && !obj_type->is_inlinetypeptr(), "Eliminating lock on inline type");
2229 if (!alock->is_coarsened()) {
2230 // Check that new "eliminated" BoxLock node is created.
2231 BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2232 assert(oldbox->is_eliminated(), "should be done already");
2233 }
2234 #endif
2235
2236 alock->log_lock_optimization(C, "eliminate_lock");
2237
2238 #ifndef PRODUCT
2239 if (PrintEliminateLocks) {
2240 if (alock->is_Lock()) {
2241 tty->print_cr("++++ Eliminated: %d Lock", alock->_idx);
2242 } else {
2243 tty->print_cr("++++ Eliminated: %d Unlock", alock->_idx);
2244 }
2245 }
2246 #endif
2247
2248 Node* mem = alock->in(TypeFunc::Memory);
2490 // region->in(2) is set to fast path - the object is locked to the current thread.
2491
2492 slow_path->init_req(2, ctrl); // Capture slow-control
2493 slow_mem->init_req(2, fast_lock_mem_phi);
2494
2495 transform_later(slow_path);
2496 transform_later(slow_mem);
2497 // Reset lock's memory edge.
2498 lock->set_req(TypeFunc::Memory, slow_mem);
2499
2500 } else {
2501 region = new RegionNode(3);
2502 // create a Phi for the memory state
2503 mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2504
2505 // Optimize test; set region slot 2
2506 slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2507 mem_phi->init_req(2, mem);
2508 }
2509
2510 const TypeOopPtr* objptr = _igvn.type(obj)->make_oopptr();
2511 if (objptr->can_be_inline_type()) {
2512 // Deoptimize and re-execute if a value
2513 assert(EnableValhalla, "should only be used if inline types are enabled");
2514 Node* mark = make_load(slow_path, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2515 Node* value_mask = _igvn.MakeConX(markWord::always_locked_pattern);
2516 Node* is_value = _igvn.transform(new AndXNode(mark, value_mask));
2517 Node* cmp = _igvn.transform(new CmpXNode(is_value, value_mask));
2518 Node* bol = _igvn.transform(new BoolNode(cmp, BoolTest::eq));
2519 Node* unc_ctrl = generate_slow_guard(&slow_path, bol, NULL);
2520
2521 int trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_class_check, Deoptimization::Action_none);
2522 address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
2523 const TypePtr* no_memory_effects = NULL;
2524 JVMState* jvms = lock->jvms();
2525 CallNode* unc = new CallStaticJavaNode(OptoRuntime::uncommon_trap_Type(), call_addr, "uncommon_trap",
2526 jvms->bci(), no_memory_effects);
2527
2528 unc->init_req(TypeFunc::Control, unc_ctrl);
2529 unc->init_req(TypeFunc::I_O, lock->i_o());
2530 unc->init_req(TypeFunc::Memory, mem); // may gc ptrs
2531 unc->init_req(TypeFunc::FramePtr, lock->in(TypeFunc::FramePtr));
2532 unc->init_req(TypeFunc::ReturnAdr, lock->in(TypeFunc::ReturnAdr));
2533 unc->init_req(TypeFunc::Parms+0, _igvn.intcon(trap_request));
2534 unc->set_cnt(PROB_UNLIKELY_MAG(4));
2535 unc->copy_call_debug_info(&_igvn, lock);
2536
2537 assert(unc->peek_monitor_box() == box, "wrong monitor");
2538 assert(unc->peek_monitor_obj() == obj, "wrong monitor");
2539
2540 // pop monitor and push obj back on stack: we trap before the monitorenter
2541 unc->pop_monitor();
2542 unc->grow_stack(unc->jvms(), 1);
2543 unc->set_stack(unc->jvms(), unc->jvms()->stk_size()-1, obj);
2544
2545 _igvn.register_new_node_with_optimizer(unc);
2546
2547 Node* ctrl = _igvn.transform(new ProjNode(unc, TypeFunc::Control));
2548 Node* halt = _igvn.transform(new HaltNode(ctrl, lock->in(TypeFunc::FramePtr), "monitor enter on value-type"));
2549 C->root()->add_req(halt);
2550 }
2551
2552 // Make slow path call
2553 CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2554 OptoRuntime::complete_monitor_locking_Java(), NULL, slow_path,
2555 obj, box, NULL);
2556
2557 extract_call_projections(call);
2558
2559 // Slow path can only throw asynchronous exceptions, which are always
2560 // de-opted. So the compiler thinks the slow-call can never throw an
2561 // exception. If it DOES throw an exception we would need the debug
2562 // info removed first (since if it throws there is no monitor).
2563 assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
2564 _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
2565
2566 // Capture slow path
2567 // disconnect fall-through projection from call and create a new one
2568 // hook up users of fall-through projection to region
2569 Node *slow_ctrl = _fallthroughproj->clone();
2570 transform_later(slow_ctrl);
2571 _igvn.hash_delete(_fallthroughproj);
2633 // No exceptions for unlocking
2634 // Capture slow path
2635 // disconnect fall-through projection from call and create a new one
2636 // hook up users of fall-through projection to region
2637 Node *slow_ctrl = _fallthroughproj->clone();
2638 transform_later(slow_ctrl);
2639 _igvn.hash_delete(_fallthroughproj);
2640 _fallthroughproj->disconnect_inputs(NULL, C);
2641 region->init_req(1, slow_ctrl);
2642 // region inputs are now complete
2643 transform_later(region);
2644 _igvn.replace_node(_fallthroughproj, region);
2645
2646 Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2647 mem_phi->init_req(1, memproj );
2648 mem_phi->init_req(2, mem);
2649 transform_later(mem_phi);
2650 _igvn.replace_node(_memproj_fallthrough, mem_phi);
2651 }
2652
2653 // An inline type might be returned from the call but we don't know its
2654 // type. Either we get a buffered inline type (and nothing needs to be done)
2655 // or one of the inlines being returned is the klass of the inline type
2656 // and we need to allocate an inline type instance of that type and
2657 // initialize it with other values being returned. In that case, we
2658 // first try a fast path allocation and initialize the value with the
2659 // inline klass's pack handler or we fall back to a runtime call.
2660 void PhaseMacroExpand::expand_mh_intrinsic_return(CallStaticJavaNode* call) {
2661 assert(call->method()->is_method_handle_intrinsic(), "must be a method handle intrinsic call");
2662 Node* ret = call->proj_out_or_null(TypeFunc::Parms);
2663 if (ret == NULL) {
2664 return;
2665 }
2666 const TypeFunc* tf = call->_tf;
2667 const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc();
2668 const TypeFunc* new_tf = TypeFunc::make(tf->domain_sig(), tf->domain_cc(), tf->range_sig(), domain);
2669 call->_tf = new_tf;
2670 // Make sure the change of type is applied before projections are processed by igvn
2671 _igvn.set_type(call, call->Value(&_igvn));
2672 _igvn.set_type(ret, ret->Value(&_igvn));
2673
2674 // Before any new projection is added:
2675 CallProjections* projs = call->extract_projections(true, true);
2676
2677 Node* ctl = new Node(1);
2678 Node* mem = new Node(1);
2679 Node* io = new Node(1);
2680 Node* ex_ctl = new Node(1);
2681 Node* ex_mem = new Node(1);
2682 Node* ex_io = new Node(1);
2683 Node* res = new Node(1);
2684
2685 Node* cast = transform_later(new CastP2XNode(ctl, res));
2686 Node* mask = MakeConX(0x1);
2687 Node* masked = transform_later(new AndXNode(cast, mask));
2688 Node* cmp = transform_later(new CmpXNode(masked, mask));
2689 Node* bol = transform_later(new BoolNode(cmp, BoolTest::eq));
2690 IfNode* allocation_iff = new IfNode(ctl, bol, PROB_MAX, COUNT_UNKNOWN);
2691 transform_later(allocation_iff);
2692 Node* allocation_ctl = transform_later(new IfTrueNode(allocation_iff));
2693 Node* no_allocation_ctl = transform_later(new IfFalseNode(allocation_iff));
2694
2695 Node* no_allocation_res = transform_later(new CheckCastPPNode(no_allocation_ctl, res, TypeInstPtr::BOTTOM));
2696
2697 Node* mask2 = MakeConX(-2);
2698 Node* masked2 = transform_later(new AndXNode(cast, mask2));
2699 Node* rawklassptr = transform_later(new CastX2PNode(masked2));
2700 Node* klass_node = transform_later(new CheckCastPPNode(allocation_ctl, rawklassptr, TypeKlassPtr::OBJECT_OR_NULL));
2701
2702 Node* slowpath_bol = NULL;
2703 Node* top_adr = NULL;
2704 Node* old_top = NULL;
2705 Node* new_top = NULL;
2706 if (UseTLAB) {
2707 Node* end_adr = NULL;
2708 set_eden_pointers(top_adr, end_adr);
2709 Node* end = make_load(ctl, mem, end_adr, 0, TypeRawPtr::BOTTOM, T_ADDRESS);
2710 old_top = new LoadPNode(ctl, mem, top_adr, TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM, MemNode::unordered);
2711 transform_later(old_top);
2712 Node* layout_val = make_load(NULL, mem, klass_node, in_bytes(Klass::layout_helper_offset()), TypeInt::INT, T_INT);
2713 Node* size_in_bytes = ConvI2X(layout_val);
2714 new_top = new AddPNode(top(), old_top, size_in_bytes);
2715 transform_later(new_top);
2716 Node* slowpath_cmp = new CmpPNode(new_top, end);
2717 transform_later(slowpath_cmp);
2718 slowpath_bol = new BoolNode(slowpath_cmp, BoolTest::ge);
2719 transform_later(slowpath_bol);
2720 } else {
2721 slowpath_bol = intcon(1);
2722 top_adr = top();
2723 old_top = top();
2724 new_top = top();
2725 }
2726 IfNode* slowpath_iff = new IfNode(allocation_ctl, slowpath_bol, PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN);
2727 transform_later(slowpath_iff);
2728
2729 Node* slowpath_true = new IfTrueNode(slowpath_iff);
2730 transform_later(slowpath_true);
2731
2732 CallStaticJavaNode* slow_call = new CallStaticJavaNode(OptoRuntime::store_inline_type_fields_Type(),
2733 StubRoutines::store_inline_type_fields_to_buf(),
2734 "store_inline_type_fields",
2735 call->jvms()->bci(),
2736 TypePtr::BOTTOM);
2737 slow_call->init_req(TypeFunc::Control, slowpath_true);
2738 slow_call->init_req(TypeFunc::Memory, mem);
2739 slow_call->init_req(TypeFunc::I_O, io);
2740 slow_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2741 slow_call->init_req(TypeFunc::ReturnAdr, call->in(TypeFunc::ReturnAdr));
2742 slow_call->init_req(TypeFunc::Parms, res);
2743
2744 Node* slow_ctl = transform_later(new ProjNode(slow_call, TypeFunc::Control));
2745 Node* slow_mem = transform_later(new ProjNode(slow_call, TypeFunc::Memory));
2746 Node* slow_io = transform_later(new ProjNode(slow_call, TypeFunc::I_O));
2747 Node* slow_res = transform_later(new ProjNode(slow_call, TypeFunc::Parms));
2748 Node* slow_catc = transform_later(new CatchNode(slow_ctl, slow_io, 2));
2749 Node* slow_norm = transform_later(new CatchProjNode(slow_catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci));
2750 Node* slow_excp = transform_later(new CatchProjNode(slow_catc, CatchProjNode::catch_all_index, CatchProjNode::no_handler_bci));
2751
2752 Node* ex_r = new RegionNode(3);
2753 Node* ex_mem_phi = new PhiNode(ex_r, Type::MEMORY, TypePtr::BOTTOM);
2754 Node* ex_io_phi = new PhiNode(ex_r, Type::ABIO);
2755 ex_r->init_req(1, slow_excp);
2756 ex_mem_phi->init_req(1, slow_mem);
2757 ex_io_phi->init_req(1, slow_io);
2758 ex_r->init_req(2, ex_ctl);
2759 ex_mem_phi->init_req(2, ex_mem);
2760 ex_io_phi->init_req(2, ex_io);
2761
2762 transform_later(ex_r);
2763 transform_later(ex_mem_phi);
2764 transform_later(ex_io_phi);
2765
2766 Node* slowpath_false = new IfFalseNode(slowpath_iff);
2767 transform_later(slowpath_false);
2768 Node* rawmem = new StorePNode(slowpath_false, mem, top_adr, TypeRawPtr::BOTTOM, new_top, MemNode::unordered);
2769 transform_later(rawmem);
2770 Node* mark_node = makecon(TypeRawPtr::make((address)markWord::always_locked_prototype().value()));
2771 rawmem = make_store(slowpath_false, rawmem, old_top, oopDesc::mark_offset_in_bytes(), mark_node, T_ADDRESS);
2772 rawmem = make_store(slowpath_false, rawmem, old_top, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
2773 if (UseCompressedClassPointers) {
2774 rawmem = make_store(slowpath_false, rawmem, old_top, oopDesc::klass_gap_offset_in_bytes(), intcon(0), T_INT);
2775 }
2776 Node* fixed_block = make_load(slowpath_false, rawmem, klass_node, in_bytes(InstanceKlass::adr_inlineklass_fixed_block_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2777 Node* pack_handler = make_load(slowpath_false, rawmem, fixed_block, in_bytes(InlineKlass::pack_handler_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
2778
2779 CallLeafNoFPNode* handler_call = new CallLeafNoFPNode(OptoRuntime::pack_inline_type_Type(),
2780 NULL,
2781 "pack handler",
2782 TypeRawPtr::BOTTOM);
2783 handler_call->init_req(TypeFunc::Control, slowpath_false);
2784 handler_call->init_req(TypeFunc::Memory, rawmem);
2785 handler_call->init_req(TypeFunc::I_O, top());
2786 handler_call->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
2787 handler_call->init_req(TypeFunc::ReturnAdr, top());
2788 handler_call->init_req(TypeFunc::Parms, pack_handler);
2789 handler_call->init_req(TypeFunc::Parms+1, old_top);
2790
2791 // We don't know how many values are returned. This assumes the
2792 // worst case, that all available registers are used.
2793 for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2794 if (domain->field_at(i) == Type::HALF) {
2795 slow_call->init_req(i, top());
2796 handler_call->init_req(i+1, top());
2797 continue;
2798 }
2799 Node* proj = transform_later(new ProjNode(call, i));
2800 slow_call->init_req(i, proj);
2801 handler_call->init_req(i+1, proj);
2802 }
2803
2804 // We can safepoint at that new call
2805 slow_call->copy_call_debug_info(&_igvn, call);
2806 transform_later(slow_call);
2807 transform_later(handler_call);
2808
2809 Node* handler_ctl = transform_later(new ProjNode(handler_call, TypeFunc::Control));
2810 rawmem = transform_later(new ProjNode(handler_call, TypeFunc::Memory));
2811 Node* slowpath_false_res = transform_later(new ProjNode(handler_call, TypeFunc::Parms));
2812
2813 MergeMemNode* slowpath_false_mem = MergeMemNode::make(mem);
2814 slowpath_false_mem->set_memory_at(Compile::AliasIdxRaw, rawmem);
2815 transform_later(slowpath_false_mem);
2816
2817 Node* r = new RegionNode(4);
2818 Node* mem_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM);
2819 Node* io_phi = new PhiNode(r, Type::ABIO);
2820 Node* res_phi = new PhiNode(r, TypeInstPtr::BOTTOM);
2821
2822 r->init_req(1, no_allocation_ctl);
2823 mem_phi->init_req(1, mem);
2824 io_phi->init_req(1, io);
2825 res_phi->init_req(1, no_allocation_res);
2826 r->init_req(2, slow_norm);
2827 mem_phi->init_req(2, slow_mem);
2828 io_phi->init_req(2, slow_io);
2829 res_phi->init_req(2, slow_res);
2830 r->init_req(3, handler_ctl);
2831 mem_phi->init_req(3, slowpath_false_mem);
2832 io_phi->init_req(3, io);
2833 res_phi->init_req(3, slowpath_false_res);
2834
2835 transform_later(r);
2836 transform_later(mem_phi);
2837 transform_later(io_phi);
2838 transform_later(res_phi);
2839
2840 assert(projs->nb_resproj == 1, "unexpected number of results");
2841 _igvn.replace_in_uses(projs->fallthrough_catchproj, r);
2842 _igvn.replace_in_uses(projs->fallthrough_memproj, mem_phi);
2843 _igvn.replace_in_uses(projs->fallthrough_ioproj, io_phi);
2844 _igvn.replace_in_uses(projs->resproj[0], res_phi);
2845 _igvn.replace_in_uses(projs->catchall_catchproj, ex_r);
2846 _igvn.replace_in_uses(projs->catchall_memproj, ex_mem_phi);
2847 _igvn.replace_in_uses(projs->catchall_ioproj, ex_io_phi);
2848
2849 _igvn.replace_node(ctl, projs->fallthrough_catchproj);
2850 _igvn.replace_node(mem, projs->fallthrough_memproj);
2851 _igvn.replace_node(io, projs->fallthrough_ioproj);
2852 _igvn.replace_node(res, projs->resproj[0]);
2853 _igvn.replace_node(ex_ctl, projs->catchall_catchproj);
2854 _igvn.replace_node(ex_mem, projs->catchall_memproj);
2855 _igvn.replace_node(ex_io, projs->catchall_ioproj);
2856 }
2857
2858 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2859 assert(check->in(SubTypeCheckNode::Control) == NULL, "should be pinned");
2860 Node* bol = check->unique_out();
2861 Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2862 Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2863 assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2864
2865 for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2866 Node* iff = bol->last_out(i);
2867 assert(iff->is_If(), "where's the if?");
2868
2869 if (iff->in(0)->is_top()) {
2870 _igvn.replace_input_of(iff, 1, C->top());
2871 continue;
2872 }
2873
2874 Node* iftrue = iff->as_If()->proj_out(1);
2875 Node* iffalse = iff->as_If()->proj_out(0);
2876 Node* ctrl = iff->in(0);
2877
2878 Node* subklass = NULL;
2879 if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2880 subklass = obj_or_subklass;
2881 } else {
2882 Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2883 subklass = _igvn.transform(LoadKlassNode::make(_igvn, NULL, C->immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeKlassPtr::OBJECT));
2884 }
2885
2886 Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, NULL, _igvn);
2887
2888 _igvn.replace_input_of(iff, 0, C->top());
2889 _igvn.replace_node(iftrue, not_subtype_ctrl);
2890 _igvn.replace_node(iffalse, ctrl);
2891 }
2892 _igvn.replace_node(check, C->top());
2893 }
2894
2895 //---------------------------eliminate_macro_nodes----------------------
2896 // Eliminate scalar replaced allocations and associated locks.
2897 void PhaseMacroExpand::eliminate_macro_nodes() {
2898 if (C->macro_count() == 0)
2899 return;
2900
2901 // First, attempt to eliminate locks
2902 int cnt = C->macro_count();
2903 for (int i=0; i < cnt; i++) {
2919 success = eliminate_locking_node(n->as_AbstractLock());
2920 }
2921 assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2922 progress = progress || success;
2923 }
2924 }
2925 // Next, attempt to eliminate allocations
2926 _has_locks = false;
2927 progress = true;
2928 while (progress) {
2929 progress = false;
2930 for (int i = C->macro_count(); i > 0; i--) {
2931 Node * n = C->macro_node(i-1);
2932 bool success = false;
2933 debug_only(int old_macro_count = C->macro_count(););
2934 switch (n->class_id()) {
2935 case Node::Class_Allocate:
2936 case Node::Class_AllocateArray:
2937 success = eliminate_allocate_node(n->as_Allocate());
2938 break;
2939 case Node::Class_CallStaticJava: {
2940 CallStaticJavaNode* call = n->as_CallStaticJava();
2941 if (!call->method()->is_method_handle_intrinsic()) {
2942 success = eliminate_boxing_node(n->as_CallStaticJava());
2943 }
2944 break;
2945 }
2946 case Node::Class_Lock:
2947 case Node::Class_Unlock:
2948 assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2949 _has_locks = true;
2950 break;
2951 case Node::Class_ArrayCopy:
2952 break;
2953 case Node::Class_OuterStripMinedLoop:
2954 break;
2955 case Node::Class_SubTypeCheck:
2956 break;
2957 default:
2958 assert(n->Opcode() == Op_LoopLimit ||
2959 n->Opcode() == Op_Opaque1 ||
2960 n->Opcode() == Op_Opaque2 ||
2961 n->Opcode() == Op_Opaque3 ||
2962 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2963 "unknown node type in macro list");
2964 }
2965 assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2971 //------------------------------expand_macro_nodes----------------------
2972 // Returns true if a failure occurred.
2973 bool PhaseMacroExpand::expand_macro_nodes() {
2974 // Last attempt to eliminate macro nodes.
2975 eliminate_macro_nodes();
2976
2977 // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2978 bool progress = true;
2979 while (progress) {
2980 progress = false;
2981 for (int i = C->macro_count(); i > 0; i--) {
2982 Node* n = C->macro_node(i-1);
2983 bool success = false;
2984 debug_only(int old_macro_count = C->macro_count(););
2985 if (n->Opcode() == Op_LoopLimit) {
2986 // Remove it from macro list and put on IGVN worklist to optimize.
2987 C->remove_macro_node(n);
2988 _igvn._worklist.push(n);
2989 success = true;
2990 } else if (n->Opcode() == Op_CallStaticJava) {
2991 CallStaticJavaNode* call = n->as_CallStaticJava();
2992 if (!call->method()->is_method_handle_intrinsic()) {
2993 // Remove it from macro list and put on IGVN worklist to optimize.
2994 C->remove_macro_node(n);
2995 _igvn._worklist.push(n);
2996 success = true;
2997 }
2998 } else if (n->Opcode() == Op_Opaque1 || n->Opcode() == Op_Opaque2) {
2999 _igvn.replace_node(n, n->in(1));
3000 success = true;
3001 #if INCLUDE_RTM_OPT
3002 } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
3003 assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
3004 assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
3005 Node* cmp = n->unique_out();
3006 #ifdef ASSERT
3007 // Validate graph.
3008 assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
3009 BoolNode* bol = cmp->unique_out()->as_Bool();
3010 assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
3011 (bol->_test._test == BoolTest::ne), "");
3012 IfNode* ifn = bol->unique_out()->as_If();
3013 assert((ifn->outcnt() == 2) &&
3014 ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != NULL, "");
3015 #endif
3016 Node* repl = n->in(1);
3017 if (!_has_locks) {
3071 }
3072
3073 debug_only(int old_macro_count = C->macro_count(););
3074 switch (n->class_id()) {
3075 case Node::Class_Lock:
3076 expand_lock_node(n->as_Lock());
3077 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3078 break;
3079 case Node::Class_Unlock:
3080 expand_unlock_node(n->as_Unlock());
3081 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3082 break;
3083 case Node::Class_ArrayCopy:
3084 expand_arraycopy_node(n->as_ArrayCopy());
3085 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3086 break;
3087 case Node::Class_SubTypeCheck:
3088 expand_subtypecheck_node(n->as_SubTypeCheck());
3089 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3090 break;
3091 case Node::Class_CallStaticJava:
3092 expand_mh_intrinsic_return(n->as_CallStaticJava());
3093 C->remove_macro_node(n);
3094 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
3095 break;
3096 default:
3097 assert(false, "unknown node type in macro list");
3098 }
3099 assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
3100 if (C->failing()) return true;
3101
3102 // Clean up the graph so we're less likely to hit the maximum node
3103 // limit
3104 _igvn.set_delay_transform(false);
3105 _igvn.optimize();
3106 if (C->failing()) return true;
3107 _igvn.set_delay_transform(true);
3108 }
3109
3110 // All nodes except Allocate nodes are expanded now. There could be
3111 // new optimization opportunities (such as folding newly created
3112 // load from a just allocated object). Run IGVN.
3113
3114 // expand "macro" nodes
3115 // nodes are removed from the macro list as they are processed
|