1 /*
2 * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "ci/bcEscapeAnalyzer.hpp"
26 #include "ci/ciFlatArrayKlass.hpp"
27 #include "code/vmreg.hpp"
28 #include "compiler/compileLog.hpp"
29 #include "compiler/oopMap.hpp"
30 #include "gc/shared/barrierSet.hpp"
31 #include "gc/shared/c2/barrierSetC2.hpp"
32 #include "interpreter/interpreter.hpp"
33 #include "opto/callGenerator.hpp"
34 #include "opto/callnode.hpp"
35 #include "opto/castnode.hpp"
36 #include "opto/convertnode.hpp"
37 #include "opto/escape.hpp"
38 #include "opto/inlinetypenode.hpp"
39 #include "opto/locknode.hpp"
40 #include "opto/machnode.hpp"
41 #include "opto/matcher.hpp"
42 #include "opto/parse.hpp"
43 #include "opto/regalloc.hpp"
44 #include "opto/regmask.hpp"
45 #include "opto/rootnode.hpp"
46 #include "opto/runtime.hpp"
47 #include "runtime/sharedRuntime.hpp"
48 #include "runtime/stubRoutines.hpp"
49 #include "utilities/powerOfTwo.hpp"
50
51 // Portions of code courtesy of Clifford Click
52
53 // Optimization - Graph Style
54
55 //=============================================================================
56 uint StartNode::size_of() const { return sizeof(*this); }
57 bool StartNode::cmp( const Node &n ) const
58 { return _domain == ((StartNode&)n)._domain; }
59 const Type *StartNode::bottom_type() const { return _domain; }
60 const Type* StartNode::Value(PhaseGVN* phase) const { return _domain; }
61 #ifndef PRODUCT
62 void StartNode::dump_spec(outputStream *st) const { st->print(" #"); _domain->dump_on(st);}
63 void StartNode::dump_compact_spec(outputStream *st) const { /* empty */ }
64 #endif
65
66 //------------------------------Ideal------------------------------------------
67 Node *StartNode::Ideal(PhaseGVN *phase, bool can_reshape){
68 return remove_dead_region(phase, can_reshape) ? this : nullptr;
69 }
70
71 //------------------------------calling_convention-----------------------------
72 void StartNode::calling_convention(BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt) const {
73 SharedRuntime::java_calling_convention(sig_bt, parm_regs, argcnt);
74 }
75
76 //------------------------------Registers--------------------------------------
77 const RegMask &StartNode::in_RegMask(uint) const {
78 return RegMask::Empty;
79 }
80
81 //------------------------------match------------------------------------------
82 // Construct projections for incoming parameters, and their RegMask info
83 Node *StartNode::match(const ProjNode *proj, const Matcher *match, const RegMask* mask) {
84 switch (proj->_con) {
85 case TypeFunc::Control:
86 case TypeFunc::I_O:
87 case TypeFunc::Memory:
88 return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
89 case TypeFunc::FramePtr:
90 return new MachProjNode(this,proj->_con,Matcher::c_frame_ptr_mask, Op_RegP);
91 case TypeFunc::ReturnAdr:
92 return new MachProjNode(this,proj->_con,match->_return_addr_mask,Op_RegP);
93 case TypeFunc::Parms:
94 default: {
95 uint parm_num = proj->_con - TypeFunc::Parms;
96 const Type *t = _domain->field_at(proj->_con);
97 if (t->base() == Type::Half) // 2nd half of Longs and Doubles
98 return new ConNode(Type::TOP);
99 uint ideal_reg = t->ideal_reg();
100 RegMask &rm = match->_calling_convention_mask[parm_num];
101 return new MachProjNode(this,proj->_con,rm,ideal_reg);
102 }
103 }
104 return nullptr;
105 }
106
107 //=============================================================================
108 const char * const ParmNode::names[TypeFunc::Parms+1] = {
109 "Control", "I_O", "Memory", "FramePtr", "ReturnAdr", "Parms"
110 };
111
112 #ifndef PRODUCT
113 void ParmNode::dump_spec(outputStream *st) const {
114 if( _con < TypeFunc::Parms ) {
115 st->print("%s", names[_con]);
116 } else {
117 st->print("Parm%d: ",_con-TypeFunc::Parms);
118 // Verbose and WizardMode dump bottom_type for all nodes
119 if( !Verbose && !WizardMode ) bottom_type()->dump_on(st);
120 }
121 }
122
123 void ParmNode::dump_compact_spec(outputStream *st) const {
124 if (_con < TypeFunc::Parms) {
125 st->print("%s", names[_con]);
126 } else {
127 st->print("%d:", _con-TypeFunc::Parms);
128 // unconditionally dump bottom_type
129 bottom_type()->dump_on(st);
130 }
131 }
132 #endif
133
134 uint ParmNode::ideal_reg() const {
135 switch( _con ) {
136 case TypeFunc::Control : // fall through
137 case TypeFunc::I_O : // fall through
138 case TypeFunc::Memory : return 0;
139 case TypeFunc::FramePtr : // fall through
140 case TypeFunc::ReturnAdr: return Op_RegP;
141 default : assert( _con > TypeFunc::Parms, "" );
142 // fall through
143 case TypeFunc::Parms : {
144 // Type of argument being passed
145 const Type *t = in(0)->as_Start()->_domain->field_at(_con);
146 return t->ideal_reg();
147 }
148 }
149 ShouldNotReachHere();
150 return 0;
151 }
152
153 //=============================================================================
154 ReturnNode::ReturnNode(uint edges, Node *cntrl, Node *i_o, Node *memory, Node *frameptr, Node *retadr ) : Node(edges) {
155 init_req(TypeFunc::Control,cntrl);
156 init_req(TypeFunc::I_O,i_o);
157 init_req(TypeFunc::Memory,memory);
158 init_req(TypeFunc::FramePtr,frameptr);
159 init_req(TypeFunc::ReturnAdr,retadr);
160 }
161
162 Node *ReturnNode::Ideal(PhaseGVN *phase, bool can_reshape){
163 return remove_dead_region(phase, can_reshape) ? this : nullptr;
164 }
165
166 const Type* ReturnNode::Value(PhaseGVN* phase) const {
167 return ( phase->type(in(TypeFunc::Control)) == Type::TOP)
168 ? Type::TOP
169 : Type::BOTTOM;
170 }
171
172 // Do we Match on this edge index or not? No edges on return nodes
173 uint ReturnNode::match_edge(uint idx) const {
174 return 0;
175 }
176
177
178 #ifndef PRODUCT
179 void ReturnNode::dump_req(outputStream *st, DumpConfig* dc) const {
180 // Dump the required inputs, after printing "returns"
181 uint i; // Exit value of loop
182 for (i = 0; i < req(); i++) { // For all required inputs
183 if (i == TypeFunc::Parms) st->print("returns ");
184 Node* p = in(i);
185 if (p != nullptr) {
186 p->dump_idx(false, st, dc);
187 st->print(" ");
188 } else {
189 st->print("_ ");
190 }
191 }
192 }
193 #endif
194
195 //=============================================================================
196 RethrowNode::RethrowNode(
197 Node* cntrl,
198 Node* i_o,
199 Node* memory,
200 Node* frameptr,
201 Node* ret_adr,
202 Node* exception
203 ) : Node(TypeFunc::Parms + 1) {
204 init_req(TypeFunc::Control , cntrl );
205 init_req(TypeFunc::I_O , i_o );
206 init_req(TypeFunc::Memory , memory );
207 init_req(TypeFunc::FramePtr , frameptr );
208 init_req(TypeFunc::ReturnAdr, ret_adr);
209 init_req(TypeFunc::Parms , exception);
210 }
211
212 Node *RethrowNode::Ideal(PhaseGVN *phase, bool can_reshape){
213 return remove_dead_region(phase, can_reshape) ? this : nullptr;
214 }
215
216 const Type* RethrowNode::Value(PhaseGVN* phase) const {
217 return (phase->type(in(TypeFunc::Control)) == Type::TOP)
218 ? Type::TOP
219 : Type::BOTTOM;
220 }
221
222 uint RethrowNode::match_edge(uint idx) const {
223 return 0;
224 }
225
226 #ifndef PRODUCT
227 void RethrowNode::dump_req(outputStream *st, DumpConfig* dc) const {
228 // Dump the required inputs, after printing "exception"
229 uint i; // Exit value of loop
230 for (i = 0; i < req(); i++) { // For all required inputs
231 if (i == TypeFunc::Parms) st->print("exception ");
232 Node* p = in(i);
233 if (p != nullptr) {
234 p->dump_idx(false, st, dc);
235 st->print(" ");
236 } else {
237 st->print("_ ");
238 }
239 }
240 }
241 #endif
242
243 //=============================================================================
244 // Do we Match on this edge index or not? Match only target address & method
245 uint TailCallNode::match_edge(uint idx) const {
246 return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;
247 }
248
249 //=============================================================================
250 // Do we Match on this edge index or not? Match only target address & oop
251 uint TailJumpNode::match_edge(uint idx) const {
252 return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;
253 }
254
255 //=============================================================================
256 JVMState::JVMState(ciMethod* method, JVMState* caller) :
257 _method(method),
258 _receiver_info(nullptr) {
259 assert(method != nullptr, "must be valid call site");
260 _bci = InvocationEntryBci;
261 _reexecute = Reexecute_Undefined;
262 DEBUG_ONLY(_bci = -99); // random garbage value
263 DEBUG_ONLY(_map = (SafePointNode*)-1);
264 _caller = caller;
265 _depth = 1 + (caller == nullptr ? 0 : caller->depth());
266 _locoff = TypeFunc::Parms;
267 _stkoff = _locoff + _method->max_locals();
268 _monoff = _stkoff + _method->max_stack();
269 _scloff = _monoff;
270 _endoff = _monoff;
271 _sp = 0;
272 }
273 JVMState::JVMState(int stack_size) :
274 _method(nullptr),
275 _receiver_info(nullptr) {
276 _bci = InvocationEntryBci;
277 _reexecute = Reexecute_Undefined;
278 DEBUG_ONLY(_map = (SafePointNode*)-1);
279 _caller = nullptr;
280 _depth = 1;
281 _locoff = TypeFunc::Parms;
282 _stkoff = _locoff;
283 _monoff = _stkoff + stack_size;
284 _scloff = _monoff;
285 _endoff = _monoff;
286 _sp = 0;
287 }
288
289 //--------------------------------of_depth-------------------------------------
290 JVMState* JVMState::of_depth(int d) const {
291 const JVMState* jvmp = this;
292 assert(0 < d && (uint)d <= depth(), "oob");
293 for (int skip = depth() - d; skip > 0; skip--) {
294 jvmp = jvmp->caller();
295 }
296 assert(jvmp->depth() == (uint)d, "found the right one");
297 return (JVMState*)jvmp;
298 }
299
300 //-----------------------------same_calls_as-----------------------------------
301 bool JVMState::same_calls_as(const JVMState* that) const {
302 if (this == that) return true;
303 if (this->depth() != that->depth()) return false;
304 const JVMState* p = this;
305 const JVMState* q = that;
306 for (;;) {
307 if (p->_method != q->_method) return false;
308 if (p->_method == nullptr) return true; // bci is irrelevant
309 if (p->_bci != q->_bci) return false;
310 if (p->_reexecute != q->_reexecute) return false;
311 p = p->caller();
312 q = q->caller();
313 if (p == q) return true;
314 assert(p != nullptr && q != nullptr, "depth check ensures we don't run off end");
315 }
316 }
317
318 //------------------------------debug_start------------------------------------
319 uint JVMState::debug_start() const {
320 DEBUG_ONLY(JVMState* jvmroot = of_depth(1));
321 assert(jvmroot->locoff() <= this->locoff(), "youngest JVMState must be last");
322 return of_depth(1)->locoff();
323 }
324
325 //-------------------------------debug_end-------------------------------------
326 uint JVMState::debug_end() const {
327 DEBUG_ONLY(JVMState* jvmroot = of_depth(1));
328 assert(jvmroot->endoff() <= this->endoff(), "youngest JVMState must be last");
329 return endoff();
330 }
331
332 //------------------------------debug_depth------------------------------------
333 uint JVMState::debug_depth() const {
334 uint total = 0;
335 for (const JVMState* jvmp = this; jvmp != nullptr; jvmp = jvmp->caller()) {
336 total += jvmp->debug_size();
337 }
338 return total;
339 }
340
341 #ifndef PRODUCT
342
343 //------------------------------format_helper----------------------------------
344 // Given an allocation (a Chaitin object) and a Node decide if the Node carries
345 // any defined value or not. If it does, print out the register or constant.
346 static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, const char *msg, uint i, GrowableArray<SafePointScalarObjectNode*> *scobjs ) {
347 if (n == nullptr) { st->print(" null"); return; }
348 if (n->is_SafePointScalarObject()) {
349 // Scalar replacement.
350 SafePointScalarObjectNode* spobj = n->as_SafePointScalarObject();
351 scobjs->append_if_missing(spobj);
352 int sco_n = scobjs->find(spobj);
353 assert(sco_n >= 0, "");
354 st->print(" %s%d]=#ScObj" INT32_FORMAT, msg, i, sco_n);
355 return;
356 }
357 if (regalloc->node_regs_max_index() > 0 &&
358 OptoReg::is_valid(regalloc->get_reg_first(n))) { // Check for undefined
359 char buf[50];
360 regalloc->dump_register(n,buf,sizeof(buf));
361 st->print(" %s%d]=%s",msg,i,buf);
362 } else { // No register, but might be constant
363 const Type *t = n->bottom_type();
364 switch (t->base()) {
365 case Type::Int:
366 st->print(" %s%d]=#" INT32_FORMAT,msg,i,t->is_int()->get_con());
367 break;
368 case Type::AnyPtr:
369 assert( t == TypePtr::NULL_PTR || n->in_dump(), "" );
370 st->print(" %s%d]=#null",msg,i);
371 break;
372 case Type::AryPtr:
373 case Type::InstPtr:
374 st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->isa_oopptr()->const_oop()));
375 break;
376 case Type::KlassPtr:
377 case Type::AryKlassPtr:
378 case Type::InstKlassPtr:
379 st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_klassptr()->exact_klass()));
380 break;
381 case Type::MetadataPtr:
382 st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_metadataptr()->metadata()));
383 break;
384 case Type::NarrowOop:
385 st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_oopptr()->const_oop()));
386 break;
387 case Type::RawPtr:
388 st->print(" %s%d]=#Raw" INTPTR_FORMAT,msg,i,p2i(t->is_rawptr()));
389 break;
390 case Type::DoubleCon:
391 st->print(" %s%d]=#%fD",msg,i,t->is_double_constant()->_d);
392 break;
393 case Type::FloatCon:
394 st->print(" %s%d]=#%fF",msg,i,t->is_float_constant()->_f);
395 break;
396 case Type::Long:
397 st->print(" %s%d]=#" INT64_FORMAT,msg,i,(int64_t)(t->is_long()->get_con()));
398 break;
399 case Type::Half:
400 case Type::Top:
401 st->print(" %s%d]=_",msg,i);
402 break;
403 default: ShouldNotReachHere();
404 }
405 }
406 }
407
408 //---------------------print_method_with_lineno--------------------------------
409 void JVMState::print_method_with_lineno(outputStream* st, bool show_name) const {
410 if (show_name) _method->print_short_name(st);
411
412 int lineno = _method->line_number_from_bci(_bci);
413 if (lineno != -1) {
414 st->print(" @ bci:%d (line %d)", _bci, lineno);
415 } else {
416 st->print(" @ bci:%d", _bci);
417 }
418 }
419
420 //------------------------------format-----------------------------------------
421 void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) const {
422 st->print(" #");
423 if (_method) {
424 print_method_with_lineno(st, true);
425 } else {
426 st->print_cr(" runtime stub ");
427 return;
428 }
429 if (n->is_MachSafePoint()) {
430 GrowableArray<SafePointScalarObjectNode*> scobjs;
431 MachSafePointNode *mcall = n->as_MachSafePoint();
432 uint i;
433 // Print locals
434 for (i = 0; i < (uint)loc_size(); i++)
435 format_helper(regalloc, st, mcall->local(this, i), "L[", i, &scobjs);
436 // Print stack
437 for (i = 0; i < (uint)stk_size(); i++) {
438 if ((uint)(_stkoff + i) >= mcall->len())
439 st->print(" oob ");
440 else
441 format_helper(regalloc, st, mcall->stack(this, i), "STK[", i, &scobjs);
442 }
443 for (i = 0; (int)i < nof_monitors(); i++) {
444 Node *box = mcall->monitor_box(this, i);
445 Node *obj = mcall->monitor_obj(this, i);
446 if (regalloc->node_regs_max_index() > 0 &&
447 OptoReg::is_valid(regalloc->get_reg_first(box))) {
448 box = BoxLockNode::box_node(box);
449 format_helper(regalloc, st, box, "MON-BOX[", i, &scobjs);
450 } else {
451 OptoReg::Name box_reg = BoxLockNode::reg(box);
452 st->print(" MON-BOX%d=%s+%d",
453 i,
454 OptoReg::regname(OptoReg::c_frame_pointer),
455 regalloc->reg2offset(box_reg));
456 }
457 const char* obj_msg = "MON-OBJ[";
458 if (EliminateLocks) {
459 if (BoxLockNode::box_node(box)->is_eliminated())
460 obj_msg = "MON-OBJ(LOCK ELIMINATED)[";
461 }
462 format_helper(regalloc, st, obj, obj_msg, i, &scobjs);
463 }
464
465 for (i = 0; i < (uint)scobjs.length(); i++) {
466 // Scalar replaced objects.
467 st->cr();
468 st->print(" # ScObj" INT32_FORMAT " ", i);
469 SafePointScalarObjectNode* spobj = scobjs.at(i);
470 ciKlass* cik = spobj->bottom_type()->is_oopptr()->exact_klass();
471 assert(cik->is_instance_klass() ||
472 cik->is_array_klass(), "Not supported allocation.");
473 ciInstanceKlass *iklass = nullptr;
474 if (cik->is_instance_klass()) {
475 cik->print_name_on(st);
476 iklass = cik->as_instance_klass();
477 } else if (cik->is_type_array_klass()) {
478 cik->as_array_klass()->base_element_type()->print_name_on(st);
479 st->print("[%d]", spobj->n_fields());
480 } else if (cik->is_obj_array_klass()) {
481 ciKlass* cie = cik->as_obj_array_klass()->base_element_klass();
482 if (cie->is_instance_klass()) {
483 cie->print_name_on(st);
484 } else if (cie->is_type_array_klass()) {
485 cie->as_array_klass()->base_element_type()->print_name_on(st);
486 } else {
487 ShouldNotReachHere();
488 }
489 st->print("[%d]", spobj->n_fields());
490 int ndim = cik->as_array_klass()->dimension() - 1;
491 while (ndim-- > 0) {
492 st->print("[]");
493 }
494 } else if (cik->is_flat_array_klass()) {
495 ciKlass* cie = cik->as_flat_array_klass()->base_element_klass();
496 cie->print_name_on(st);
497 st->print("[%d]", spobj->n_fields());
498 int ndim = cik->as_array_klass()->dimension() - 1;
499 while (ndim-- > 0) {
500 st->print("[]");
501 }
502 }
503 st->print("={");
504 uint nf = spobj->n_fields();
505 if (nf > 0) {
506 uint first_ind = spobj->first_index(mcall->jvms());
507 if (iklass != nullptr && iklass->is_inlinetype()) {
508 Node* null_marker = mcall->in(first_ind++);
509 if (!null_marker->is_top()) {
510 st->print(" [null marker");
511 format_helper(regalloc, st, null_marker, ":", -1, nullptr);
512 }
513 }
514 Node* fld_node = mcall->in(first_ind);
515 if (iklass != nullptr) {
516 st->print(" [");
517 iklass->nonstatic_field_at(0)->print_name_on(st);
518 format_helper(regalloc, st, fld_node, ":", 0, &scobjs);
519 } else {
520 format_helper(regalloc, st, fld_node, "[", 0, &scobjs);
521 }
522 for (uint j = 1; j < nf; j++) {
523 fld_node = mcall->in(first_ind+j);
524 if (iklass != nullptr) {
525 st->print(", [");
526 iklass->nonstatic_field_at(j)->print_name_on(st);
527 format_helper(regalloc, st, fld_node, ":", j, &scobjs);
528 } else {
529 format_helper(regalloc, st, fld_node, ", [", j, &scobjs);
530 }
531 }
532 }
533 st->print(" }");
534 }
535 }
536 st->cr();
537 if (caller() != nullptr) caller()->format(regalloc, n, st);
538 }
539
540
541 void JVMState::dump_spec(outputStream *st) const {
542 if (_method != nullptr) {
543 bool printed = false;
544 if (!Verbose) {
545 // The JVMS dumps make really, really long lines.
546 // Take out the most boring parts, which are the package prefixes.
547 char buf[500];
548 stringStream namest(buf, sizeof(buf));
549 _method->print_short_name(&namest);
550 if (namest.count() < sizeof(buf)) {
551 const char* name = namest.base();
552 if (name[0] == ' ') ++name;
553 const char* endcn = strchr(name, ':'); // end of class name
554 if (endcn == nullptr) endcn = strchr(name, '(');
555 if (endcn == nullptr) endcn = name + strlen(name);
556 while (endcn > name && endcn[-1] != '.' && endcn[-1] != '/')
557 --endcn;
558 st->print(" %s", endcn);
559 printed = true;
560 }
561 }
562 print_method_with_lineno(st, !printed);
563 if(_reexecute == Reexecute_True)
564 st->print(" reexecute");
565 } else {
566 st->print(" runtime stub");
567 }
568 if (caller() != nullptr) caller()->dump_spec(st);
569 }
570
571
572 void JVMState::dump_on(outputStream* st) const {
573 bool print_map = _map && !((uintptr_t)_map & 1) &&
574 ((caller() == nullptr) || (caller()->map() != _map));
575 if (print_map) {
576 if (_map->len() > _map->req()) { // _map->has_exceptions()
577 Node* ex = _map->in(_map->req()); // _map->next_exception()
578 // skip the first one; it's already being printed
579 while (ex != nullptr && ex->len() > ex->req()) {
580 ex = ex->in(ex->req()); // ex->next_exception()
581 ex->dump(1);
582 }
583 }
584 _map->dump(Verbose ? 2 : 1);
585 }
586 if (caller() != nullptr) {
587 caller()->dump_on(st);
588 }
589 st->print("JVMS depth=%d loc=%d stk=%d arg=%d mon=%d scalar=%d end=%d mondepth=%d sp=%d bci=%d reexecute=%s method=",
590 depth(), locoff(), stkoff(), argoff(), monoff(), scloff(), endoff(), monitor_depth(), sp(), bci(), should_reexecute()?"true":"false");
591 if (_method == nullptr) {
592 st->print_cr("(none)");
593 } else {
594 _method->print_name(st);
595 st->cr();
596 if (bci() >= 0 && bci() < _method->code_size()) {
597 st->print(" bc: ");
598 _method->print_codes_on(bci(), bci()+1, st);
599 }
600 }
601 }
602
603 // Extra way to dump a jvms from the debugger,
604 // to avoid a bug with C++ member function calls.
605 void dump_jvms(JVMState* jvms) {
606 jvms->dump();
607 }
608 #endif
609
610 //--------------------------clone_shallow--------------------------------------
611 JVMState* JVMState::clone_shallow(Compile* C) const {
612 JVMState* n = has_method() ? new (C) JVMState(_method, _caller) : new (C) JVMState(0);
613 n->set_bci(_bci);
614 n->_reexecute = _reexecute;
615 n->set_locoff(_locoff);
616 n->set_stkoff(_stkoff);
617 n->set_monoff(_monoff);
618 n->set_scloff(_scloff);
619 n->set_endoff(_endoff);
620 n->set_sp(_sp);
621 n->set_map(_map);
622 n->set_receiver_info(_receiver_info);
623 return n;
624 }
625
626 //---------------------------clone_deep----------------------------------------
627 JVMState* JVMState::clone_deep(Compile* C) const {
628 JVMState* n = clone_shallow(C);
629 for (JVMState* p = n; p->_caller != nullptr; p = p->_caller) {
630 p->_caller = p->_caller->clone_shallow(C);
631 }
632 assert(n->depth() == depth(), "sanity");
633 assert(n->debug_depth() == debug_depth(), "sanity");
634 return n;
635 }
636
637 /**
638 * Reset map for all callers
639 */
640 void JVMState::set_map_deep(SafePointNode* map) {
641 for (JVMState* p = this; p != nullptr; p = p->_caller) {
642 p->set_map(map);
643 }
644 }
645
646 // unlike set_map(), this is two-way setting.
647 void JVMState::bind_map(SafePointNode* map) {
648 set_map(map);
649 _map->set_jvms(this);
650 }
651
652 // Adapt offsets in in-array after adding or removing an edge.
653 // Prerequisite is that the JVMState is used by only one node.
654 void JVMState::adapt_position(int delta) {
655 for (JVMState* jvms = this; jvms != nullptr; jvms = jvms->caller()) {
656 jvms->set_locoff(jvms->locoff() + delta);
657 jvms->set_stkoff(jvms->stkoff() + delta);
658 jvms->set_monoff(jvms->monoff() + delta);
659 jvms->set_scloff(jvms->scloff() + delta);
660 jvms->set_endoff(jvms->endoff() + delta);
661 }
662 }
663
664 // Mirror the stack size calculation in the deopt code
665 // How much stack space would we need at this point in the program in
666 // case of deoptimization?
667 int JVMState::interpreter_frame_size() const {
668 const JVMState* jvms = this;
669 int size = 0;
670 int callee_parameters = 0;
671 int callee_locals = 0;
672 int extra_args = method()->max_stack() - stk_size();
673
674 while (jvms != nullptr) {
675 int locks = jvms->nof_monitors();
676 int temps = jvms->stk_size();
677 bool is_top_frame = (jvms == this);
678 ciMethod* method = jvms->method();
679
680 int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
681 temps + callee_parameters,
682 extra_args,
683 locks,
684 callee_parameters,
685 callee_locals,
686 is_top_frame);
687 size += frame_size;
688
689 callee_parameters = method->size_of_parameters();
690 callee_locals = method->max_locals();
691 extra_args = 0;
692 jvms = jvms->caller();
693 }
694 return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
695 }
696
697 // Compute receiver info for a compiled lambda form at call site.
698 ciInstance* JVMState::compute_receiver_info(ciMethod* callee) const {
699 assert(callee != nullptr && callee->is_compiled_lambda_form(), "");
700 if (has_method() && method()->is_compiled_lambda_form()) { // callee is not a MH invoker
701 Node* recv = map()->argument(this, 0);
702 assert(recv != nullptr, "");
703 const TypeOopPtr* recv_toop = recv->bottom_type()->isa_oopptr();
704 if (recv_toop != nullptr && recv_toop->const_oop() != nullptr) {
705 return recv_toop->const_oop()->as_instance();
706 }
707 }
708 return nullptr;
709 }
710
711 //=============================================================================
712 bool CallNode::cmp( const Node &n ) const
713 { return _tf == ((CallNode&)n)._tf && _jvms == ((CallNode&)n)._jvms; }
714 #ifndef PRODUCT
715 void CallNode::dump_req(outputStream *st, DumpConfig* dc) const {
716 // Dump the required inputs, enclosed in '(' and ')'
717 uint i; // Exit value of loop
718 for (i = 0; i < req(); i++) { // For all required inputs
719 if (i == TypeFunc::Parms) st->print("(");
720 Node* p = in(i);
721 if (p != nullptr) {
722 p->dump_idx(false, st, dc);
723 st->print(" ");
724 } else {
725 st->print("_ ");
726 }
727 }
728 st->print(")");
729 }
730
731 void CallNode::dump_spec(outputStream *st) const {
732 st->print(" ");
733 if (tf() != nullptr) tf()->dump_on(st);
734 if (_cnt != COUNT_UNKNOWN) st->print(" C=%f",_cnt);
735 if (jvms() != nullptr) jvms()->dump_spec(st);
736 }
737
738 void AllocateNode::dump_spec(outputStream* st) const {
739 st->print(" ");
740 if (tf() != nullptr) {
741 tf()->dump_on(st);
742 }
743 if (_cnt != COUNT_UNKNOWN) {
744 st->print(" C=%f", _cnt);
745 }
746 const Node* const klass_node = in(KlassNode);
747 if (klass_node != nullptr) {
748 const TypeKlassPtr* const klass_ptr = klass_node->bottom_type()->isa_klassptr();
749
750 if (klass_ptr != nullptr && klass_ptr->klass_is_exact()) {
751 st->print(" allocationKlass:");
752 klass_ptr->exact_klass()->print_name_on(st);
753 }
754 }
755 if (jvms() != nullptr) {
756 jvms()->dump_spec(st);
757 }
758 }
759 #endif
760
761 const Type *CallNode::bottom_type() const { return tf()->range_cc(); }
762 const Type* CallNode::Value(PhaseGVN* phase) const {
763 if (in(0) == nullptr || phase->type(in(0)) == Type::TOP) {
764 return Type::TOP;
765 }
766 return tf()->range_cc();
767 }
768
769 //------------------------------calling_convention-----------------------------
770 void CallNode::calling_convention(BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt) const {
771 if (_entry_point == StubRoutines::store_inline_type_fields_to_buf()) {
772 // The call to that stub is a special case: its inputs are
773 // multiple values returned from a call and so it should follow
774 // the return convention.
775 SharedRuntime::java_return_convention(sig_bt, parm_regs, argcnt);
776 return;
777 }
778 // Use the standard compiler calling convention
779 SharedRuntime::java_calling_convention(sig_bt, parm_regs, argcnt);
780 }
781
782
783 //------------------------------match------------------------------------------
784 // Construct projections for control, I/O, memory-fields, ..., and
785 // return result(s) along with their RegMask info
786 Node *CallNode::match(const ProjNode *proj, const Matcher *match, const RegMask* mask) {
787 uint con = proj->_con;
788 const TypeTuple* range_cc = tf()->range_cc();
789 if (con >= TypeFunc::Parms) {
790 if (tf()->returns_inline_type_as_fields()) {
791 // The call returns multiple values (inline type fields): we
792 // create one projection per returned value.
793 assert(con <= TypeFunc::Parms+1 || InlineTypeReturnedAsFields, "only for multi value return");
794 uint ideal_reg = range_cc->field_at(con)->ideal_reg();
795 return new MachProjNode(this, con, mask[con-TypeFunc::Parms], ideal_reg);
796 } else {
797 if (con == TypeFunc::Parms) {
798 uint ideal_reg = range_cc->field_at(TypeFunc::Parms)->ideal_reg();
799 OptoRegPair regs = Opcode() == Op_CallLeafVector
800 ? match->vector_return_value(ideal_reg) // Calls into assembly vector routine
801 : match->c_return_value(ideal_reg);
802 RegMask rm = RegMask(regs.first());
803
804 if (Opcode() == Op_CallLeafVector) {
805 // If the return is in vector, compute appropriate regmask taking into account the whole range
806 if(ideal_reg >= Op_VecA && ideal_reg <= Op_VecZ) {
807 if(OptoReg::is_valid(regs.second())) {
808 for (OptoReg::Name r = regs.first(); r <= regs.second(); r = OptoReg::add(r, 1)) {
809 rm.Insert(r);
810 }
811 }
812 }
813 }
814
815 if (OptoReg::is_valid(regs.second())) {
816 rm.Insert(regs.second());
817 }
818 return new MachProjNode(this,con,rm,ideal_reg);
819 } else {
820 assert(con == TypeFunc::Parms+1, "only one return value");
821 assert(range_cc->field_at(TypeFunc::Parms+1) == Type::HALF, "");
822 return new MachProjNode(this,con, RegMask::Empty, (uint)OptoReg::Bad);
823 }
824 }
825 }
826
827 switch (con) {
828 case TypeFunc::Control:
829 case TypeFunc::I_O:
830 case TypeFunc::Memory:
831 return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
832
833 case TypeFunc::ReturnAdr:
834 case TypeFunc::FramePtr:
835 default:
836 ShouldNotReachHere();
837 }
838 return nullptr;
839 }
840
841 // Do we Match on this edge index or not? Match no edges
842 uint CallNode::match_edge(uint idx) const {
843 return 0;
844 }
845
846 //
847 // Determine whether the call could modify the field of the specified
848 // instance at the specified offset.
849 //
850 bool CallNode::may_modify(const TypeOopPtr* t_oop, PhaseValues* phase) {
851 assert((t_oop != nullptr), "sanity");
852 if (is_call_to_arraycopystub() && strcmp(_name, "unsafe_arraycopy") != 0) {
853 const TypeTuple* args = _tf->domain_sig();
854 Node* dest = nullptr;
855 // Stubs that can be called once an ArrayCopyNode is expanded have
856 // different signatures. Look for the second pointer argument,
857 // that is the destination of the copy.
858 for (uint i = TypeFunc::Parms, j = 0; i < args->cnt(); i++) {
859 if (args->field_at(i)->isa_ptr()) {
860 j++;
861 if (j == 2) {
862 dest = in(i);
863 break;
864 }
865 }
866 }
867 guarantee(dest != nullptr, "Call had only one ptr in, broken IR!");
868 if (!dest->is_top() && may_modify_arraycopy_helper(phase->type(dest)->is_oopptr(), t_oop, phase)) {
869 return true;
870 }
871 return false;
872 }
873 if (t_oop->is_known_instance()) {
874 // The instance_id is set only for scalar-replaceable allocations which
875 // are not passed as arguments according to Escape Analysis.
876 return false;
877 }
878 if (t_oop->is_ptr_to_boxed_value()) {
879 ciKlass* boxing_klass = t_oop->is_instptr()->instance_klass();
880 if (is_CallStaticJava() && as_CallStaticJava()->is_boxing_method()) {
881 // Skip unrelated boxing methods.
882 Node* proj = proj_out_or_null(TypeFunc::Parms);
883 if ((proj == nullptr) || (phase->type(proj)->is_instptr()->instance_klass() != boxing_klass)) {
884 return false;
885 }
886 }
887 if (is_CallJava() && as_CallJava()->method() != nullptr) {
888 ciMethod* meth = as_CallJava()->method();
889 if (meth->is_getter()) {
890 return false;
891 }
892 // May modify (by reflection) if an boxing object is passed
893 // as argument or returned.
894 Node* proj = returns_pointer() ? proj_out_or_null(TypeFunc::Parms) : nullptr;
895 if (proj != nullptr) {
896 const TypeInstPtr* inst_t = phase->type(proj)->isa_instptr();
897 if ((inst_t != nullptr) && (!inst_t->klass_is_exact() ||
898 (inst_t->instance_klass() == boxing_klass))) {
899 return true;
900 }
901 }
902 const TypeTuple* d = tf()->domain_cc();
903 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
904 const TypeInstPtr* inst_t = d->field_at(i)->isa_instptr();
905 if ((inst_t != nullptr) && (!inst_t->klass_is_exact() ||
906 (inst_t->instance_klass() == boxing_klass))) {
907 return true;
908 }
909 }
910 return false;
911 }
912 }
913 return true;
914 }
915
916 // Does this call have a direct reference to n other than debug information?
917 bool CallNode::has_non_debug_use(Node* n) {
918 const TypeTuple* d = tf()->domain_cc();
919 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
920 if (in(i) == n) {
921 return true;
922 }
923 }
924 return false;
925 }
926
927 bool CallNode::has_debug_use(Node* n) {
928 if (jvms() != nullptr) {
929 for (uint i = jvms()->debug_start(); i < jvms()->debug_end(); i++) {
930 if (in(i) == n) {
931 return true;
932 }
933 }
934 }
935 return false;
936 }
937
938 // Returns the unique CheckCastPP of a call
939 // or 'this' if there are several CheckCastPP or unexpected uses
940 // or returns null if there is no one.
941 Node *CallNode::result_cast() {
942 Node *cast = nullptr;
943
944 Node *p = proj_out_or_null(TypeFunc::Parms);
945 if (p == nullptr)
946 return nullptr;
947
948 for (DUIterator_Fast imax, i = p->fast_outs(imax); i < imax; i++) {
949 Node *use = p->fast_out(i);
950 if (use->is_CheckCastPP()) {
951 if (cast != nullptr) {
952 return this; // more than 1 CheckCastPP
953 }
954 cast = use;
955 } else if (!use->is_Initialize() &&
956 !use->is_AddP() &&
957 use->Opcode() != Op_MemBarStoreStore) {
958 // Expected uses are restricted to a CheckCastPP, an Initialize
959 // node, a MemBarStoreStore (clone) and AddP nodes. If we
960 // encounter any other use (a Phi node can be seen in rare
961 // cases) return this to prevent incorrect optimizations.
962 return this;
963 }
964 }
965 return cast;
966 }
967
968
969 CallProjections* CallNode::extract_projections(bool separate_io_proj, bool do_asserts) const {
970 uint max_res = TypeFunc::Parms-1;
971 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
972 ProjNode *pn = fast_out(i)->as_Proj();
973 max_res = MAX2(max_res, pn->_con);
974 }
975
976 assert(max_res < _tf->range_cc()->cnt(), "result out of bounds");
977
978 uint projs_size = sizeof(CallProjections);
979 if (max_res > TypeFunc::Parms) {
980 projs_size += (max_res-TypeFunc::Parms)*sizeof(Node*);
981 }
982 char* projs_storage = resource_allocate_bytes(projs_size);
983 CallProjections* projs = new(projs_storage)CallProjections(max_res - TypeFunc::Parms + 1);
984
985 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
986 ProjNode *pn = fast_out(i)->as_Proj();
987 if (pn->outcnt() == 0) continue;
988 switch (pn->_con) {
989 case TypeFunc::Control:
990 {
991 // For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
992 projs->fallthrough_proj = pn;
993 const Node* cn = pn->unique_ctrl_out_or_null();
994 if (cn != nullptr && cn->is_Catch()) {
995 ProjNode *cpn = nullptr;
996 for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
997 cpn = cn->fast_out(k)->as_Proj();
998 assert(cpn->is_CatchProj(), "must be a CatchProjNode");
999 if (cpn->_con == CatchProjNode::fall_through_index)
1000 projs->fallthrough_catchproj = cpn;
1001 else {
1002 assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
1003 projs->catchall_catchproj = cpn;
1004 }
1005 }
1006 }
1007 break;
1008 }
1009 case TypeFunc::I_O:
1010 if (pn->_is_io_use)
1011 projs->catchall_ioproj = pn;
1012 else
1013 projs->fallthrough_ioproj = pn;
1014 for (DUIterator j = pn->outs(); pn->has_out(j); j++) {
1015 Node* e = pn->out(j);
1016 if (e->Opcode() == Op_CreateEx && e->in(0)->is_CatchProj() && e->outcnt() > 0) {
1017 assert(projs->exobj == nullptr, "only one");
1018 projs->exobj = e;
1019 }
1020 }
1021 break;
1022 case TypeFunc::Memory:
1023 if (pn->_is_io_use)
1024 projs->catchall_memproj = pn;
1025 else
1026 projs->fallthrough_memproj = pn;
1027 break;
1028 case TypeFunc::Parms:
1029 projs->resproj[0] = pn;
1030 break;
1031 default:
1032 assert(pn->_con <= max_res, "unexpected projection from allocation node.");
1033 projs->resproj[pn->_con-TypeFunc::Parms] = pn;
1034 break;
1035 }
1036 }
1037
1038 // The resproj may not exist because the result could be ignored
1039 // and the exception object may not exist if an exception handler
1040 // swallows the exception but all the other must exist and be found.
1041 do_asserts = do_asserts && !Compile::current()->inlining_incrementally();
1042 assert(!do_asserts || projs->fallthrough_proj != nullptr, "must be found");
1043 assert(!do_asserts || projs->fallthrough_catchproj != nullptr, "must be found");
1044 assert(!do_asserts || projs->fallthrough_memproj != nullptr, "must be found");
1045 assert(!do_asserts || projs->fallthrough_ioproj != nullptr, "must be found");
1046 assert(!do_asserts || projs->catchall_catchproj != nullptr, "must be found");
1047 if (separate_io_proj) {
1048 assert(!do_asserts || projs->catchall_memproj != nullptr, "must be found");
1049 assert(!do_asserts || projs->catchall_ioproj != nullptr, "must be found");
1050 }
1051 return projs;
1052 }
1053
1054 Node* CallNode::Ideal(PhaseGVN* phase, bool can_reshape) {
1055 #ifdef ASSERT
1056 // Validate attached generator
1057 CallGenerator* cg = generator();
1058 if (cg != nullptr) {
1059 assert((is_CallStaticJava() && cg->is_mh_late_inline()) ||
1060 (is_CallDynamicJava() && cg->is_virtual_late_inline()), "mismatch");
1061 }
1062 #endif // ASSERT
1063 return SafePointNode::Ideal(phase, can_reshape);
1064 }
1065
1066 bool CallNode::is_call_to_arraycopystub() const {
1067 if (_name != nullptr && strstr(_name, "arraycopy") != nullptr) {
1068 return true;
1069 }
1070 return false;
1071 }
1072
1073 //=============================================================================
1074 uint CallJavaNode::size_of() const { return sizeof(*this); }
1075 bool CallJavaNode::cmp( const Node &n ) const {
1076 CallJavaNode &call = (CallJavaNode&)n;
1077 return CallNode::cmp(call) && _method == call._method &&
1078 _override_symbolic_info == call._override_symbolic_info;
1079 }
1080
1081 void CallJavaNode::copy_call_debug_info(PhaseIterGVN* phase, SafePointNode* sfpt) {
1082 // Copy debug information and adjust JVMState information
1083 uint old_dbg_start = sfpt->is_Call() ? sfpt->as_Call()->tf()->domain_sig()->cnt() : (uint)TypeFunc::Parms+1;
1084 uint new_dbg_start = tf()->domain_sig()->cnt();
1085 int jvms_adj = new_dbg_start - old_dbg_start;
1086 assert (new_dbg_start == req(), "argument count mismatch");
1087 Compile* C = phase->C;
1088
1089 // SafePointScalarObject node could be referenced several times in debug info.
1090 // Use Dict to record cloned nodes.
1091 Dict* sosn_map = new Dict(cmpkey,hashkey);
1092 for (uint i = old_dbg_start; i < sfpt->req(); i++) {
1093 Node* old_in = sfpt->in(i);
1094 // Clone old SafePointScalarObjectNodes, adjusting their field contents.
1095 if (old_in != nullptr && old_in->is_SafePointScalarObject()) {
1096 SafePointScalarObjectNode* old_sosn = old_in->as_SafePointScalarObject();
1097 bool new_node;
1098 Node* new_in = old_sosn->clone(sosn_map, new_node);
1099 if (new_node) { // New node?
1100 new_in->set_req(0, C->root()); // reset control edge
1101 new_in = phase->transform(new_in); // Register new node.
1102 }
1103 old_in = new_in;
1104 }
1105 add_req(old_in);
1106 }
1107
1108 // JVMS may be shared so clone it before we modify it
1109 set_jvms(sfpt->jvms() != nullptr ? sfpt->jvms()->clone_deep(C) : nullptr);
1110 for (JVMState *jvms = this->jvms(); jvms != nullptr; jvms = jvms->caller()) {
1111 jvms->set_map(this);
1112 jvms->set_locoff(jvms->locoff()+jvms_adj);
1113 jvms->set_stkoff(jvms->stkoff()+jvms_adj);
1114 jvms->set_monoff(jvms->monoff()+jvms_adj);
1115 jvms->set_scloff(jvms->scloff()+jvms_adj);
1116 jvms->set_endoff(jvms->endoff()+jvms_adj);
1117 }
1118 }
1119
1120 #ifdef ASSERT
1121 bool CallJavaNode::validate_symbolic_info() const {
1122 if (method() == nullptr) {
1123 return true; // call into runtime or uncommon trap
1124 }
1125 Bytecodes::Code bc = jvms()->method()->java_code_at_bci(jvms()->bci());
1126 if (EnableValhalla && (bc == Bytecodes::_if_acmpeq || bc == Bytecodes::_if_acmpne)) {
1127 return true;
1128 }
1129 ciMethod* symbolic_info = jvms()->method()->get_method_at_bci(jvms()->bci());
1130 ciMethod* callee = method();
1131 if (symbolic_info->is_method_handle_intrinsic() && !callee->is_method_handle_intrinsic()) {
1132 assert(override_symbolic_info(), "should be set");
1133 }
1134 assert(ciMethod::is_consistent_info(symbolic_info, callee), "inconsistent info");
1135 return true;
1136 }
1137 #endif
1138
1139 #ifndef PRODUCT
1140 void CallJavaNode::dump_spec(outputStream* st) const {
1141 if( _method ) _method->print_short_name(st);
1142 CallNode::dump_spec(st);
1143 }
1144
1145 void CallJavaNode::dump_compact_spec(outputStream* st) const {
1146 if (_method) {
1147 _method->print_short_name(st);
1148 } else {
1149 st->print("<?>");
1150 }
1151 }
1152 #endif
1153
1154 void CallJavaNode::register_for_late_inline() {
1155 if (generator() != nullptr) {
1156 Compile::current()->prepend_late_inline(generator());
1157 set_generator(nullptr);
1158 } else {
1159 assert(false, "repeated inline attempt");
1160 }
1161 }
1162
1163 //=============================================================================
1164 uint CallStaticJavaNode::size_of() const { return sizeof(*this); }
1165 bool CallStaticJavaNode::cmp( const Node &n ) const {
1166 CallStaticJavaNode &call = (CallStaticJavaNode&)n;
1167 return CallJavaNode::cmp(call);
1168 }
1169
1170 Node* CallStaticJavaNode::Ideal(PhaseGVN* phase, bool can_reshape) {
1171 if (can_reshape && uncommon_trap_request() != 0) {
1172 PhaseIterGVN* igvn = phase->is_IterGVN();
1173 if (remove_unknown_flat_array_load(igvn, in(0), in(TypeFunc::Memory), in(TypeFunc::Parms))) {
1174 if (!in(0)->is_Region()) {
1175 igvn->replace_input_of(this, 0, phase->C->top());
1176 }
1177 return this;
1178 }
1179 }
1180
1181 CallGenerator* cg = generator();
1182 if (can_reshape && cg != nullptr) {
1183 if (cg->is_mh_late_inline()) {
1184 assert(IncrementalInlineMH, "required");
1185 assert(cg->call_node() == this, "mismatch");
1186 assert(cg->method()->is_method_handle_intrinsic(), "required");
1187
1188 // Check whether this MH handle call becomes a candidate for inlining.
1189 ciMethod* callee = cg->method();
1190 vmIntrinsics::ID iid = callee->intrinsic_id();
1191 if (iid == vmIntrinsics::_invokeBasic) {
1192 if (in(TypeFunc::Parms)->Opcode() == Op_ConP) {
1193 register_for_late_inline();
1194 }
1195 } else if (iid == vmIntrinsics::_linkToNative) {
1196 // never retry
1197 } else {
1198 assert(callee->has_member_arg(), "wrong type of call?");
1199 if (in(TypeFunc::Parms + callee->arg_size() - 1)->Opcode() == Op_ConP) {
1200 register_for_late_inline();
1201 phase->C->inc_number_of_mh_late_inlines();
1202 }
1203 }
1204 } else {
1205 assert(IncrementalInline, "required");
1206 assert(!cg->method()->is_method_handle_intrinsic(), "required");
1207 if (phase->C->print_inlining()) {
1208 phase->C->inline_printer()->record(cg->method(), cg->call_node()->jvms(), InliningResult::FAILURE,
1209 "static call node changed: trying again");
1210 }
1211 register_for_late_inline();
1212 }
1213 }
1214 return CallNode::Ideal(phase, can_reshape);
1215 }
1216
1217 //----------------------------is_uncommon_trap----------------------------
1218 // Returns true if this is an uncommon trap.
1219 bool CallStaticJavaNode::is_uncommon_trap() const {
1220 return (_name != nullptr && !strcmp(_name, "uncommon_trap"));
1221 }
1222
1223 //----------------------------uncommon_trap_request----------------------------
1224 // If this is an uncommon trap, return the request code, else zero.
1225 int CallStaticJavaNode::uncommon_trap_request() const {
1226 return is_uncommon_trap() ? extract_uncommon_trap_request(this) : 0;
1227 }
1228 int CallStaticJavaNode::extract_uncommon_trap_request(const Node* call) {
1229 #ifndef PRODUCT
1230 if (!(call->req() > TypeFunc::Parms &&
1231 call->in(TypeFunc::Parms) != nullptr &&
1232 call->in(TypeFunc::Parms)->is_Con() &&
1233 call->in(TypeFunc::Parms)->bottom_type()->isa_int())) {
1234 assert(in_dump() != 0, "OK if dumping");
1235 tty->print("[bad uncommon trap]");
1236 return 0;
1237 }
1238 #endif
1239 return call->in(TypeFunc::Parms)->bottom_type()->is_int()->get_con();
1240 }
1241
1242 // Split if can cause the flat array branch of an array load with unknown type (see
1243 // Parse::array_load) to end in an uncommon trap. In that case, the call to
1244 // 'load_unknown_inline' is useless. Replace it with an uncommon trap with the same JVMState.
1245 bool CallStaticJavaNode::remove_unknown_flat_array_load(PhaseIterGVN* igvn, Node* ctl, Node* mem, Node* unc_arg) {
1246 if (ctl == nullptr || ctl->is_top() || mem == nullptr || mem->is_top() || !mem->is_MergeMem()) {
1247 return false;
1248 }
1249 if (ctl->is_Region()) {
1250 bool res = false;
1251 for (uint i = 1; i < ctl->req(); i++) {
1252 MergeMemNode* mm = mem->clone()->as_MergeMem();
1253 for (MergeMemStream mms(mm); mms.next_non_empty(); ) {
1254 Node* m = mms.memory();
1255 if (m->is_Phi() && m->in(0) == ctl) {
1256 mms.set_memory(m->in(i));
1257 }
1258 }
1259 if (remove_unknown_flat_array_load(igvn, ctl->in(i), mm, unc_arg)) {
1260 res = true;
1261 if (!ctl->in(i)->is_Region()) {
1262 igvn->replace_input_of(ctl, i, igvn->C->top());
1263 }
1264 }
1265 igvn->remove_dead_node(mm);
1266 }
1267 return res;
1268 }
1269 // Verify the control flow is ok
1270 Node* call = ctl;
1271 MemBarNode* membar = nullptr;
1272 for (;;) {
1273 if (call == nullptr || call->is_top()) {
1274 return false;
1275 }
1276 if (call->is_Proj() || call->is_Catch() || call->is_MemBar()) {
1277 call = call->in(0);
1278 } else if (call->Opcode() == Op_CallStaticJava && !call->in(0)->is_top() &&
1279 call->as_Call()->entry_point() == OptoRuntime::load_unknown_inline_Java()) {
1280 assert(call->in(0)->is_Proj() && call->in(0)->in(0)->is_MemBar(), "missing membar");
1281 membar = call->in(0)->in(0)->as_MemBar();
1282 break;
1283 } else {
1284 return false;
1285 }
1286 }
1287
1288 JVMState* jvms = call->jvms();
1289 if (igvn->C->too_many_traps(jvms->method(), jvms->bci(), Deoptimization::trap_request_reason(uncommon_trap_request()))) {
1290 return false;
1291 }
1292
1293 Node* call_mem = call->in(TypeFunc::Memory);
1294 if (call_mem == nullptr || call_mem->is_top()) {
1295 return false;
1296 }
1297 if (!call_mem->is_MergeMem()) {
1298 call_mem = MergeMemNode::make(call_mem);
1299 igvn->register_new_node_with_optimizer(call_mem);
1300 }
1301
1302 // Verify that there's no unexpected side effect
1303 for (MergeMemStream mms2(mem->as_MergeMem(), call_mem->as_MergeMem()); mms2.next_non_empty2(); ) {
1304 Node* m1 = mms2.is_empty() ? mms2.base_memory() : mms2.memory();
1305 Node* m2 = mms2.memory2();
1306
1307 for (uint i = 0; i < 100; i++) {
1308 if (m1 == m2) {
1309 break;
1310 } else if (m1->is_Proj()) {
1311 m1 = m1->in(0);
1312 } else if (m1->is_MemBar()) {
1313 m1 = m1->in(TypeFunc::Memory);
1314 } else if (m1->Opcode() == Op_CallStaticJava &&
1315 m1->as_Call()->entry_point() == OptoRuntime::load_unknown_inline_Java()) {
1316 if (m1 != call) {
1317 return false;
1318 }
1319 break;
1320 } else if (m1->is_MergeMem()) {
1321 MergeMemNode* mm = m1->as_MergeMem();
1322 int idx = mms2.alias_idx();
1323 if (idx == Compile::AliasIdxBot) {
1324 m1 = mm->base_memory();
1325 } else {
1326 m1 = mm->memory_at(idx);
1327 }
1328 } else {
1329 return false;
1330 }
1331 }
1332 }
1333 if (call_mem->outcnt() == 0) {
1334 igvn->remove_dead_node(call_mem);
1335 }
1336
1337 // Remove membar preceding the call
1338 membar->remove(igvn);
1339
1340 address call_addr = OptoRuntime::uncommon_trap_blob()->entry_point();
1341 CallNode* unc = new CallStaticJavaNode(OptoRuntime::uncommon_trap_Type(), call_addr, "uncommon_trap", nullptr);
1342 unc->init_req(TypeFunc::Control, call->in(0));
1343 unc->init_req(TypeFunc::I_O, call->in(TypeFunc::I_O));
1344 unc->init_req(TypeFunc::Memory, call->in(TypeFunc::Memory));
1345 unc->init_req(TypeFunc::FramePtr, call->in(TypeFunc::FramePtr));
1346 unc->init_req(TypeFunc::ReturnAdr, call->in(TypeFunc::ReturnAdr));
1347 unc->init_req(TypeFunc::Parms+0, unc_arg);
1348 unc->set_cnt(PROB_UNLIKELY_MAG(4));
1349 unc->copy_call_debug_info(igvn, call->as_CallStaticJava());
1350
1351 // Replace the call with an uncommon trap
1352 igvn->replace_input_of(call, 0, igvn->C->top());
1353
1354 igvn->register_new_node_with_optimizer(unc);
1355
1356 Node* ctrl = igvn->transform(new ProjNode(unc, TypeFunc::Control));
1357 Node* halt = igvn->transform(new HaltNode(ctrl, call->in(TypeFunc::FramePtr), "uncommon trap returned which should never happen"));
1358 igvn->add_input_to(igvn->C->root(), halt);
1359
1360 return true;
1361 }
1362
1363
1364 #ifndef PRODUCT
1365 void CallStaticJavaNode::dump_spec(outputStream *st) const {
1366 st->print("# Static ");
1367 if (_name != nullptr) {
1368 st->print("%s", _name);
1369 int trap_req = uncommon_trap_request();
1370 if (trap_req != 0) {
1371 char buf[100];
1372 st->print("(%s)",
1373 Deoptimization::format_trap_request(buf, sizeof(buf),
1374 trap_req));
1375 }
1376 st->print(" ");
1377 }
1378 CallJavaNode::dump_spec(st);
1379 }
1380
1381 void CallStaticJavaNode::dump_compact_spec(outputStream* st) const {
1382 if (_method) {
1383 _method->print_short_name(st);
1384 } else if (_name) {
1385 st->print("%s", _name);
1386 } else {
1387 st->print("<?>");
1388 }
1389 }
1390 #endif
1391
1392 //=============================================================================
1393 uint CallDynamicJavaNode::size_of() const { return sizeof(*this); }
1394 bool CallDynamicJavaNode::cmp( const Node &n ) const {
1395 CallDynamicJavaNode &call = (CallDynamicJavaNode&)n;
1396 return CallJavaNode::cmp(call);
1397 }
1398
1399 Node* CallDynamicJavaNode::Ideal(PhaseGVN* phase, bool can_reshape) {
1400 CallGenerator* cg = generator();
1401 if (can_reshape && cg != nullptr) {
1402 if (cg->is_virtual_late_inline()) {
1403 assert(IncrementalInlineVirtual, "required");
1404 assert(cg->call_node() == this, "mismatch");
1405
1406 if (cg->callee_method() == nullptr) {
1407 // Recover symbolic info for method resolution.
1408 ciMethod* caller = jvms()->method();
1409 ciBytecodeStream iter(caller);
1410 iter.force_bci(jvms()->bci());
1411
1412 bool not_used1;
1413 ciSignature* not_used2;
1414 ciMethod* orig_callee = iter.get_method(not_used1, ¬_used2); // callee in the bytecode
1415 ciKlass* holder = iter.get_declared_method_holder();
1416 if (orig_callee->is_method_handle_intrinsic()) {
1417 assert(_override_symbolic_info, "required");
1418 orig_callee = method();
1419 holder = method()->holder();
1420 }
1421
1422 ciInstanceKlass* klass = ciEnv::get_instance_klass_for_declared_method_holder(holder);
1423
1424 Node* receiver_node = in(TypeFunc::Parms);
1425 const TypeOopPtr* receiver_type = phase->type(receiver_node)->isa_oopptr();
1426
1427 int not_used3;
1428 bool call_does_dispatch;
1429 ciMethod* callee = phase->C->optimize_virtual_call(caller, klass, holder, orig_callee, receiver_type, true /*is_virtual*/,
1430 call_does_dispatch, not_used3); // out-parameters
1431 if (!call_does_dispatch) {
1432 cg->set_callee_method(callee);
1433 }
1434 }
1435 if (cg->callee_method() != nullptr) {
1436 // Register for late inlining.
1437 register_for_late_inline(); // MH late inlining prepends to the list, so do the same
1438 }
1439 } else {
1440 assert(IncrementalInline, "required");
1441 if (phase->C->print_inlining()) {
1442 phase->C->inline_printer()->record(cg->method(), cg->call_node()->jvms(), InliningResult::FAILURE,
1443 "dynamic call node changed: trying again");
1444 }
1445 register_for_late_inline();
1446 }
1447 }
1448 return CallNode::Ideal(phase, can_reshape);
1449 }
1450
1451 #ifndef PRODUCT
1452 void CallDynamicJavaNode::dump_spec(outputStream *st) const {
1453 st->print("# Dynamic ");
1454 CallJavaNode::dump_spec(st);
1455 }
1456 #endif
1457
1458 //=============================================================================
1459 uint CallRuntimeNode::size_of() const { return sizeof(*this); }
1460 bool CallRuntimeNode::cmp( const Node &n ) const {
1461 CallRuntimeNode &call = (CallRuntimeNode&)n;
1462 return CallNode::cmp(call) && !strcmp(_name,call._name);
1463 }
1464 #ifndef PRODUCT
1465 void CallRuntimeNode::dump_spec(outputStream *st) const {
1466 st->print("# ");
1467 st->print("%s", _name);
1468 CallNode::dump_spec(st);
1469 }
1470 #endif
1471 uint CallLeafVectorNode::size_of() const { return sizeof(*this); }
1472 bool CallLeafVectorNode::cmp( const Node &n ) const {
1473 CallLeafVectorNode &call = (CallLeafVectorNode&)n;
1474 return CallLeafNode::cmp(call) && _num_bits == call._num_bits;
1475 }
1476
1477 //------------------------------calling_convention-----------------------------
1478 void CallRuntimeNode::calling_convention(BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt) const {
1479 if (_entry_point == nullptr) {
1480 // The call to that stub is a special case: its inputs are
1481 // multiple values returned from a call and so it should follow
1482 // the return convention.
1483 SharedRuntime::java_return_convention(sig_bt, parm_regs, argcnt);
1484 return;
1485 }
1486 SharedRuntime::c_calling_convention(sig_bt, parm_regs, argcnt);
1487 }
1488
1489 void CallLeafVectorNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
1490 #ifdef ASSERT
1491 assert(tf()->range_sig()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte == _num_bits,
1492 "return vector size must match");
1493 const TypeTuple* d = tf()->domain_sig();
1494 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1495 Node* arg = in(i);
1496 assert(arg->bottom_type()->is_vect()->length_in_bytes() * BitsPerByte == _num_bits,
1497 "vector argument size must match");
1498 }
1499 #endif
1500
1501 SharedRuntime::vector_calling_convention(parm_regs, _num_bits, argcnt);
1502 }
1503
1504 //=============================================================================
1505 //------------------------------calling_convention-----------------------------
1506
1507
1508 //=============================================================================
1509 bool CallLeafPureNode::is_unused() const {
1510 return proj_out_or_null(TypeFunc::Parms) == nullptr;
1511 }
1512
1513 bool CallLeafPureNode::is_dead() const {
1514 return proj_out_or_null(TypeFunc::Control) == nullptr;
1515 }
1516
1517 /* We make a tuple of the global input state + TOP for the output values.
1518 * We use this to delete a pure function that is not used: by replacing the call with
1519 * such a tuple, we let output Proj's idealization pick the corresponding input of the
1520 * pure call, so jumping over it, and effectively, removing the call from the graph.
1521 * This avoids doing the graph surgery manually, but leaves that to IGVN
1522 * that is specialized for doing that right. We need also tuple components for output
1523 * values of the function to respect the return arity, and in case there is a projection
1524 * that would pick an output (which shouldn't happen at the moment).
1525 */
1526 TupleNode* CallLeafPureNode::make_tuple_of_input_state_and_top_return_values(const Compile* C) const {
1527 // Transparently propagate input state but parameters
1528 TupleNode* tuple = TupleNode::make(
1529 tf()->range_cc(),
1530 in(TypeFunc::Control),
1531 in(TypeFunc::I_O),
1532 in(TypeFunc::Memory),
1533 in(TypeFunc::FramePtr),
1534 in(TypeFunc::ReturnAdr));
1535
1536 // And add TOPs for the return values
1537 for (uint i = TypeFunc::Parms; i < tf()->range_cc()->cnt(); i++) {
1538 tuple->set_req(i, C->top());
1539 }
1540
1541 return tuple;
1542 }
1543
1544 Node* CallLeafPureNode::Ideal(PhaseGVN* phase, bool can_reshape) {
1545 if (is_dead()) {
1546 return nullptr;
1547 }
1548
1549 // We need to wait until IGVN because during parsing, usages might still be missing
1550 // and we would remove the call immediately.
1551 if (can_reshape && is_unused()) {
1552 // The result is not used. We remove the call by replacing it with a tuple, that
1553 // is later disintegrated by the projections.
1554 return make_tuple_of_input_state_and_top_return_values(phase->C);
1555 }
1556
1557 return CallRuntimeNode::Ideal(phase, can_reshape);
1558 }
1559
1560 #ifndef PRODUCT
1561 void CallLeafNode::dump_spec(outputStream *st) const {
1562 st->print("# ");
1563 st->print("%s", _name);
1564 CallNode::dump_spec(st);
1565 }
1566 #endif
1567
1568 uint CallLeafNoFPNode::match_edge(uint idx) const {
1569 // Null entry point is a special case for which the target is in a
1570 // register. Need to match that edge.
1571 return entry_point() == nullptr && idx == TypeFunc::Parms;
1572 }
1573
1574 //=============================================================================
1575
1576 void SafePointNode::set_local(const JVMState* jvms, uint idx, Node *c) {
1577 assert(verify_jvms(jvms), "jvms must match");
1578 int loc = jvms->locoff() + idx;
1579 if (in(loc)->is_top() && idx > 0 && !c->is_top() ) {
1580 // If current local idx is top then local idx - 1 could
1581 // be a long/double that needs to be killed since top could
1582 // represent the 2nd half of the long/double.
1583 uint ideal = in(loc -1)->ideal_reg();
1584 if (ideal == Op_RegD || ideal == Op_RegL) {
1585 // set other (low index) half to top
1586 set_req(loc - 1, in(loc));
1587 }
1588 }
1589 set_req(loc, c);
1590 }
1591
1592 uint SafePointNode::size_of() const { return sizeof(*this); }
1593 bool SafePointNode::cmp( const Node &n ) const {
1594 return (&n == this); // Always fail except on self
1595 }
1596
1597 //-------------------------set_next_exception----------------------------------
1598 void SafePointNode::set_next_exception(SafePointNode* n) {
1599 assert(n == nullptr || n->Opcode() == Op_SafePoint, "correct value for next_exception");
1600 if (len() == req()) {
1601 if (n != nullptr) add_prec(n);
1602 } else {
1603 set_prec(req(), n);
1604 }
1605 }
1606
1607
1608 //----------------------------next_exception-----------------------------------
1609 SafePointNode* SafePointNode::next_exception() const {
1610 if (len() == req()) {
1611 return nullptr;
1612 } else {
1613 Node* n = in(req());
1614 assert(n == nullptr || n->Opcode() == Op_SafePoint, "no other uses of prec edges");
1615 return (SafePointNode*) n;
1616 }
1617 }
1618
1619
1620 //------------------------------Ideal------------------------------------------
1621 // Skip over any collapsed Regions
1622 Node *SafePointNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1623 assert(_jvms == nullptr || ((uintptr_t)_jvms->map() & 1) || _jvms->map() == this, "inconsistent JVMState");
1624 if (remove_dead_region(phase, can_reshape)) {
1625 return this;
1626 }
1627 // Scalarize inline types in safepoint debug info.
1628 // Delay this until all inlining is over to avoid getting inconsistent debug info.
1629 if (phase->C->scalarize_in_safepoints() && can_reshape && jvms() != nullptr) {
1630 for (uint i = jvms()->debug_start(); i < jvms()->debug_end(); i++) {
1631 Node* n = in(i)->uncast();
1632 if (n->is_InlineType()) {
1633 n->as_InlineType()->make_scalar_in_safepoints(phase->is_IterGVN());
1634 }
1635 }
1636 }
1637 return nullptr;
1638 }
1639
1640 //------------------------------Identity---------------------------------------
1641 // Remove obviously duplicate safepoints
1642 Node* SafePointNode::Identity(PhaseGVN* phase) {
1643
1644 // If you have back to back safepoints, remove one
1645 if (in(TypeFunc::Control)->is_SafePoint()) {
1646 Node* out_c = unique_ctrl_out_or_null();
1647 // This can be the safepoint of an outer strip mined loop if the inner loop's backedge was removed. Replacing the
1648 // outer loop's safepoint could confuse removal of the outer loop.
1649 if (out_c != nullptr && !out_c->is_OuterStripMinedLoopEnd()) {
1650 return in(TypeFunc::Control);
1651 }
1652 }
1653
1654 // Transforming long counted loops requires a safepoint node. Do not
1655 // eliminate a safepoint until loop opts are over.
1656 if (in(0)->is_Proj() && !phase->C->major_progress()) {
1657 Node *n0 = in(0)->in(0);
1658 // Check if he is a call projection (except Leaf Call)
1659 if( n0->is_Catch() ) {
1660 n0 = n0->in(0)->in(0);
1661 assert( n0->is_Call(), "expect a call here" );
1662 }
1663 if( n0->is_Call() && n0->as_Call()->guaranteed_safepoint() ) {
1664 // Don't remove a safepoint belonging to an OuterStripMinedLoopEndNode.
1665 // If the loop dies, they will be removed together.
1666 if (has_out_with(Op_OuterStripMinedLoopEnd)) {
1667 return this;
1668 }
1669 // Useless Safepoint, so remove it
1670 return in(TypeFunc::Control);
1671 }
1672 }
1673
1674 return this;
1675 }
1676
1677 //------------------------------Value------------------------------------------
1678 const Type* SafePointNode::Value(PhaseGVN* phase) const {
1679 if (phase->type(in(0)) == Type::TOP) {
1680 return Type::TOP;
1681 }
1682 if (in(0) == this) {
1683 return Type::TOP; // Dead infinite loop
1684 }
1685 return Type::CONTROL;
1686 }
1687
1688 #ifndef PRODUCT
1689 void SafePointNode::dump_spec(outputStream *st) const {
1690 st->print(" SafePoint ");
1691 _replaced_nodes.dump(st);
1692 }
1693 #endif
1694
1695 const RegMask &SafePointNode::in_RegMask(uint idx) const {
1696 if( idx < TypeFunc::Parms ) return RegMask::Empty;
1697 // Values outside the domain represent debug info
1698 return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1699 }
1700 const RegMask &SafePointNode::out_RegMask() const {
1701 return RegMask::Empty;
1702 }
1703
1704
1705 void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) {
1706 assert((int)grow_by > 0, "sanity");
1707 int monoff = jvms->monoff();
1708 int scloff = jvms->scloff();
1709 int endoff = jvms->endoff();
1710 assert(endoff == (int)req(), "no other states or debug info after me");
1711 Node* top = Compile::current()->top();
1712 for (uint i = 0; i < grow_by; i++) {
1713 ins_req(monoff, top);
1714 }
1715 jvms->set_monoff(monoff + grow_by);
1716 jvms->set_scloff(scloff + grow_by);
1717 jvms->set_endoff(endoff + grow_by);
1718 }
1719
1720 void SafePointNode::push_monitor(const FastLockNode *lock) {
1721 // Add a LockNode, which points to both the original BoxLockNode (the
1722 // stack space for the monitor) and the Object being locked.
1723 const int MonitorEdges = 2;
1724 assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1725 assert(req() == jvms()->endoff(), "correct sizing");
1726 int nextmon = jvms()->scloff();
1727 ins_req(nextmon, lock->box_node());
1728 ins_req(nextmon+1, lock->obj_node());
1729 jvms()->set_scloff(nextmon + MonitorEdges);
1730 jvms()->set_endoff(req());
1731 }
1732
1733 void SafePointNode::pop_monitor() {
1734 // Delete last monitor from debug info
1735 DEBUG_ONLY(int num_before_pop = jvms()->nof_monitors());
1736 const int MonitorEdges = 2;
1737 assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1738 int scloff = jvms()->scloff();
1739 int endoff = jvms()->endoff();
1740 int new_scloff = scloff - MonitorEdges;
1741 int new_endoff = endoff - MonitorEdges;
1742 jvms()->set_scloff(new_scloff);
1743 jvms()->set_endoff(new_endoff);
1744 while (scloff > new_scloff) del_req_ordered(--scloff);
1745 assert(jvms()->nof_monitors() == num_before_pop-1, "");
1746 }
1747
1748 Node *SafePointNode::peek_monitor_box() const {
1749 int mon = jvms()->nof_monitors() - 1;
1750 assert(mon >= 0, "must have a monitor");
1751 return monitor_box(jvms(), mon);
1752 }
1753
1754 Node *SafePointNode::peek_monitor_obj() const {
1755 int mon = jvms()->nof_monitors() - 1;
1756 assert(mon >= 0, "must have a monitor");
1757 return monitor_obj(jvms(), mon);
1758 }
1759
1760 Node* SafePointNode::peek_operand(uint off) const {
1761 assert(jvms()->sp() > 0, "must have an operand");
1762 assert(off < jvms()->sp(), "off is out-of-range");
1763 return stack(jvms(), jvms()->sp() - off - 1);
1764 }
1765
1766 // Do we Match on this edge index or not? Match no edges
1767 uint SafePointNode::match_edge(uint idx) const {
1768 return (TypeFunc::Parms == idx);
1769 }
1770
1771 void SafePointNode::disconnect_from_root(PhaseIterGVN *igvn) {
1772 assert(Opcode() == Op_SafePoint, "only value for safepoint in loops");
1773 int nb = igvn->C->root()->find_prec_edge(this);
1774 if (nb != -1) {
1775 igvn->delete_precedence_of(igvn->C->root(), nb);
1776 }
1777 }
1778
1779 //============== SafePointScalarObjectNode ==============
1780
1781 SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp, Node* alloc, uint first_index, uint depth, uint n_fields) :
1782 TypeNode(tp, 1), // 1 control input -- seems required. Get from root.
1783 _first_index(first_index),
1784 _depth(depth),
1785 _n_fields(n_fields),
1786 _alloc(alloc)
1787 {
1788 #ifdef ASSERT
1789 if (alloc != nullptr && !alloc->is_Allocate() && !(alloc->Opcode() == Op_VectorBox)) {
1790 alloc->dump();
1791 assert(false, "unexpected call node");
1792 }
1793 #endif
1794 init_class_id(Class_SafePointScalarObject);
1795 }
1796
1797 // Do not allow value-numbering for SafePointScalarObject node.
1798 uint SafePointScalarObjectNode::hash() const { return NO_HASH; }
1799 bool SafePointScalarObjectNode::cmp( const Node &n ) const {
1800 return (&n == this); // Always fail except on self
1801 }
1802
1803 uint SafePointScalarObjectNode::ideal_reg() const {
1804 return 0; // No matching to machine instruction
1805 }
1806
1807 const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const {
1808 return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1809 }
1810
1811 const RegMask &SafePointScalarObjectNode::out_RegMask() const {
1812 return RegMask::Empty;
1813 }
1814
1815 uint SafePointScalarObjectNode::match_edge(uint idx) const {
1816 return 0;
1817 }
1818
1819 SafePointScalarObjectNode*
1820 SafePointScalarObjectNode::clone(Dict* sosn_map, bool& new_node) const {
1821 void* cached = (*sosn_map)[(void*)this];
1822 if (cached != nullptr) {
1823 new_node = false;
1824 return (SafePointScalarObjectNode*)cached;
1825 }
1826 new_node = true;
1827 SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone();
1828 sosn_map->Insert((void*)this, (void*)res);
1829 return res;
1830 }
1831
1832
1833 #ifndef PRODUCT
1834 void SafePointScalarObjectNode::dump_spec(outputStream *st) const {
1835 st->print(" # fields@[%d..%d]", first_index(), first_index() + n_fields() - 1);
1836 }
1837 #endif
1838
1839 //============== SafePointScalarMergeNode ==============
1840
1841 SafePointScalarMergeNode::SafePointScalarMergeNode(const TypeOopPtr* tp, int merge_pointer_idx) :
1842 TypeNode(tp, 1), // 1 control input -- seems required. Get from root.
1843 _merge_pointer_idx(merge_pointer_idx)
1844 {
1845 init_class_id(Class_SafePointScalarMerge);
1846 }
1847
1848 // Do not allow value-numbering for SafePointScalarMerge node.
1849 uint SafePointScalarMergeNode::hash() const { return NO_HASH; }
1850 bool SafePointScalarMergeNode::cmp( const Node &n ) const {
1851 return (&n == this); // Always fail except on self
1852 }
1853
1854 uint SafePointScalarMergeNode::ideal_reg() const {
1855 return 0; // No matching to machine instruction
1856 }
1857
1858 const RegMask &SafePointScalarMergeNode::in_RegMask(uint idx) const {
1859 return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1860 }
1861
1862 const RegMask &SafePointScalarMergeNode::out_RegMask() const {
1863 return RegMask::Empty;
1864 }
1865
1866 uint SafePointScalarMergeNode::match_edge(uint idx) const {
1867 return 0;
1868 }
1869
1870 SafePointScalarMergeNode*
1871 SafePointScalarMergeNode::clone(Dict* sosn_map, bool& new_node) const {
1872 void* cached = (*sosn_map)[(void*)this];
1873 if (cached != nullptr) {
1874 new_node = false;
1875 return (SafePointScalarMergeNode*)cached;
1876 }
1877 new_node = true;
1878 SafePointScalarMergeNode* res = (SafePointScalarMergeNode*)Node::clone();
1879 sosn_map->Insert((void*)this, (void*)res);
1880 return res;
1881 }
1882
1883 #ifndef PRODUCT
1884 void SafePointScalarMergeNode::dump_spec(outputStream *st) const {
1885 st->print(" # merge_pointer_idx=%d, scalarized_objects=%d", _merge_pointer_idx, req()-1);
1886 }
1887 #endif
1888
1889 //=============================================================================
1890 uint AllocateNode::size_of() const { return sizeof(*this); }
1891
1892 AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype,
1893 Node *ctrl, Node *mem, Node *abio,
1894 Node *size, Node *klass_node,
1895 Node* initial_test,
1896 InlineTypeNode* inline_type_node)
1897 : CallNode(atype, nullptr, TypeRawPtr::BOTTOM)
1898 {
1899 init_class_id(Class_Allocate);
1900 init_flags(Flag_is_macro);
1901 _is_scalar_replaceable = false;
1902 _is_non_escaping = false;
1903 _is_allocation_MemBar_redundant = false;
1904 _larval = false;
1905 Node *topnode = C->top();
1906
1907 init_req( TypeFunc::Control , ctrl );
1908 init_req( TypeFunc::I_O , abio );
1909 init_req( TypeFunc::Memory , mem );
1910 init_req( TypeFunc::ReturnAdr, topnode );
1911 init_req( TypeFunc::FramePtr , topnode );
1912 init_req( AllocSize , size);
1913 init_req( KlassNode , klass_node);
1914 init_req( InitialTest , initial_test);
1915 init_req( ALength , topnode);
1916 init_req( ValidLengthTest , topnode);
1917 init_req( InlineType , inline_type_node);
1918 // DefaultValue defaults to nullptr
1919 // RawDefaultValue defaults to nullptr
1920 C->add_macro_node(this);
1921 }
1922
1923 void AllocateNode::compute_MemBar_redundancy(ciMethod* initializer)
1924 {
1925 assert(initializer != nullptr &&
1926 (initializer->is_object_constructor() || initializer->is_class_initializer()),
1927 "unexpected initializer method");
1928 BCEscapeAnalyzer* analyzer = initializer->get_bcea();
1929 if (analyzer == nullptr) {
1930 return;
1931 }
1932
1933 // Allocation node is first parameter in its initializer
1934 if (analyzer->is_arg_stack(0) || analyzer->is_arg_local(0)) {
1935 _is_allocation_MemBar_redundant = true;
1936 }
1937 }
1938
1939 Node* AllocateNode::make_ideal_mark(PhaseGVN* phase, Node* control, Node* mem) {
1940 Node* mark_node = nullptr;
1941 if (UseCompactObjectHeaders || EnableValhalla) {
1942 Node* klass_node = in(AllocateNode::KlassNode);
1943 Node* proto_adr = phase->transform(new AddPNode(klass_node, klass_node, phase->MakeConX(in_bytes(Klass::prototype_header_offset()))));
1944 mark_node = LoadNode::make(*phase, control, mem, proto_adr, TypeRawPtr::BOTTOM, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
1945 if (EnableValhalla) {
1946 mark_node = phase->transform(mark_node);
1947 // Avoid returning a constant (old node) here because this method is used by LoadNode::Ideal
1948 mark_node = new OrXNode(mark_node, phase->MakeConX(_larval ? markWord::larval_bit_in_place : 0));
1949 }
1950 return mark_node;
1951 } else {
1952 return phase->MakeConX(markWord::prototype().value());
1953 }
1954 }
1955
1956 // Retrieve the length from the AllocateArrayNode. Narrow the type with a
1957 // CastII, if appropriate. If we are not allowed to create new nodes, and
1958 // a CastII is appropriate, return null.
1959 Node *AllocateArrayNode::make_ideal_length(const TypeOopPtr* oop_type, PhaseValues* phase, bool allow_new_nodes) {
1960 Node *length = in(AllocateNode::ALength);
1961 assert(length != nullptr, "length is not null");
1962
1963 const TypeInt* length_type = phase->find_int_type(length);
1964 const TypeAryPtr* ary_type = oop_type->isa_aryptr();
1965
1966 if (ary_type != nullptr && length_type != nullptr) {
1967 const TypeInt* narrow_length_type = ary_type->narrow_size_type(length_type);
1968 if (narrow_length_type != length_type) {
1969 // Assert one of:
1970 // - the narrow_length is 0
1971 // - the narrow_length is not wider than length
1972 assert(narrow_length_type == TypeInt::ZERO ||
1973 (length_type->is_con() && narrow_length_type->is_con() &&
1974 (narrow_length_type->_hi <= length_type->_lo)) ||
1975 (narrow_length_type->_hi <= length_type->_hi &&
1976 narrow_length_type->_lo >= length_type->_lo),
1977 "narrow type must be narrower than length type");
1978
1979 // Return null if new nodes are not allowed
1980 if (!allow_new_nodes) {
1981 return nullptr;
1982 }
1983 // Create a cast which is control dependent on the initialization to
1984 // propagate the fact that the array length must be positive.
1985 InitializeNode* init = initialization();
1986 if (init != nullptr) {
1987 length = new CastIINode(init->proj_out_or_null(TypeFunc::Control), length, narrow_length_type);
1988 }
1989 }
1990 }
1991
1992 return length;
1993 }
1994
1995 //=============================================================================
1996 const TypeFunc* LockNode::_lock_type_Type = nullptr;
1997
1998 uint LockNode::size_of() const { return sizeof(*this); }
1999
2000 // Redundant lock elimination
2001 //
2002 // There are various patterns of locking where we release and
2003 // immediately reacquire a lock in a piece of code where no operations
2004 // occur in between that would be observable. In those cases we can
2005 // skip releasing and reacquiring the lock without violating any
2006 // fairness requirements. Doing this around a loop could cause a lock
2007 // to be held for a very long time so we concentrate on non-looping
2008 // control flow. We also require that the operations are fully
2009 // redundant meaning that we don't introduce new lock operations on
2010 // some paths so to be able to eliminate it on others ala PRE. This
2011 // would probably require some more extensive graph manipulation to
2012 // guarantee that the memory edges were all handled correctly.
2013 //
2014 // Assuming p is a simple predicate which can't trap in any way and s
2015 // is a synchronized method consider this code:
2016 //
2017 // s();
2018 // if (p)
2019 // s();
2020 // else
2021 // s();
2022 // s();
2023 //
2024 // 1. The unlocks of the first call to s can be eliminated if the
2025 // locks inside the then and else branches are eliminated.
2026 //
2027 // 2. The unlocks of the then and else branches can be eliminated if
2028 // the lock of the final call to s is eliminated.
2029 //
2030 // Either of these cases subsumes the simple case of sequential control flow
2031 //
2032 // Additionally we can eliminate versions without the else case:
2033 //
2034 // s();
2035 // if (p)
2036 // s();
2037 // s();
2038 //
2039 // 3. In this case we eliminate the unlock of the first s, the lock
2040 // and unlock in the then case and the lock in the final s.
2041 //
2042 // Note also that in all these cases the then/else pieces don't have
2043 // to be trivial as long as they begin and end with synchronization
2044 // operations.
2045 //
2046 // s();
2047 // if (p)
2048 // s();
2049 // f();
2050 // s();
2051 // s();
2052 //
2053 // The code will work properly for this case, leaving in the unlock
2054 // before the call to f and the relock after it.
2055 //
2056 // A potentially interesting case which isn't handled here is when the
2057 // locking is partially redundant.
2058 //
2059 // s();
2060 // if (p)
2061 // s();
2062 //
2063 // This could be eliminated putting unlocking on the else case and
2064 // eliminating the first unlock and the lock in the then side.
2065 // Alternatively the unlock could be moved out of the then side so it
2066 // was after the merge and the first unlock and second lock
2067 // eliminated. This might require less manipulation of the memory
2068 // state to get correct.
2069 //
2070 // Additionally we might allow work between a unlock and lock before
2071 // giving up eliminating the locks. The current code disallows any
2072 // conditional control flow between these operations. A formulation
2073 // similar to partial redundancy elimination computing the
2074 // availability of unlocking and the anticipatability of locking at a
2075 // program point would allow detection of fully redundant locking with
2076 // some amount of work in between. I'm not sure how often I really
2077 // think that would occur though. Most of the cases I've seen
2078 // indicate it's likely non-trivial work would occur in between.
2079 // There may be other more complicated constructs where we could
2080 // eliminate locking but I haven't seen any others appear as hot or
2081 // interesting.
2082 //
2083 // Locking and unlocking have a canonical form in ideal that looks
2084 // roughly like this:
2085 //
2086 // <obj>
2087 // | \\------+
2088 // | \ \
2089 // | BoxLock \
2090 // | | | \
2091 // | | \ \
2092 // | | FastLock
2093 // | | /
2094 // | | /
2095 // | | |
2096 //
2097 // Lock
2098 // |
2099 // Proj #0
2100 // |
2101 // MembarAcquire
2102 // |
2103 // Proj #0
2104 //
2105 // MembarRelease
2106 // |
2107 // Proj #0
2108 // |
2109 // Unlock
2110 // |
2111 // Proj #0
2112 //
2113 //
2114 // This code proceeds by processing Lock nodes during PhaseIterGVN
2115 // and searching back through its control for the proper code
2116 // patterns. Once it finds a set of lock and unlock operations to
2117 // eliminate they are marked as eliminatable which causes the
2118 // expansion of the Lock and Unlock macro nodes to make the operation a NOP
2119 //
2120 //=============================================================================
2121
2122 //
2123 // Utility function to skip over uninteresting control nodes. Nodes skipped are:
2124 // - copy regions. (These may not have been optimized away yet.)
2125 // - eliminated locking nodes
2126 //
2127 static Node *next_control(Node *ctrl) {
2128 if (ctrl == nullptr)
2129 return nullptr;
2130 while (1) {
2131 if (ctrl->is_Region()) {
2132 RegionNode *r = ctrl->as_Region();
2133 Node *n = r->is_copy();
2134 if (n == nullptr)
2135 break; // hit a region, return it
2136 else
2137 ctrl = n;
2138 } else if (ctrl->is_Proj()) {
2139 Node *in0 = ctrl->in(0);
2140 if (in0->is_AbstractLock() && in0->as_AbstractLock()->is_eliminated()) {
2141 ctrl = in0->in(0);
2142 } else {
2143 break;
2144 }
2145 } else {
2146 break; // found an interesting control
2147 }
2148 }
2149 return ctrl;
2150 }
2151 //
2152 // Given a control, see if it's the control projection of an Unlock which
2153 // operating on the same object as lock.
2154 //
2155 bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock,
2156 GrowableArray<AbstractLockNode*> &lock_ops) {
2157 ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : nullptr;
2158 if (ctrl_proj != nullptr && ctrl_proj->_con == TypeFunc::Control) {
2159 Node *n = ctrl_proj->in(0);
2160 if (n != nullptr && n->is_Unlock()) {
2161 UnlockNode *unlock = n->as_Unlock();
2162 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2163 Node* lock_obj = bs->step_over_gc_barrier(lock->obj_node());
2164 Node* unlock_obj = bs->step_over_gc_barrier(unlock->obj_node());
2165 if (lock_obj->eqv_uncast(unlock_obj) &&
2166 BoxLockNode::same_slot(lock->box_node(), unlock->box_node()) &&
2167 !unlock->is_eliminated()) {
2168 lock_ops.append(unlock);
2169 return true;
2170 }
2171 }
2172 }
2173 return false;
2174 }
2175
2176 //
2177 // Find the lock matching an unlock. Returns null if a safepoint
2178 // or complicated control is encountered first.
2179 LockNode *AbstractLockNode::find_matching_lock(UnlockNode* unlock) {
2180 LockNode *lock_result = nullptr;
2181 // find the matching lock, or an intervening safepoint
2182 Node *ctrl = next_control(unlock->in(0));
2183 while (1) {
2184 assert(ctrl != nullptr, "invalid control graph");
2185 assert(!ctrl->is_Start(), "missing lock for unlock");
2186 if (ctrl->is_top()) break; // dead control path
2187 if (ctrl->is_Proj()) ctrl = ctrl->in(0);
2188 if (ctrl->is_SafePoint()) {
2189 break; // found a safepoint (may be the lock we are searching for)
2190 } else if (ctrl->is_Region()) {
2191 // Check for a simple diamond pattern. Punt on anything more complicated
2192 if (ctrl->req() == 3 && ctrl->in(1) != nullptr && ctrl->in(2) != nullptr) {
2193 Node *in1 = next_control(ctrl->in(1));
2194 Node *in2 = next_control(ctrl->in(2));
2195 if (((in1->is_IfTrue() && in2->is_IfFalse()) ||
2196 (in2->is_IfTrue() && in1->is_IfFalse())) && (in1->in(0) == in2->in(0))) {
2197 ctrl = next_control(in1->in(0)->in(0));
2198 } else {
2199 break;
2200 }
2201 } else {
2202 break;
2203 }
2204 } else {
2205 ctrl = next_control(ctrl->in(0)); // keep searching
2206 }
2207 }
2208 if (ctrl->is_Lock()) {
2209 LockNode *lock = ctrl->as_Lock();
2210 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2211 Node* lock_obj = bs->step_over_gc_barrier(lock->obj_node());
2212 Node* unlock_obj = bs->step_over_gc_barrier(unlock->obj_node());
2213 if (lock_obj->eqv_uncast(unlock_obj) &&
2214 BoxLockNode::same_slot(lock->box_node(), unlock->box_node())) {
2215 lock_result = lock;
2216 }
2217 }
2218 return lock_result;
2219 }
2220
2221 // This code corresponds to case 3 above.
2222
2223 bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* lock,
2224 GrowableArray<AbstractLockNode*> &lock_ops) {
2225 Node* if_node = node->in(0);
2226 bool if_true = node->is_IfTrue();
2227
2228 if (if_node->is_If() && if_node->outcnt() == 2 && (if_true || node->is_IfFalse())) {
2229 Node *lock_ctrl = next_control(if_node->in(0));
2230 if (find_matching_unlock(lock_ctrl, lock, lock_ops)) {
2231 Node* lock1_node = nullptr;
2232 ProjNode* proj = if_node->as_If()->proj_out(!if_true);
2233 if (if_true) {
2234 if (proj->is_IfFalse() && proj->outcnt() == 1) {
2235 lock1_node = proj->unique_out();
2236 }
2237 } else {
2238 if (proj->is_IfTrue() && proj->outcnt() == 1) {
2239 lock1_node = proj->unique_out();
2240 }
2241 }
2242 if (lock1_node != nullptr && lock1_node->is_Lock()) {
2243 LockNode *lock1 = lock1_node->as_Lock();
2244 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2245 Node* lock_obj = bs->step_over_gc_barrier(lock->obj_node());
2246 Node* lock1_obj = bs->step_over_gc_barrier(lock1->obj_node());
2247 if (lock_obj->eqv_uncast(lock1_obj) &&
2248 BoxLockNode::same_slot(lock->box_node(), lock1->box_node()) &&
2249 !lock1->is_eliminated()) {
2250 lock_ops.append(lock1);
2251 return true;
2252 }
2253 }
2254 }
2255 }
2256
2257 lock_ops.trunc_to(0);
2258 return false;
2259 }
2260
2261 bool AbstractLockNode::find_unlocks_for_region(const RegionNode* region, LockNode* lock,
2262 GrowableArray<AbstractLockNode*> &lock_ops) {
2263 // check each control merging at this point for a matching unlock.
2264 // in(0) should be self edge so skip it.
2265 for (int i = 1; i < (int)region->req(); i++) {
2266 Node *in_node = next_control(region->in(i));
2267 if (in_node != nullptr) {
2268 if (find_matching_unlock(in_node, lock, lock_ops)) {
2269 // found a match so keep on checking.
2270 continue;
2271 } else if (find_lock_and_unlock_through_if(in_node, lock, lock_ops)) {
2272 continue;
2273 }
2274
2275 // If we fall through to here then it was some kind of node we
2276 // don't understand or there wasn't a matching unlock, so give
2277 // up trying to merge locks.
2278 lock_ops.trunc_to(0);
2279 return false;
2280 }
2281 }
2282 return true;
2283
2284 }
2285
2286 // Check that all locks/unlocks associated with object come from balanced regions.
2287 bool AbstractLockNode::is_balanced() {
2288 Node* obj = obj_node();
2289 for (uint j = 0; j < obj->outcnt(); j++) {
2290 Node* n = obj->raw_out(j);
2291 if (n->is_AbstractLock() &&
2292 n->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2293 BoxLockNode* n_box = n->as_AbstractLock()->box_node()->as_BoxLock();
2294 if (n_box->is_unbalanced()) {
2295 return false;
2296 }
2297 }
2298 }
2299 return true;
2300 }
2301
2302 const char* AbstractLockNode::_kind_names[] = {"Regular", "NonEscObj", "Coarsened", "Nested"};
2303
2304 const char * AbstractLockNode::kind_as_string() const {
2305 return _kind_names[_kind];
2306 }
2307
2308 #ifndef PRODUCT
2309 //
2310 // Create a counter which counts the number of times this lock is acquired
2311 //
2312 void AbstractLockNode::create_lock_counter(JVMState* state) {
2313 _counter = OptoRuntime::new_named_counter(state, NamedCounter::LockCounter);
2314 }
2315
2316 void AbstractLockNode::set_eliminated_lock_counter() {
2317 if (_counter) {
2318 // Update the counter to indicate that this lock was eliminated.
2319 // The counter update code will stay around even though the
2320 // optimizer will eliminate the lock operation itself.
2321 _counter->set_tag(NamedCounter::EliminatedLockCounter);
2322 }
2323 }
2324
2325 void AbstractLockNode::dump_spec(outputStream* st) const {
2326 st->print("%s ", _kind_names[_kind]);
2327 CallNode::dump_spec(st);
2328 }
2329
2330 void AbstractLockNode::dump_compact_spec(outputStream* st) const {
2331 st->print("%s", _kind_names[_kind]);
2332 }
2333 #endif
2334
2335 //=============================================================================
2336 Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2337
2338 // perform any generic optimizations first (returns 'this' or null)
2339 Node *result = SafePointNode::Ideal(phase, can_reshape);
2340 if (result != nullptr) return result;
2341 // Don't bother trying to transform a dead node
2342 if (in(0) && in(0)->is_top()) return nullptr;
2343
2344 // Now see if we can optimize away this lock. We don't actually
2345 // remove the locking here, we simply set the _eliminate flag which
2346 // prevents macro expansion from expanding the lock. Since we don't
2347 // modify the graph, the value returned from this function is the
2348 // one computed above.
2349 const Type* obj_type = phase->type(obj_node());
2350 if (can_reshape && EliminateLocks && !is_non_esc_obj() && !obj_type->is_inlinetypeptr()) {
2351 //
2352 // If we are locking an non-escaped object, the lock/unlock is unnecessary
2353 //
2354 ConnectionGraph *cgr = phase->C->congraph();
2355 if (cgr != nullptr && cgr->can_eliminate_lock(this)) {
2356 assert(!is_eliminated() || is_coarsened(), "sanity");
2357 // The lock could be marked eliminated by lock coarsening
2358 // code during first IGVN before EA. Replace coarsened flag
2359 // to eliminate all associated locks/unlocks.
2360 #ifdef ASSERT
2361 this->log_lock_optimization(phase->C,"eliminate_lock_set_non_esc1");
2362 #endif
2363 this->set_non_esc_obj();
2364 return result;
2365 }
2366
2367 if (!phase->C->do_locks_coarsening()) {
2368 return result; // Compiling without locks coarsening
2369 }
2370 //
2371 // Try lock coarsening
2372 //
2373 PhaseIterGVN* iter = phase->is_IterGVN();
2374 if (iter != nullptr && !is_eliminated()) {
2375
2376 GrowableArray<AbstractLockNode*> lock_ops;
2377
2378 Node *ctrl = next_control(in(0));
2379
2380 // now search back for a matching Unlock
2381 if (find_matching_unlock(ctrl, this, lock_ops)) {
2382 // found an unlock directly preceding this lock. This is the
2383 // case of single unlock directly control dependent on a
2384 // single lock which is the trivial version of case 1 or 2.
2385 } else if (ctrl->is_Region() ) {
2386 if (find_unlocks_for_region(ctrl->as_Region(), this, lock_ops)) {
2387 // found lock preceded by multiple unlocks along all paths
2388 // joining at this point which is case 3 in description above.
2389 }
2390 } else {
2391 // see if this lock comes from either half of an if and the
2392 // predecessors merges unlocks and the other half of the if
2393 // performs a lock.
2394 if (find_lock_and_unlock_through_if(ctrl, this, lock_ops)) {
2395 // found unlock splitting to an if with locks on both branches.
2396 }
2397 }
2398
2399 if (lock_ops.length() > 0) {
2400 // add ourselves to the list of locks to be eliminated.
2401 lock_ops.append(this);
2402
2403 #ifndef PRODUCT
2404 if (PrintEliminateLocks) {
2405 int locks = 0;
2406 int unlocks = 0;
2407 if (Verbose) {
2408 tty->print_cr("=== Locks coarsening ===");
2409 tty->print("Obj: ");
2410 obj_node()->dump();
2411 }
2412 for (int i = 0; i < lock_ops.length(); i++) {
2413 AbstractLockNode* lock = lock_ops.at(i);
2414 if (lock->Opcode() == Op_Lock)
2415 locks++;
2416 else
2417 unlocks++;
2418 if (Verbose) {
2419 tty->print("Box %d: ", i);
2420 box_node()->dump();
2421 tty->print(" %d: ", i);
2422 lock->dump();
2423 }
2424 }
2425 tty->print_cr("=== Coarsened %d unlocks and %d locks", unlocks, locks);
2426 }
2427 #endif
2428
2429 // for each of the identified locks, mark them
2430 // as eliminatable
2431 for (int i = 0; i < lock_ops.length(); i++) {
2432 AbstractLockNode* lock = lock_ops.at(i);
2433
2434 // Mark it eliminated by coarsening and update any counters
2435 #ifdef ASSERT
2436 lock->log_lock_optimization(phase->C, "eliminate_lock_set_coarsened");
2437 #endif
2438 lock->set_coarsened();
2439 }
2440 // Record this coarsened group.
2441 phase->C->add_coarsened_locks(lock_ops);
2442 } else if (ctrl->is_Region() &&
2443 iter->_worklist.member(ctrl)) {
2444 // We weren't able to find any opportunities but the region this
2445 // lock is control dependent on hasn't been processed yet so put
2446 // this lock back on the worklist so we can check again once any
2447 // region simplification has occurred.
2448 iter->_worklist.push(this);
2449 }
2450 }
2451 }
2452
2453 return result;
2454 }
2455
2456 //=============================================================================
2457 bool LockNode::is_nested_lock_region() {
2458 return is_nested_lock_region(nullptr);
2459 }
2460
2461 // p is used for access to compilation log; no logging if null
2462 bool LockNode::is_nested_lock_region(Compile * c) {
2463 BoxLockNode* box = box_node()->as_BoxLock();
2464 int stk_slot = box->stack_slot();
2465 if (stk_slot <= 0) {
2466 #ifdef ASSERT
2467 this->log_lock_optimization(c, "eliminate_lock_INLR_1");
2468 #endif
2469 return false; // External lock or it is not Box (Phi node).
2470 }
2471
2472 // Ignore complex cases: merged locks or multiple locks.
2473 Node* obj = obj_node();
2474 LockNode* unique_lock = nullptr;
2475 Node* bad_lock = nullptr;
2476 if (!box->is_simple_lock_region(&unique_lock, obj, &bad_lock)) {
2477 #ifdef ASSERT
2478 this->log_lock_optimization(c, "eliminate_lock_INLR_2a", bad_lock);
2479 #endif
2480 return false;
2481 }
2482 if (unique_lock != this) {
2483 #ifdef ASSERT
2484 this->log_lock_optimization(c, "eliminate_lock_INLR_2b", (unique_lock != nullptr ? unique_lock : bad_lock));
2485 if (PrintEliminateLocks && Verbose) {
2486 tty->print_cr("=============== unique_lock != this ============");
2487 tty->print(" this: ");
2488 this->dump();
2489 tty->print(" box: ");
2490 box->dump();
2491 tty->print(" obj: ");
2492 obj->dump();
2493 if (unique_lock != nullptr) {
2494 tty->print(" unique_lock: ");
2495 unique_lock->dump();
2496 }
2497 if (bad_lock != nullptr) {
2498 tty->print(" bad_lock: ");
2499 bad_lock->dump();
2500 }
2501 tty->print_cr("===============");
2502 }
2503 #endif
2504 return false;
2505 }
2506
2507 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2508 obj = bs->step_over_gc_barrier(obj);
2509 // Look for external lock for the same object.
2510 SafePointNode* sfn = this->as_SafePoint();
2511 JVMState* youngest_jvms = sfn->jvms();
2512 int max_depth = youngest_jvms->depth();
2513 for (int depth = 1; depth <= max_depth; depth++) {
2514 JVMState* jvms = youngest_jvms->of_depth(depth);
2515 int num_mon = jvms->nof_monitors();
2516 // Loop over monitors
2517 for (int idx = 0; idx < num_mon; idx++) {
2518 Node* obj_node = sfn->monitor_obj(jvms, idx);
2519 obj_node = bs->step_over_gc_barrier(obj_node);
2520 BoxLockNode* box_node = sfn->monitor_box(jvms, idx)->as_BoxLock();
2521 if ((box_node->stack_slot() < stk_slot) && obj_node->eqv_uncast(obj)) {
2522 box->set_nested();
2523 return true;
2524 }
2525 }
2526 }
2527 #ifdef ASSERT
2528 this->log_lock_optimization(c, "eliminate_lock_INLR_3");
2529 #endif
2530 return false;
2531 }
2532
2533 //=============================================================================
2534 uint UnlockNode::size_of() const { return sizeof(*this); }
2535
2536 //=============================================================================
2537 Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2538
2539 // perform any generic optimizations first (returns 'this' or null)
2540 Node *result = SafePointNode::Ideal(phase, can_reshape);
2541 if (result != nullptr) return result;
2542 // Don't bother trying to transform a dead node
2543 if (in(0) && in(0)->is_top()) return nullptr;
2544
2545 // Now see if we can optimize away this unlock. We don't actually
2546 // remove the unlocking here, we simply set the _eliminate flag which
2547 // prevents macro expansion from expanding the unlock. Since we don't
2548 // modify the graph, the value returned from this function is the
2549 // one computed above.
2550 // Escape state is defined after Parse phase.
2551 const Type* obj_type = phase->type(obj_node());
2552 if (can_reshape && EliminateLocks && !is_non_esc_obj() && !obj_type->is_inlinetypeptr()) {
2553 //
2554 // If we are unlocking an non-escaped object, the lock/unlock is unnecessary.
2555 //
2556 ConnectionGraph *cgr = phase->C->congraph();
2557 if (cgr != nullptr && cgr->can_eliminate_lock(this)) {
2558 assert(!is_eliminated() || is_coarsened(), "sanity");
2559 // The lock could be marked eliminated by lock coarsening
2560 // code during first IGVN before EA. Replace coarsened flag
2561 // to eliminate all associated locks/unlocks.
2562 #ifdef ASSERT
2563 this->log_lock_optimization(phase->C, "eliminate_lock_set_non_esc2");
2564 #endif
2565 this->set_non_esc_obj();
2566 }
2567 }
2568 return result;
2569 }
2570
2571 void AbstractLockNode::log_lock_optimization(Compile *C, const char * tag, Node* bad_lock) const {
2572 if (C == nullptr) {
2573 return;
2574 }
2575 CompileLog* log = C->log();
2576 if (log != nullptr) {
2577 Node* box = box_node();
2578 Node* obj = obj_node();
2579 int box_id = box != nullptr ? box->_idx : -1;
2580 int obj_id = obj != nullptr ? obj->_idx : -1;
2581
2582 log->begin_head("%s compile_id='%d' lock_id='%d' class='%s' kind='%s' box_id='%d' obj_id='%d' bad_id='%d'",
2583 tag, C->compile_id(), this->_idx,
2584 is_Unlock() ? "unlock" : is_Lock() ? "lock" : "?",
2585 kind_as_string(), box_id, obj_id, (bad_lock != nullptr ? bad_lock->_idx : -1));
2586 log->stamp();
2587 log->end_head();
2588 JVMState* p = is_Unlock() ? (as_Unlock()->dbg_jvms()) : jvms();
2589 while (p != nullptr) {
2590 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
2591 p = p->caller();
2592 }
2593 log->tail(tag);
2594 }
2595 }
2596
2597 bool CallNode::may_modify_arraycopy_helper(const TypeOopPtr* dest_t, const TypeOopPtr* t_oop, PhaseValues* phase) {
2598 if (dest_t->is_known_instance() && t_oop->is_known_instance()) {
2599 return dest_t->instance_id() == t_oop->instance_id();
2600 }
2601
2602 if (dest_t->isa_instptr() && !dest_t->is_instptr()->instance_klass()->equals(phase->C->env()->Object_klass())) {
2603 // clone
2604 if (t_oop->isa_aryptr()) {
2605 return false;
2606 }
2607 if (!t_oop->isa_instptr()) {
2608 return true;
2609 }
2610 if (dest_t->maybe_java_subtype_of(t_oop) || t_oop->maybe_java_subtype_of(dest_t)) {
2611 return true;
2612 }
2613 // unrelated
2614 return false;
2615 }
2616
2617 if (dest_t->isa_aryptr()) {
2618 // arraycopy or array clone
2619 if (t_oop->isa_instptr()) {
2620 return false;
2621 }
2622 if (!t_oop->isa_aryptr()) {
2623 return true;
2624 }
2625
2626 const Type* elem = dest_t->is_aryptr()->elem();
2627 if (elem == Type::BOTTOM) {
2628 // An array but we don't know what elements are
2629 return true;
2630 }
2631
2632 dest_t = dest_t->is_aryptr()->with_field_offset(Type::OffsetBot)->add_offset(Type::OffsetBot)->is_oopptr();
2633 t_oop = t_oop->is_aryptr()->with_field_offset(Type::OffsetBot);
2634 uint dest_alias = phase->C->get_alias_index(dest_t);
2635 uint t_oop_alias = phase->C->get_alias_index(t_oop);
2636
2637 return dest_alias == t_oop_alias;
2638 }
2639
2640 return true;
2641 }