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