1 /*
2 * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2024, 2025, Alibaba Group Holding Limited. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 *
24 */
25
26 #include "gc/shared/barrierSet.hpp"
27 #include "gc/shared/c2/barrierSetC2.hpp"
28 #include "libadt/vectset.hpp"
29 #include "memory/allocation.inline.hpp"
30 #include "memory/resourceArea.hpp"
31 #include "opto/ad.hpp"
32 #include "opto/callGenerator.hpp"
33 #include "opto/castnode.hpp"
34 #include "opto/cfgnode.hpp"
35 #include "opto/connode.hpp"
36 #include "opto/inlinetypenode.hpp"
37 #include "opto/loopnode.hpp"
38 #include "opto/machnode.hpp"
39 #include "opto/matcher.hpp"
40 #include "opto/node.hpp"
41 #include "opto/opcodes.hpp"
42 #include "opto/regmask.hpp"
43 #include "opto/rootnode.hpp"
44 #include "opto/type.hpp"
45 #include "utilities/copy.hpp"
46 #include "utilities/macros.hpp"
47 #include "utilities/powerOfTwo.hpp"
48 #include "utilities/stringUtils.hpp"
49
50 class RegMask;
51 // #include "phase.hpp"
52 class PhaseTransform;
53 class PhaseGVN;
54
55 // Arena we are currently building Nodes in
56 const uint Node::NotAMachineReg = 0xffff0000;
57
58 #ifndef PRODUCT
59 extern uint nodes_created;
60 #endif
61 #ifdef __clang__
62 #pragma clang diagnostic push
63 #pragma GCC diagnostic ignored "-Wuninitialized"
64 #endif
65
66 #ifdef ASSERT
67
68 //-------------------------- construct_node------------------------------------
69 // Set a breakpoint here to identify where a particular node index is built.
70 void Node::verify_construction() {
71 _debug_orig = nullptr;
72 // The decimal digits of _debug_idx are <compile_id> followed by 10 digits of <_idx>
73 Compile* C = Compile::current();
74 assert(C->unique() < (INT_MAX - 1), "Node limit exceeded INT_MAX");
75 uint64_t new_debug_idx = (uint64_t)C->compile_id() * 10000000000 + _idx;
76 set_debug_idx(new_debug_idx);
77 if (!C->phase_optimize_finished()) {
78 // Only check assert during parsing and optimization phase. Skip it while generating code.
79 assert(C->live_nodes() <= C->max_node_limit(), "Live Node limit exceeded limit");
80 }
81 if (BreakAtNode != 0 && (_debug_idx == BreakAtNode || (uint64_t)_idx == BreakAtNode)) {
82 tty->print_cr("BreakAtNode: _idx=%d _debug_idx=" UINT64_FORMAT, _idx, _debug_idx);
83 BREAKPOINT;
84 }
85 #if OPTO_DU_ITERATOR_ASSERT
86 _last_del = nullptr;
87 _del_tick = 0;
88 #endif
89 _hash_lock = 0;
90 }
91
92
93 // #ifdef ASSERT ...
94
95 #if OPTO_DU_ITERATOR_ASSERT
96 void DUIterator_Common::sample(const Node* node) {
97 _vdui = VerifyDUIterators;
98 _node = node;
99 _outcnt = node->_outcnt;
100 _del_tick = node->_del_tick;
101 _last = nullptr;
102 }
103
104 void DUIterator_Common::verify(const Node* node, bool at_end_ok) {
105 assert(_node == node, "consistent iterator source");
106 assert(_del_tick == node->_del_tick, "no unexpected deletions allowed");
107 }
108
109 void DUIterator_Common::verify_resync() {
110 // Ensure that the loop body has just deleted the last guy produced.
111 const Node* node = _node;
112 // Ensure that at least one copy of the last-seen edge was deleted.
113 // Note: It is OK to delete multiple copies of the last-seen edge.
114 // Unfortunately, we have no way to verify that all the deletions delete
115 // that same edge. On this point we must use the Honor System.
116 assert(node->_del_tick >= _del_tick+1, "must have deleted an edge");
117 assert(node->_last_del == _last, "must have deleted the edge just produced");
118 // We liked this deletion, so accept the resulting outcnt and tick.
119 _outcnt = node->_outcnt;
120 _del_tick = node->_del_tick;
121 }
122
123 void DUIterator_Common::reset(const DUIterator_Common& that) {
124 if (this == &that) return; // ignore assignment to self
125 if (!_vdui) {
126 // We need to initialize everything, overwriting garbage values.
127 _last = that._last;
128 _vdui = that._vdui;
129 }
130 // Note: It is legal (though odd) for an iterator over some node x
131 // to be reassigned to iterate over another node y. Some doubly-nested
132 // progress loops depend on being able to do this.
133 const Node* node = that._node;
134 // Re-initialize everything, except _last.
135 _node = node;
136 _outcnt = node->_outcnt;
137 _del_tick = node->_del_tick;
138 }
139
140 void DUIterator::sample(const Node* node) {
141 DUIterator_Common::sample(node); // Initialize the assertion data.
142 _refresh_tick = 0; // No refreshes have happened, as yet.
143 }
144
145 void DUIterator::verify(const Node* node, bool at_end_ok) {
146 DUIterator_Common::verify(node, at_end_ok);
147 assert(_idx < node->_outcnt + (uint)at_end_ok, "idx in range");
148 }
149
150 void DUIterator::verify_increment() {
151 if (_refresh_tick & 1) {
152 // We have refreshed the index during this loop.
153 // Fix up _idx to meet asserts.
154 if (_idx > _outcnt) _idx = _outcnt;
155 }
156 verify(_node, true);
157 }
158
159 void DUIterator::verify_resync() {
160 // Note: We do not assert on _outcnt, because insertions are OK here.
161 DUIterator_Common::verify_resync();
162 // Make sure we are still in sync, possibly with no more out-edges:
163 verify(_node, true);
164 }
165
166 void DUIterator::reset(const DUIterator& that) {
167 if (this == &that) return; // self assignment is always a no-op
168 assert(that._refresh_tick == 0, "assign only the result of Node::outs()");
169 assert(that._idx == 0, "assign only the result of Node::outs()");
170 assert(_idx == that._idx, "already assigned _idx");
171 if (!_vdui) {
172 // We need to initialize everything, overwriting garbage values.
173 sample(that._node);
174 } else {
175 DUIterator_Common::reset(that);
176 if (_refresh_tick & 1) {
177 _refresh_tick++; // Clear the "was refreshed" flag.
178 }
179 assert(_refresh_tick < 2*100000, "DU iteration must converge quickly");
180 }
181 }
182
183 void DUIterator::refresh() {
184 DUIterator_Common::sample(_node); // Re-fetch assertion data.
185 _refresh_tick |= 1; // Set the "was refreshed" flag.
186 }
187
188 void DUIterator::verify_finish() {
189 // If the loop has killed the node, do not require it to re-run.
190 if (_node->_outcnt == 0) _refresh_tick &= ~1;
191 // If this assert triggers, it means that a loop used refresh_out_pos
192 // to re-synch an iteration index, but the loop did not correctly
193 // re-run itself, using a "while (progress)" construct.
194 // This iterator enforces the rule that you must keep trying the loop
195 // until it "runs clean" without any need for refreshing.
196 assert(!(_refresh_tick & 1), "the loop must run once with no refreshing");
197 }
198
199
200 void DUIterator_Fast::verify(const Node* node, bool at_end_ok) {
201 DUIterator_Common::verify(node, at_end_ok);
202 Node** out = node->_out;
203 uint cnt = node->_outcnt;
204 assert(cnt == _outcnt, "no insertions allowed");
205 assert(_outp >= out && _outp <= out + cnt - !at_end_ok, "outp in range");
206 // This last check is carefully designed to work for NO_OUT_ARRAY.
207 }
208
209 void DUIterator_Fast::verify_limit() {
210 const Node* node = _node;
211 verify(node, true);
212 assert(_outp == node->_out + node->_outcnt, "limit still correct");
213 }
214
215 void DUIterator_Fast::verify_resync() {
216 const Node* node = _node;
217 if (_outp == node->_out + _outcnt) {
218 // Note that the limit imax, not the pointer i, gets updated with the
219 // exact count of deletions. (For the pointer it's always "--i".)
220 assert(node->_outcnt+node->_del_tick == _outcnt+_del_tick, "no insertions allowed with deletion(s)");
221 // This is a limit pointer, with a name like "imax".
222 // Fudge the _last field so that the common assert will be happy.
223 _last = (Node*) node->_last_del;
224 DUIterator_Common::verify_resync();
225 } else {
226 assert(node->_outcnt < _outcnt, "no insertions allowed with deletion(s)");
227 // A normal internal pointer.
228 DUIterator_Common::verify_resync();
229 // Make sure we are still in sync, possibly with no more out-edges:
230 verify(node, true);
231 }
232 }
233
234 void DUIterator_Fast::verify_relimit(uint n) {
235 const Node* node = _node;
236 assert((int)n > 0, "use imax -= n only with a positive count");
237 // This must be a limit pointer, with a name like "imax".
238 assert(_outp == node->_out + node->_outcnt, "apply -= only to a limit (imax)");
239 // The reported number of deletions must match what the node saw.
240 assert(node->_del_tick == _del_tick + n, "must have deleted n edges");
241 // Fudge the _last field so that the common assert will be happy.
242 _last = (Node*) node->_last_del;
243 DUIterator_Common::verify_resync();
244 }
245
246 void DUIterator_Fast::reset(const DUIterator_Fast& that) {
247 assert(_outp == that._outp, "already assigned _outp");
248 DUIterator_Common::reset(that);
249 }
250
251 void DUIterator_Last::verify(const Node* node, bool at_end_ok) {
252 // at_end_ok means the _outp is allowed to underflow by 1
253 _outp += at_end_ok;
254 DUIterator_Fast::verify(node, at_end_ok); // check _del_tick, etc.
255 _outp -= at_end_ok;
256 assert(_outp == (node->_out + node->_outcnt) - 1, "pointer must point to end of nodes");
257 }
258
259 void DUIterator_Last::verify_limit() {
260 // Do not require the limit address to be resynched.
261 //verify(node, true);
262 assert(_outp == _node->_out, "limit still correct");
263 }
264
265 void DUIterator_Last::verify_step(uint num_edges) {
266 assert((int)num_edges > 0, "need non-zero edge count for loop progress");
267 _outcnt -= num_edges;
268 _del_tick += num_edges;
269 // Make sure we are still in sync, possibly with no more out-edges:
270 const Node* node = _node;
271 verify(node, true);
272 assert(node->_last_del == _last, "must have deleted the edge just produced");
273 }
274
275 #endif //OPTO_DU_ITERATOR_ASSERT
276
277
278 #endif //ASSERT
279
280
281 // This constant used to initialize _out may be any non-null value.
282 // The value null is reserved for the top node only.
283 #define NO_OUT_ARRAY ((Node**)-1)
284
285 // Out-of-line code from node constructors.
286 // Executed only when extra debug info. is being passed around.
287 static void init_node_notes(Compile* C, int idx, Node_Notes* nn) {
288 C->set_node_notes_at(idx, nn);
289 }
290
291 // Shared initialization code.
292 inline int Node::Init(int req) {
293 Compile* C = Compile::current();
294 int idx = C->next_unique();
295 NOT_PRODUCT(_igv_idx = C->next_igv_idx());
296
297 // Allocate memory for the necessary number of edges.
298 if (req > 0) {
299 // Allocate space for _in array to have double alignment.
300 _in = (Node **) ((char *) (C->node_arena()->AmallocWords(req * sizeof(void*))));
301 }
302 // If there are default notes floating around, capture them:
303 Node_Notes* nn = C->default_node_notes();
304 if (nn != nullptr) init_node_notes(C, idx, nn);
305
306 // Note: At this point, C is dead,
307 // and we begin to initialize the new Node.
308
309 _cnt = _max = req;
310 _outcnt = _outmax = 0;
311 _class_id = Class_Node;
312 _flags = 0;
313 _out = NO_OUT_ARRAY;
314 return idx;
315 }
316
317 //------------------------------Node-------------------------------------------
318 // Create a Node, with a given number of required edges.
319 Node::Node(uint req)
320 : _idx(Init(req))
321 #ifdef ASSERT
322 , _parse_idx(_idx)
323 #endif
324 {
325 assert( req < Compile::current()->max_node_limit() - NodeLimitFudgeFactor, "Input limit exceeded" );
326 DEBUG_ONLY( verify_construction() );
327 NOT_PRODUCT(nodes_created++);
328 if (req == 0) {
329 _in = nullptr;
330 } else {
331 Node** to = _in;
332 for(uint i = 0; i < req; i++) {
333 to[i] = nullptr;
334 }
335 }
336 }
337
338 //------------------------------Node-------------------------------------------
339 Node::Node(Node *n0)
340 : _idx(Init(1))
341 #ifdef ASSERT
342 , _parse_idx(_idx)
343 #endif
344 {
345 DEBUG_ONLY( verify_construction() );
346 NOT_PRODUCT(nodes_created++);
347 assert( is_not_dead(n0), "can not use dead node");
348 _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
349 }
350
351 //------------------------------Node-------------------------------------------
352 Node::Node(Node *n0, Node *n1)
353 : _idx(Init(2))
354 #ifdef ASSERT
355 , _parse_idx(_idx)
356 #endif
357 {
358 DEBUG_ONLY( verify_construction() );
359 NOT_PRODUCT(nodes_created++);
360 assert( is_not_dead(n0), "can not use dead node");
361 assert( is_not_dead(n1), "can not use dead node");
362 _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
363 _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
364 }
365
366 //------------------------------Node-------------------------------------------
367 Node::Node(Node *n0, Node *n1, Node *n2)
368 : _idx(Init(3))
369 #ifdef ASSERT
370 , _parse_idx(_idx)
371 #endif
372 {
373 DEBUG_ONLY( verify_construction() );
374 NOT_PRODUCT(nodes_created++);
375 assert( is_not_dead(n0), "can not use dead node");
376 assert( is_not_dead(n1), "can not use dead node");
377 assert( is_not_dead(n2), "can not use dead node");
378 _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
379 _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
380 _in[2] = n2; if (n2 != nullptr) n2->add_out((Node *)this);
381 }
382
383 //------------------------------Node-------------------------------------------
384 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3)
385 : _idx(Init(4))
386 #ifdef ASSERT
387 , _parse_idx(_idx)
388 #endif
389 {
390 DEBUG_ONLY( verify_construction() );
391 NOT_PRODUCT(nodes_created++);
392 assert( is_not_dead(n0), "can not use dead node");
393 assert( is_not_dead(n1), "can not use dead node");
394 assert( is_not_dead(n2), "can not use dead node");
395 assert( is_not_dead(n3), "can not use dead node");
396 _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
397 _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
398 _in[2] = n2; if (n2 != nullptr) n2->add_out((Node *)this);
399 _in[3] = n3; if (n3 != nullptr) n3->add_out((Node *)this);
400 }
401
402 //------------------------------Node-------------------------------------------
403 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3, Node *n4)
404 : _idx(Init(5))
405 #ifdef ASSERT
406 , _parse_idx(_idx)
407 #endif
408 {
409 DEBUG_ONLY( verify_construction() );
410 NOT_PRODUCT(nodes_created++);
411 assert( is_not_dead(n0), "can not use dead node");
412 assert( is_not_dead(n1), "can not use dead node");
413 assert( is_not_dead(n2), "can not use dead node");
414 assert( is_not_dead(n3), "can not use dead node");
415 assert( is_not_dead(n4), "can not use dead node");
416 _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
417 _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
418 _in[2] = n2; if (n2 != nullptr) n2->add_out((Node *)this);
419 _in[3] = n3; if (n3 != nullptr) n3->add_out((Node *)this);
420 _in[4] = n4; if (n4 != nullptr) n4->add_out((Node *)this);
421 }
422
423 //------------------------------Node-------------------------------------------
424 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3,
425 Node *n4, Node *n5)
426 : _idx(Init(6))
427 #ifdef ASSERT
428 , _parse_idx(_idx)
429 #endif
430 {
431 DEBUG_ONLY( verify_construction() );
432 NOT_PRODUCT(nodes_created++);
433 assert( is_not_dead(n0), "can not use dead node");
434 assert( is_not_dead(n1), "can not use dead node");
435 assert( is_not_dead(n2), "can not use dead node");
436 assert( is_not_dead(n3), "can not use dead node");
437 assert( is_not_dead(n4), "can not use dead node");
438 assert( is_not_dead(n5), "can not use dead node");
439 _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
440 _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
441 _in[2] = n2; if (n2 != nullptr) n2->add_out((Node *)this);
442 _in[3] = n3; if (n3 != nullptr) n3->add_out((Node *)this);
443 _in[4] = n4; if (n4 != nullptr) n4->add_out((Node *)this);
444 _in[5] = n5; if (n5 != nullptr) n5->add_out((Node *)this);
445 }
446
447 //------------------------------Node-------------------------------------------
448 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3,
449 Node *n4, Node *n5, Node *n6)
450 : _idx(Init(7))
451 #ifdef ASSERT
452 , _parse_idx(_idx)
453 #endif
454 {
455 DEBUG_ONLY( verify_construction() );
456 NOT_PRODUCT(nodes_created++);
457 assert( is_not_dead(n0), "can not use dead node");
458 assert( is_not_dead(n1), "can not use dead node");
459 assert( is_not_dead(n2), "can not use dead node");
460 assert( is_not_dead(n3), "can not use dead node");
461 assert( is_not_dead(n4), "can not use dead node");
462 assert( is_not_dead(n5), "can not use dead node");
463 assert( is_not_dead(n6), "can not use dead node");
464 _in[0] = n0; if (n0 != nullptr) n0->add_out((Node *)this);
465 _in[1] = n1; if (n1 != nullptr) n1->add_out((Node *)this);
466 _in[2] = n2; if (n2 != nullptr) n2->add_out((Node *)this);
467 _in[3] = n3; if (n3 != nullptr) n3->add_out((Node *)this);
468 _in[4] = n4; if (n4 != nullptr) n4->add_out((Node *)this);
469 _in[5] = n5; if (n5 != nullptr) n5->add_out((Node *)this);
470 _in[6] = n6; if (n6 != nullptr) n6->add_out((Node *)this);
471 }
472
473 #ifdef __clang__
474 #pragma clang diagnostic pop
475 #endif
476
477
478 //------------------------------clone------------------------------------------
479 // Clone a Node.
480 Node *Node::clone() const {
481 Compile* C = Compile::current();
482 uint s = size_of(); // Size of inherited Node
483 Node *n = (Node*)C->node_arena()->AmallocWords(size_of() + _max*sizeof(Node*));
484 Copy::conjoint_words_to_lower((HeapWord*)this, (HeapWord*)n, s);
485 // Set the new input pointer array
486 n->_in = (Node**)(((char*)n)+s);
487 // Cannot share the old output pointer array, so kill it
488 n->_out = NO_OUT_ARRAY;
489 // And reset the counters to 0
490 n->_outcnt = 0;
491 n->_outmax = 0;
492 // Unlock this guy, since he is not in any hash table.
493 DEBUG_ONLY(n->_hash_lock = 0);
494 // Walk the old node's input list to duplicate its edges
495 uint i;
496 for( i = 0; i < len(); i++ ) {
497 Node *x = in(i);
498 n->_in[i] = x;
499 if (x != nullptr) x->add_out(n);
500 }
501 if (is_macro()) {
502 C->add_macro_node(n);
503 }
504 if (is_expensive()) {
505 C->add_expensive_node(n);
506 }
507 if (for_post_loop_opts_igvn()) {
508 // Don't add cloned node to Compile::_for_post_loop_opts_igvn list automatically.
509 // If it is applicable, it will happen anyway when the cloned node is registered with IGVN.
510 n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
511 }
512 if (for_merge_stores_igvn()) {
513 // Don't add cloned node to Compile::_for_merge_stores_igvn list automatically.
514 // If it is applicable, it will happen anyway when the cloned node is registered with IGVN.
515 n->remove_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
516 }
517 if (n->is_ParsePredicate()) {
518 C->add_parse_predicate(n->as_ParsePredicate());
519 }
520 if (n->is_OpaqueTemplateAssertionPredicate()) {
521 C->add_template_assertion_predicate_opaque(n->as_OpaqueTemplateAssertionPredicate());
522 }
523
524 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
525 bs->register_potential_barrier_node(n);
526
527 n->set_idx(C->next_unique()); // Get new unique index as well
528 NOT_PRODUCT(n->_igv_idx = C->next_igv_idx());
529 DEBUG_ONLY( n->verify_construction() );
530 NOT_PRODUCT(nodes_created++);
531 // Do not patch over the debug_idx of a clone, because it makes it
532 // impossible to break on the clone's moment of creation.
533 //DEBUG_ONLY( n->set_debug_idx( debug_idx() ) );
534
535 C->copy_node_notes_to(n, (Node*) this);
536
537 // MachNode clone
538 uint nopnds;
539 if (this->is_Mach() && (nopnds = this->as_Mach()->num_opnds()) > 0) {
540 MachNode *mach = n->as_Mach();
541 MachNode *mthis = this->as_Mach();
542 // Get address of _opnd_array.
543 // It should be the same offset since it is the clone of this node.
544 MachOper **from = mthis->_opnds;
545 MachOper **to = (MachOper **)((size_t)(&mach->_opnds) +
546 pointer_delta((const void*)from,
547 (const void*)(&mthis->_opnds), 1));
548 mach->_opnds = to;
549 for ( uint i = 0; i < nopnds; ++i ) {
550 to[i] = from[i]->clone();
551 }
552 }
553 if (this->is_MachProj()) {
554 // MachProjNodes contain register masks that may contain pointers to
555 // externally allocated memory. Make sure to use a proper constructor
556 // instead of just shallowly copying.
557 MachProjNode* mach = n->as_MachProj();
558 MachProjNode* mthis = this->as_MachProj();
559 new (&mach->_rout) RegMask(mthis->_rout);
560 }
561 if (n->is_Call()) {
562 // CallGenerator is linked to the original node.
563 CallGenerator* cg = n->as_Call()->generator();
564 if (cg != nullptr) {
565 CallGenerator* cloned_cg = cg->with_call_node(n->as_Call());
566 n->as_Call()->set_generator(cloned_cg);
567 }
568 }
569 if (n->is_SafePoint()) {
570 // Scalar replacement and macro expansion might modify the JVMState.
571 // Clone it to make sure it's not shared between SafePointNodes.
572 n->as_SafePoint()->clone_jvms(C);
573 n->as_SafePoint()->clone_replaced_nodes();
574 }
575 if (n->is_InlineType()) {
576 C->add_inline_type(n);
577 }
578 if (n->is_LoadFlat() || n->is_StoreFlat()) {
579 C->add_flat_access(n);
580 }
581 Compile::current()->record_modified_node(n);
582 return n; // Return the clone
583 }
584
585 //---------------------------setup_is_top--------------------------------------
586 // Call this when changing the top node, to reassert the invariants
587 // required by Node::is_top. See Compile::set_cached_top_node.
588 void Node::setup_is_top() {
589 if (this == (Node*)Compile::current()->top()) {
590 // This node has just become top. Kill its out array.
591 _outcnt = _outmax = 0;
592 _out = nullptr; // marker value for top
593 assert(is_top(), "must be top");
594 } else {
595 if (_out == nullptr) _out = NO_OUT_ARRAY;
596 assert(!is_top(), "must not be top");
597 }
598 }
599
600 //------------------------------~Node------------------------------------------
601 // Fancy destructor; eagerly attempt to reclaim Node numberings and storage
602 void Node::destruct(PhaseValues* phase) {
603 Compile* compile = (phase != nullptr) ? phase->C : Compile::current();
604 if (phase != nullptr && phase->is_IterGVN()) {
605 phase->is_IterGVN()->_worklist.remove(this);
606 }
607 // If this is the most recently created node, reclaim its index. Otherwise,
608 // record the node as dead to keep liveness information accurate.
609 if ((uint)_idx+1 == compile->unique()) {
610 compile->set_unique(compile->unique()-1);
611 } else {
612 compile->record_dead_node(_idx);
613 }
614 // Clear debug info:
615 Node_Notes* nn = compile->node_notes_at(_idx);
616 if (nn != nullptr) nn->clear();
617 // Walk the input array, freeing the corresponding output edges
618 _cnt = _max; // forget req/prec distinction
619 uint i;
620 for( i = 0; i < _max; i++ ) {
621 set_req(i, nullptr);
622 //assert(def->out(def->outcnt()-1) == (Node *)this,"bad def-use hacking in reclaim");
623 }
624 assert(outcnt() == 0, "deleting a node must not leave a dangling use");
625
626 if (is_macro()) {
627 compile->remove_macro_node(this);
628 }
629 if (is_expensive()) {
630 compile->remove_expensive_node(this);
631 }
632 if (is_OpaqueTemplateAssertionPredicate()) {
633 compile->remove_template_assertion_predicate_opaque(as_OpaqueTemplateAssertionPredicate());
634 }
635 if (is_ParsePredicate()) {
636 compile->remove_parse_predicate(as_ParsePredicate());
637 }
638 if (for_post_loop_opts_igvn()) {
639 compile->remove_from_post_loop_opts_igvn(this);
640 }
641 if (is_InlineType()) {
642 compile->remove_inline_type(this);
643 }
644 if (for_merge_stores_igvn()) {
645 compile->remove_from_merge_stores_igvn(this);
646 }
647
648 if (is_SafePoint()) {
649 as_SafePoint()->delete_replaced_nodes();
650
651 if (is_CallStaticJava()) {
652 compile->remove_unstable_if_trap(as_CallStaticJava(), false);
653 }
654 }
655 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
656 bs->unregister_potential_barrier_node(this);
657
658 // See if the input array was allocated just prior to the object
659 int edge_size = _max*sizeof(void*);
660 int out_edge_size = _outmax*sizeof(void*);
661 char *in_array = ((char*)_in);
662 char *edge_end = in_array + edge_size;
663 char *out_array = (char*)(_out == NO_OUT_ARRAY? nullptr: _out);
664 int node_size = size_of();
665
666 #ifdef ASSERT
667 // We will not actually delete the storage, but we'll make the node unusable.
668 compile->remove_modified_node(this);
669 *(address*)this = badAddress; // smash the C++ vtbl, probably
670 _in = _out = (Node**) badAddress;
671 _max = _cnt = _outmax = _outcnt = 0;
672 #endif
673
674 // Free the output edge array
675 if (out_edge_size > 0) {
676 compile->node_arena()->Afree(out_array, out_edge_size);
677 }
678
679 // Free the input edge array and the node itself
680 if( edge_end == (char*)this ) {
681 // It was; free the input array and object all in one hit
682 #ifndef ASSERT
683 compile->node_arena()->Afree(in_array, edge_size+node_size);
684 #endif
685 } else {
686 // Free just the input array
687 compile->node_arena()->Afree(in_array, edge_size);
688
689 // Free just the object
690 #ifndef ASSERT
691 compile->node_arena()->Afree(this, node_size);
692 #endif
693 }
694 }
695
696 // Resize input or output array to grow it to the next larger power-of-2 bigger
697 // than len.
698 void Node::resize_array(Node**& array, node_idx_t& max_size, uint len, bool needs_clearing) {
699 Arena* arena = Compile::current()->node_arena();
700 uint new_max = max_size;
701 if (new_max == 0) {
702 max_size = 4;
703 array = (Node**)arena->Amalloc(4 * sizeof(Node*));
704 if (needs_clearing) {
705 array[0] = nullptr;
706 array[1] = nullptr;
707 array[2] = nullptr;
708 array[3] = nullptr;
709 }
710 return;
711 }
712 new_max = next_power_of_2(len);
713 assert(needs_clearing || (array != nullptr && array != NO_OUT_ARRAY), "out must have sensible value");
714 array = (Node**)arena->Arealloc(array, max_size * sizeof(Node*), new_max * sizeof(Node*));
715 if (needs_clearing) {
716 Copy::zero_to_bytes(&array[max_size], (new_max - max_size) * sizeof(Node*)); // null all new space
717 }
718 max_size = new_max; // Record new max length
719 // This assertion makes sure that Node::_max is wide enough to
720 // represent the numerical value of new_max.
721 assert(max_size > len, "int width of _max or _outmax is too small");
722 }
723
724 //------------------------------grow-------------------------------------------
725 // Grow the input array, making space for more edges
726 void Node::grow(uint len) {
727 resize_array(_in, _max, len, true);
728 }
729
730 //-----------------------------out_grow----------------------------------------
731 // Grow the input array, making space for more edges
732 void Node::out_grow(uint len) {
733 assert(!is_top(), "cannot grow a top node's out array");
734 resize_array(_out, _outmax, len, false);
735 }
736
737 #ifdef ASSERT
738 //------------------------------is_dead----------------------------------------
739 bool Node::is_dead() const {
740 // Mach and pinch point nodes may look like dead.
741 if( is_top() || is_Mach() || (Opcode() == Op_Node && _outcnt > 0) )
742 return false;
743 for( uint i = 0; i < _max; i++ )
744 if( _in[i] != nullptr )
745 return false;
746 return true;
747 }
748
749 bool Node::is_not_dead(const Node* n) {
750 return n == nullptr || !PhaseIterGVN::is_verify_def_use() || !(n->is_dead());
751 }
752
753 bool Node::is_reachable_from_root() const {
754 ResourceMark rm;
755 Unique_Node_List wq;
756 wq.push((Node*)this);
757 RootNode* root = Compile::current()->root();
758 for (uint i = 0; i < wq.size(); i++) {
759 Node* m = wq.at(i);
760 if (m == root) {
761 return true;
762 }
763 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
764 Node* u = m->fast_out(j);
765 wq.push(u);
766 }
767 }
768 return false;
769 }
770 #endif
771
772 //------------------------------is_unreachable---------------------------------
773 bool Node::is_unreachable(PhaseIterGVN &igvn) const {
774 assert(!is_Mach(), "doesn't work with MachNodes");
775 return outcnt() == 0 || igvn.type(this) == Type::TOP || (in(0) != nullptr && in(0)->is_top());
776 }
777
778 //------------------------------add_req----------------------------------------
779 // Add a new required input at the end
780 void Node::add_req( Node *n ) {
781 assert( is_not_dead(n), "can not use dead node");
782
783 // Look to see if I can move precedence down one without reallocating
784 if( (_cnt >= _max) || (in(_max-1) != nullptr) )
785 grow( _max+1 );
786
787 // Find a precedence edge to move
788 if( in(_cnt) != nullptr ) { // Next precedence edge is busy?
789 uint i;
790 for( i=_cnt; i<_max; i++ )
791 if( in(i) == nullptr ) // Find the null at end of prec edge list
792 break; // There must be one, since we grew the array
793 _in[i] = in(_cnt); // Move prec over, making space for req edge
794 }
795 _in[_cnt++] = n; // Stuff over old prec edge
796 if (n != nullptr) n->add_out((Node *)this);
797 Compile::current()->record_modified_node(this);
798 }
799
800 //---------------------------add_req_batch-------------------------------------
801 // Add a new required input at the end
802 void Node::add_req_batch( Node *n, uint m ) {
803 assert( is_not_dead(n), "can not use dead node");
804 // check various edge cases
805 if ((int)m <= 1) {
806 assert((int)m >= 0, "oob");
807 if (m != 0) add_req(n);
808 return;
809 }
810
811 // Look to see if I can move precedence down one without reallocating
812 if( (_cnt+m) > _max || _in[_max-m] )
813 grow( _max+m );
814
815 // Find a precedence edge to move
816 if( _in[_cnt] != nullptr ) { // Next precedence edge is busy?
817 uint i;
818 for( i=_cnt; i<_max; i++ )
819 if( _in[i] == nullptr ) // Find the null at end of prec edge list
820 break; // There must be one, since we grew the array
821 // Slide all the precs over by m positions (assume #prec << m).
822 Copy::conjoint_words_to_higher((HeapWord*)&_in[_cnt], (HeapWord*)&_in[_cnt+m], ((i-_cnt)*sizeof(Node*)));
823 }
824
825 // Stuff over the old prec edges
826 for(uint i=0; i<m; i++ ) {
827 _in[_cnt++] = n;
828 }
829
830 // Insert multiple out edges on the node.
831 if (n != nullptr && !n->is_top()) {
832 for(uint i=0; i<m; i++ ) {
833 n->add_out((Node *)this);
834 }
835 }
836 Compile::current()->record_modified_node(this);
837 }
838
839 //------------------------------del_req----------------------------------------
840 // Delete the required edge and compact the edge array
841 void Node::del_req( uint idx ) {
842 assert( idx < _cnt, "oob");
843 assert( !VerifyHashTableKeys || _hash_lock == 0,
844 "remove node from hash table before modifying it");
845 // First remove corresponding def-use edge
846 Node *n = in(idx);
847 if (n != nullptr) n->del_out((Node *)this);
848 _in[idx] = in(--_cnt); // Compact the array
849 // Avoid spec violation: Gap in prec edges.
850 close_prec_gap_at(_cnt);
851 Compile::current()->record_modified_node(this);
852 }
853
854 //------------------------------del_req_ordered--------------------------------
855 // Delete the required edge and compact the edge array with preserved order
856 void Node::del_req_ordered( uint idx ) {
857 assert( idx < _cnt, "oob");
858 assert( !VerifyHashTableKeys || _hash_lock == 0,
859 "remove node from hash table before modifying it");
860 // First remove corresponding def-use edge
861 Node *n = in(idx);
862 if (n != nullptr) n->del_out((Node *)this);
863 if (idx < --_cnt) { // Not last edge ?
864 Copy::conjoint_words_to_lower((HeapWord*)&_in[idx+1], (HeapWord*)&_in[idx], ((_cnt-idx)*sizeof(Node*)));
865 }
866 // Avoid spec violation: Gap in prec edges.
867 close_prec_gap_at(_cnt);
868 Compile::current()->record_modified_node(this);
869 }
870
871 //------------------------------ins_req----------------------------------------
872 // Insert a new required input at the end
873 void Node::ins_req( uint idx, Node *n ) {
874 assert( is_not_dead(n), "can not use dead node");
875 add_req(nullptr); // Make space
876 assert( idx < _max, "Must have allocated enough space");
877 // Slide over
878 if(_cnt-idx-1 > 0) {
879 Copy::conjoint_words_to_higher((HeapWord*)&_in[idx], (HeapWord*)&_in[idx+1], ((_cnt-idx-1)*sizeof(Node*)));
880 }
881 _in[idx] = n; // Stuff over old required edge
882 if (n != nullptr) n->add_out((Node *)this); // Add reciprocal def-use edge
883 Compile::current()->record_modified_node(this);
884 }
885
886 //-----------------------------find_edge---------------------------------------
887 int Node::find_edge(Node* n) {
888 for (uint i = 0; i < len(); i++) {
889 if (_in[i] == n) return i;
890 }
891 return -1;
892 }
893
894 //----------------------------replace_edge-------------------------------------
895 int Node::replace_edge(Node* old, Node* neww, PhaseGVN* gvn) {
896 if (old == neww) return 0; // nothing to do
897 uint nrep = 0;
898 for (uint i = 0; i < len(); i++) {
899 if (in(i) == old) {
900 if (i < req()) {
901 if (gvn != nullptr) {
902 set_req_X(i, neww, gvn);
903 } else {
904 set_req(i, neww);
905 }
906 } else {
907 assert(gvn == nullptr || gvn->is_IterGVN() == nullptr, "no support for igvn here");
908 assert(find_prec_edge(neww) == -1, "spec violation: duplicated prec edge (node %d -> %d)", _idx, neww->_idx);
909 set_prec(i, neww);
910 }
911 nrep++;
912 }
913 }
914 return nrep;
915 }
916
917 /**
918 * Replace input edges in the range pointing to 'old' node.
919 */
920 int Node::replace_edges_in_range(Node* old, Node* neww, int start, int end, PhaseGVN* gvn) {
921 if (old == neww) return 0; // nothing to do
922 uint nrep = 0;
923 for (int i = start; i < end; i++) {
924 if (in(i) == old) {
925 set_req_X(i, neww, gvn);
926 nrep++;
927 }
928 }
929 return nrep;
930 }
931
932 //-------------------------disconnect_inputs-----------------------------------
933 // null out all inputs to eliminate incoming Def-Use edges.
934 void Node::disconnect_inputs(Compile* C) {
935 // the layout of Node::_in
936 // r: a required input, null is allowed
937 // p: a precedence, null values are all at the end
938 // -----------------------------------
939 // |r|...|r|p|...|p|null|...|null|
940 // | |
941 // req() len()
942 // -----------------------------------
943 for (uint i = 0; i < req(); ++i) {
944 if (in(i) != nullptr) {
945 set_req(i, nullptr);
946 }
947 }
948
949 // Remove precedence edges if any exist
950 // Note: Safepoints may have precedence edges, even during parsing
951 for (uint i = len(); i > req(); ) {
952 rm_prec(--i); // no-op if _in[i] is null
953 }
954
955 #ifdef ASSERT
956 // sanity check
957 for (uint i = 0; i < len(); ++i) {
958 assert(_in[i] == nullptr, "disconnect_inputs() failed!");
959 }
960 #endif
961
962 // Node::destruct requires all out edges be deleted first
963 // DEBUG_ONLY(destruct();) // no reuse benefit expected
964 C->record_dead_node(_idx);
965 }
966
967 //-----------------------------uncast---------------------------------------
968 // %%% Temporary, until we sort out CheckCastPP vs. CastPP.
969 // Strip away casting. (It is depth-limited.)
970 // Optionally, keep casts with dependencies.
971 Node* Node::uncast(bool keep_deps) const {
972 // Should be inline:
973 //return is_ConstraintCast() ? uncast_helper(this) : (Node*) this;
974 if (is_ConstraintCast()) {
975 return uncast_helper(this, keep_deps);
976 } else {
977 return (Node*) this;
978 }
979 }
980
981 // Find out of current node that matches opcode.
982 Node* Node::find_out_with(int opcode) {
983 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
984 Node* use = fast_out(i);
985 if (use->Opcode() == opcode) {
986 return use;
987 }
988 }
989 return nullptr;
990 }
991
992 // Return true if the current node has an out that matches opcode.
993 bool Node::has_out_with(int opcode) {
994 return (find_out_with(opcode) != nullptr);
995 }
996
997 // Return true if the current node has an out that matches any of the opcodes.
998 bool Node::has_out_with(int opcode1, int opcode2, int opcode3, int opcode4) {
999 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
1000 int opcode = fast_out(i)->Opcode();
1001 if (opcode == opcode1 || opcode == opcode2 || opcode == opcode3 || opcode == opcode4) {
1002 return true;
1003 }
1004 }
1005 return false;
1006 }
1007
1008
1009 //---------------------------uncast_helper-------------------------------------
1010 Node* Node::uncast_helper(const Node* p, bool keep_deps) {
1011 #ifdef ASSERT
1012 uint depth_count = 0;
1013 const Node* orig_p = p;
1014 #endif
1015
1016 while (true) {
1017 #ifdef ASSERT
1018 if (depth_count >= K) {
1019 orig_p->dump(4);
1020 if (p != orig_p)
1021 p->dump(1);
1022 }
1023 assert(depth_count++ < K, "infinite loop in Node::uncast_helper");
1024 #endif
1025 if (p == nullptr || p->req() != 2) {
1026 break;
1027 } else if (p->is_ConstraintCast()) {
1028 if (keep_deps && p->as_ConstraintCast()->carry_dependency()) {
1029 break; // stop at casts with dependencies
1030 }
1031 p = p->in(1);
1032 } else {
1033 break;
1034 }
1035 }
1036 return (Node*) p;
1037 }
1038
1039 //------------------------------add_prec---------------------------------------
1040 // Add a new precedence input. Precedence inputs are unordered, with
1041 // duplicates removed and nulls packed down at the end.
1042 void Node::add_prec( Node *n ) {
1043 assert( is_not_dead(n), "can not use dead node");
1044
1045 // Check for null at end
1046 if( _cnt >= _max || in(_max-1) )
1047 grow( _max+1 );
1048
1049 // Find a precedence edge to move
1050 uint i = _cnt;
1051 while( in(i) != nullptr ) {
1052 if (in(i) == n) return; // Avoid spec violation: duplicated prec edge.
1053 i++;
1054 }
1055 _in[i] = n; // Stuff prec edge over null
1056 if ( n != nullptr) n->add_out((Node *)this); // Add mirror edge
1057
1058 #ifdef ASSERT
1059 while ((++i)<_max) { assert(_in[i] == nullptr, "spec violation: Gap in prec edges (node %d)", _idx); }
1060 #endif
1061 Compile::current()->record_modified_node(this);
1062 }
1063
1064 //------------------------------rm_prec----------------------------------------
1065 // Remove a precedence input. Precedence inputs are unordered, with
1066 // duplicates removed and nulls packed down at the end.
1067 void Node::rm_prec( uint j ) {
1068 assert(j < _max, "oob: i=%d, _max=%d", j, _max);
1069 assert(j >= _cnt, "not a precedence edge");
1070 if (_in[j] == nullptr) return; // Avoid spec violation: Gap in prec edges.
1071 _in[j]->del_out((Node *)this);
1072 close_prec_gap_at(j);
1073 Compile::current()->record_modified_node(this);
1074 }
1075
1076 //------------------------------size_of----------------------------------------
1077 uint Node::size_of() const { return sizeof(*this); }
1078
1079 //------------------------------ideal_reg--------------------------------------
1080 uint Node::ideal_reg() const { return 0; }
1081
1082 //------------------------------jvms-------------------------------------------
1083 JVMState* Node::jvms() const { return nullptr; }
1084
1085 #ifdef ASSERT
1086 //------------------------------jvms-------------------------------------------
1087 bool Node::verify_jvms(const JVMState* using_jvms) const {
1088 for (JVMState* jvms = this->jvms(); jvms != nullptr; jvms = jvms->caller()) {
1089 if (jvms == using_jvms) return true;
1090 }
1091 return false;
1092 }
1093
1094 //------------------------------init_NodeProperty------------------------------
1095 void Node::init_NodeProperty() {
1096 assert(_max_classes <= max_juint, "too many NodeProperty classes");
1097 assert(max_flags() <= max_juint, "too many NodeProperty flags");
1098 }
1099
1100 //-----------------------------max_flags---------------------------------------
1101 juint Node::max_flags() {
1102 return (PD::_last_flag << 1) - 1; // allow flags combination
1103 }
1104 #endif
1105
1106 //------------------------------format-----------------------------------------
1107 // Print as assembly
1108 void Node::format( PhaseRegAlloc *, outputStream *st ) const {}
1109 //------------------------------emit-------------------------------------------
1110 // Emit bytes using C2_MacroAssembler
1111 void Node::emit(C2_MacroAssembler *masm, PhaseRegAlloc *ra_) const {}
1112 //------------------------------size-------------------------------------------
1113 // Size of instruction in bytes
1114 uint Node::size(PhaseRegAlloc *ra_) const { return 0; }
1115
1116 //------------------------------CFG Construction-------------------------------
1117 // Nodes that end basic blocks, e.g. IfTrue/IfFalse, JumpProjNode, Root,
1118 // Goto and Return.
1119 const Node *Node::is_block_proj() const { return nullptr; }
1120
1121 // Minimum guaranteed type
1122 const Type *Node::bottom_type() const { return Type::BOTTOM; }
1123
1124
1125 //------------------------------raise_bottom_type------------------------------
1126 // Get the worst-case Type output for this Node.
1127 void Node::raise_bottom_type(const Type* new_type) {
1128 if (is_Type()) {
1129 TypeNode *n = this->as_Type();
1130 if (VerifyAliases) {
1131 assert(new_type->higher_equal_speculative(n->type()), "new type must refine old type");
1132 }
1133 n->set_type(new_type);
1134 } else if (is_Load()) {
1135 LoadNode *n = this->as_Load();
1136 if (VerifyAliases) {
1137 assert(new_type->higher_equal_speculative(n->type()), "new type must refine old type");
1138 }
1139 n->set_type(new_type);
1140 }
1141 }
1142
1143 //------------------------------Identity---------------------------------------
1144 // Return a node that the given node is equivalent to.
1145 Node* Node::Identity(PhaseGVN* phase) {
1146 return this; // Default to no identities
1147 }
1148
1149 //------------------------------Value------------------------------------------
1150 // Compute a new Type for a node using the Type of the inputs.
1151 const Type* Node::Value(PhaseGVN* phase) const {
1152 return bottom_type(); // Default to worst-case Type
1153 }
1154
1155 //------------------------------Ideal------------------------------------------
1156 //
1157 // 'Idealize' the graph rooted at this Node.
1158 //
1159 // In order to be efficient and flexible there are some subtle invariants
1160 // these Ideal calls need to hold. Running with '-XX:VerifyIterativeGVN=1' checks
1161 // these invariants, although its too slow to have on by default. If you are
1162 // hacking an Ideal call, be sure to test with '-XX:VerifyIterativeGVN=1'
1163 //
1164 // The Ideal call almost arbitrarily reshape the graph rooted at the 'this'
1165 // pointer. If ANY change is made, it must return the root of the reshaped
1166 // graph - even if the root is the same Node. Example: swapping the inputs
1167 // to an AddINode gives the same answer and same root, but you still have to
1168 // return the 'this' pointer instead of null.
1169 //
1170 // You cannot return an OLD Node, except for the 'this' pointer. Use the
1171 // Identity call to return an old Node; basically if Identity can find
1172 // another Node have the Ideal call make no change and return null.
1173 // Example: AddINode::Ideal must check for add of zero; in this case it
1174 // returns null instead of doing any graph reshaping.
1175 //
1176 // You cannot modify any old Nodes except for the 'this' pointer. Due to
1177 // sharing there may be other users of the old Nodes relying on their current
1178 // semantics. Modifying them will break the other users.
1179 // Example: when reshape "(X+3)+4" into "X+7" you must leave the Node for
1180 // "X+3" unchanged in case it is shared.
1181 //
1182 // If you modify the 'this' pointer's inputs, you should use
1183 // 'set_req'. If you are making a new Node (either as the new root or
1184 // some new internal piece) you may use 'init_req' to set the initial
1185 // value. You can make a new Node with either 'new' or 'clone'. In
1186 // either case, def-use info is correctly maintained.
1187 //
1188 // Example: reshape "(X+3)+4" into "X+7":
1189 // set_req(1, in(1)->in(1));
1190 // set_req(2, phase->intcon(7));
1191 // return this;
1192 // Example: reshape "X*4" into "X<<2"
1193 // return new LShiftINode(in(1), phase->intcon(2));
1194 //
1195 // You must call 'phase->transform(X)' on any new Nodes X you make, except
1196 // for the returned root node. Example: reshape "X*31" with "(X<<5)-X".
1197 // Node *shift=phase->transform(new LShiftINode(in(1),phase->intcon(5)));
1198 // return new AddINode(shift, in(1));
1199 //
1200 // When making a Node for a constant use 'phase->makecon' or 'phase->intcon'.
1201 // These forms are faster than 'phase->transform(new ConNode())' and Do
1202 // The Right Thing with def-use info.
1203 //
1204 // You cannot bury the 'this' Node inside of a graph reshape. If the reshaped
1205 // graph uses the 'this' Node it must be the root. If you want a Node with
1206 // the same Opcode as the 'this' pointer use 'clone'.
1207 //
1208 Node *Node::Ideal(PhaseGVN *phase, bool can_reshape) {
1209 return nullptr; // Default to being Ideal already
1210 }
1211
1212 // Some nodes have specific Ideal subgraph transformations only if they are
1213 // unique users of specific nodes. Such nodes should be put on IGVN worklist
1214 // for the transformations to happen.
1215 bool Node::has_special_unique_user() const {
1216 assert(outcnt() == 1, "match only for unique out");
1217 Node* n = unique_out();
1218 int op = Opcode();
1219 if (this->is_Store()) {
1220 // Condition for back-to-back stores folding.
1221 return n->Opcode() == op && n->in(MemNode::Memory) == this;
1222 } else if (this->is_Load() || this->is_DecodeN() || this->is_Phi()) {
1223 // Condition for removing an unused LoadNode or DecodeNNode from the MemBarAcquire precedence input
1224 return n->Opcode() == Op_MemBarAcquire;
1225 } else if (op == Op_AddL) {
1226 // Condition for convL2I(addL(x,y)) ==> addI(convL2I(x),convL2I(y))
1227 return n->Opcode() == Op_ConvL2I && n->in(1) == this;
1228 } else if (op == Op_SubI || op == Op_SubL) {
1229 // Condition for subI(x,subI(y,z)) ==> subI(addI(x,z),y)
1230 return n->Opcode() == op && n->in(2) == this;
1231 } else if (is_If() && (n->is_IfFalse() || n->is_IfTrue())) {
1232 // See IfProjNode::Identity()
1233 return true;
1234 } else if ((is_IfFalse() || is_IfTrue()) && n->is_If()) {
1235 // See IfNode::fold_compares
1236 return true;
1237 } else if (n->Opcode() == Op_XorV || n->Opcode() == Op_XorVMask) {
1238 // Condition for XorVMask(VectorMaskCmp(x,y,cond), MaskAll(true)) ==> VectorMaskCmp(x,y,ncond)
1239 return true;
1240 } else {
1241 return false;
1242 }
1243 };
1244
1245 //--------------------------find_exact_control---------------------------------
1246 // Skip Proj and CatchProj nodes chains. Check for Null and Top.
1247 Node* Node::find_exact_control(Node* ctrl) {
1248 if (ctrl == nullptr && this->is_Region())
1249 ctrl = this->as_Region()->is_copy();
1250
1251 if (ctrl != nullptr && ctrl->is_CatchProj()) {
1252 if (ctrl->as_CatchProj()->_con == CatchProjNode::fall_through_index)
1253 ctrl = ctrl->in(0);
1254 if (ctrl != nullptr && !ctrl->is_top())
1255 ctrl = ctrl->in(0);
1256 }
1257
1258 if (ctrl != nullptr && ctrl->is_Proj())
1259 ctrl = ctrl->in(0);
1260
1261 return ctrl;
1262 }
1263
1264 //--------------------------dominates------------------------------------------
1265 // Helper function for MemNode::all_controls_dominate().
1266 // Check if 'this' control node dominates or equal to 'sub' control node.
1267 // We already know that if any path back to Root or Start reaches 'this',
1268 // then all paths so, so this is a simple search for one example,
1269 // not an exhaustive search for a counterexample.
1270 Node::DomResult Node::dominates(Node* sub, Node_List &nlist) {
1271 assert(this->is_CFG(), "expecting control");
1272 assert(sub != nullptr && sub->is_CFG(), "expecting control");
1273
1274 // detect dead cycle without regions
1275 int iterations_without_region_limit = DominatorSearchLimit;
1276
1277 Node* orig_sub = sub;
1278 Node* dom = this;
1279 bool met_dom = false;
1280 nlist.clear();
1281
1282 // Walk 'sub' backward up the chain to 'dom', watching for regions.
1283 // After seeing 'dom', continue up to Root or Start.
1284 // If we hit a region (backward split point), it may be a loop head.
1285 // Keep going through one of the region's inputs. If we reach the
1286 // same region again, go through a different input. Eventually we
1287 // will either exit through the loop head, or give up.
1288 // (If we get confused, break out and return a conservative 'false'.)
1289 while (sub != nullptr) {
1290 if (sub->is_top()) {
1291 // Conservative answer for dead code.
1292 return DomResult::EncounteredDeadCode;
1293 }
1294 if (sub == dom) {
1295 if (nlist.size() == 0) {
1296 // No Region nodes except loops were visited before and the EntryControl
1297 // path was taken for loops: it did not walk in a cycle.
1298 return DomResult::Dominate;
1299 } else if (met_dom) {
1300 break; // already met before: walk in a cycle
1301 } else {
1302 // Region nodes were visited. Continue walk up to Start or Root
1303 // to make sure that it did not walk in a cycle.
1304 met_dom = true; // first time meet
1305 iterations_without_region_limit = DominatorSearchLimit; // Reset
1306 }
1307 }
1308 if (sub->is_Start() || sub->is_Root()) {
1309 // Success if we met 'dom' along a path to Start or Root.
1310 // We assume there are no alternative paths that avoid 'dom'.
1311 // (This assumption is up to the caller to ensure!)
1312 return met_dom ? DomResult::Dominate : DomResult::NotDominate;
1313 }
1314 Node* up = sub->in(0);
1315 // Normalize simple pass-through regions and projections:
1316 up = sub->find_exact_control(up);
1317 // If sub == up, we found a self-loop. Try to push past it.
1318 if (sub == up && sub->is_Loop()) {
1319 // Take loop entry path on the way up to 'dom'.
1320 up = sub->in(1); // in(LoopNode::EntryControl);
1321 } else if (sub == up && sub->is_Region() && sub->req() == 2) {
1322 // Take in(1) path on the way up to 'dom' for regions with only one input
1323 up = sub->in(1);
1324 } else if (sub == up && sub->is_Region()) {
1325 // Try both paths for Regions with 2 input paths (it may be a loop head).
1326 // It could give conservative 'false' answer without information
1327 // which region's input is the entry path.
1328 iterations_without_region_limit = DominatorSearchLimit; // Reset
1329
1330 bool region_was_visited_before = false;
1331 // Was this Region node visited before?
1332 // If so, we have reached it because we accidentally took a
1333 // loop-back edge from 'sub' back into the body of the loop,
1334 // and worked our way up again to the loop header 'sub'.
1335 // So, take the first unexplored path on the way up to 'dom'.
1336 for (int j = nlist.size() - 1; j >= 0; j--) {
1337 intptr_t ni = (intptr_t)nlist.at(j);
1338 Node* visited = (Node*)(ni & ~1);
1339 bool visited_twice_already = ((ni & 1) != 0);
1340 if (visited == sub) {
1341 if (visited_twice_already) {
1342 // Visited 2 paths, but still stuck in loop body. Give up.
1343 return DomResult::NotDominate;
1344 }
1345 // The Region node was visited before only once.
1346 // (We will repush with the low bit set, below.)
1347 nlist.remove(j);
1348 // We will find a new edge and re-insert.
1349 region_was_visited_before = true;
1350 break;
1351 }
1352 }
1353
1354 // Find an incoming edge which has not been seen yet; walk through it.
1355 assert(up == sub, "");
1356 uint skip = region_was_visited_before ? 1 : 0;
1357 for (uint i = 1; i < sub->req(); i++) {
1358 Node* in = sub->in(i);
1359 if (in != nullptr && !in->is_top() && in != sub) {
1360 if (skip == 0) {
1361 up = in;
1362 break;
1363 }
1364 --skip; // skip this nontrivial input
1365 }
1366 }
1367
1368 // Set 0 bit to indicate that both paths were taken.
1369 nlist.push((Node*)((intptr_t)sub + (region_was_visited_before ? 1 : 0)));
1370 }
1371
1372 if (up == sub) {
1373 break; // some kind of tight cycle
1374 }
1375 if (up == orig_sub && met_dom) {
1376 // returned back after visiting 'dom'
1377 break; // some kind of cycle
1378 }
1379 if (--iterations_without_region_limit < 0) {
1380 break; // dead cycle
1381 }
1382 sub = up;
1383 }
1384
1385 // Did not meet Root or Start node in pred. chain.
1386 return DomResult::NotDominate;
1387 }
1388
1389 //------------------------------remove_dead_region-----------------------------
1390 // This control node is dead. Follow the subgraph below it making everything
1391 // using it dead as well. This will happen normally via the usual IterGVN
1392 // worklist but this call is more efficient. Do not update use-def info
1393 // inside the dead region, just at the borders.
1394 static void kill_dead_code( Node *dead, PhaseIterGVN *igvn ) {
1395 // Con's are a popular node to re-hit in the hash table again.
1396 if( dead->is_Con() ) return;
1397
1398 ResourceMark rm;
1399 Node_List nstack;
1400 VectorSet dead_set; // notify uses only once
1401
1402 Node *top = igvn->C->top();
1403 nstack.push(dead);
1404 bool has_irreducible_loop = igvn->C->has_irreducible_loop();
1405
1406 while (nstack.size() > 0) {
1407 dead = nstack.pop();
1408 if (!dead_set.test_set(dead->_idx)) {
1409 // If dead has any live uses, those are now still attached. Notify them before we lose them.
1410 igvn->add_users_to_worklist(dead);
1411 }
1412 if (dead->Opcode() == Op_SafePoint) {
1413 dead->as_SafePoint()->disconnect_from_root(igvn);
1414 }
1415 if (dead->outcnt() > 0) {
1416 // Keep dead node on stack until all uses are processed.
1417 nstack.push(dead);
1418 // For all Users of the Dead... ;-)
1419 for (DUIterator_Last kmin, k = dead->last_outs(kmin); k >= kmin; ) {
1420 Node* use = dead->last_out(k);
1421 igvn->hash_delete(use); // Yank from hash table prior to mod
1422 if (use->in(0) == dead) { // Found another dead node
1423 assert (!use->is_Con(), "Control for Con node should be Root node.");
1424 use->set_req(0, top); // Cut dead edge to prevent processing
1425 nstack.push(use); // the dead node again.
1426 } else if (!has_irreducible_loop && // Backedge could be alive in irreducible loop
1427 use->is_Loop() && !use->is_Root() && // Don't kill Root (RootNode extends LoopNode)
1428 use->in(LoopNode::EntryControl) == dead) { // Dead loop if its entry is dead
1429 use->set_req(LoopNode::EntryControl, top); // Cut dead edge to prevent processing
1430 use->set_req(0, top); // Cut self edge
1431 nstack.push(use);
1432 } else { // Else found a not-dead user
1433 // Dead if all inputs are top or null
1434 bool dead_use = !use->is_Root(); // Keep empty graph alive
1435 for (uint j = 1; j < use->req(); j++) {
1436 Node* in = use->in(j);
1437 if (in == dead) { // Turn all dead inputs into TOP
1438 use->set_req(j, top);
1439 } else if (in != nullptr && !in->is_top()) {
1440 dead_use = false;
1441 }
1442 }
1443 if (dead_use) {
1444 if (use->is_Region()) {
1445 use->set_req(0, top); // Cut self edge
1446 }
1447 nstack.push(use);
1448 } else {
1449 igvn->_worklist.push(use);
1450 }
1451 }
1452 // Refresh the iterator, since any number of kills might have happened.
1453 k = dead->last_outs(kmin);
1454 }
1455 } else { // (dead->outcnt() == 0)
1456 // Done with outputs.
1457 igvn->hash_delete(dead);
1458 igvn->_worklist.remove(dead);
1459 igvn->set_type(dead, Type::TOP);
1460 // Kill all inputs to the dead guy
1461 for (uint i=0; i < dead->req(); i++) {
1462 Node *n = dead->in(i); // Get input to dead guy
1463 if (n != nullptr && !n->is_top()) { // Input is valid?
1464 dead->set_req(i, top); // Smash input away
1465 if (n->outcnt() == 0) { // Input also goes dead?
1466 if (!n->is_Con())
1467 nstack.push(n); // Clear it out as well
1468 } else if (n->outcnt() == 1 &&
1469 n->has_special_unique_user()) {
1470 igvn->add_users_to_worklist( n );
1471 } else if (n->outcnt() <= 2 && n->is_Store()) {
1472 // Push store's uses on worklist to enable folding optimization for
1473 // store/store and store/load to the same address.
1474 // The restriction (outcnt() <= 2) is the same as in set_req_X()
1475 // and remove_globally_dead_node().
1476 igvn->add_users_to_worklist( n );
1477 } else if (dead->is_data_proj_of_pure_function(n)) {
1478 igvn->_worklist.push(n);
1479 } else {
1480 BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(igvn, n);
1481 }
1482 }
1483 }
1484 igvn->C->remove_useless_node(dead);
1485 } // (dead->outcnt() == 0)
1486 } // while (nstack.size() > 0) for outputs
1487 return;
1488 }
1489
1490 //------------------------------remove_dead_region-----------------------------
1491 bool Node::remove_dead_region(PhaseGVN *phase, bool can_reshape) {
1492 Node *n = in(0);
1493 if( !n ) return false;
1494 // Lost control into this guy? I.e., it became unreachable?
1495 // Aggressively kill all unreachable code.
1496 if (can_reshape && n->is_top()) {
1497 kill_dead_code(this, phase->is_IterGVN());
1498 return false; // Node is dead.
1499 }
1500
1501 if( n->is_Region() && n->as_Region()->is_copy() ) {
1502 Node *m = n->nonnull_req();
1503 set_req(0, m);
1504 return true;
1505 }
1506 return false;
1507 }
1508
1509 //------------------------------hash-------------------------------------------
1510 // Hash function over Nodes.
1511 uint Node::hash() const {
1512 uint sum = 0;
1513 for( uint i=0; i<_cnt; i++ ) // Add in all inputs
1514 sum = (sum<<1)-(uintptr_t)in(i); // Ignore embedded nulls
1515 return (sum>>2) + _cnt + Opcode();
1516 }
1517
1518 //------------------------------cmp--------------------------------------------
1519 // Compare special parts of simple Nodes
1520 bool Node::cmp( const Node &n ) const {
1521 return true; // Must be same
1522 }
1523
1524 //------------------------------rematerialize-----------------------------------
1525 // Should we clone rather than spill this instruction?
1526 bool Node::rematerialize() const {
1527 if ( is_Mach() )
1528 return this->as_Mach()->rematerialize();
1529 else
1530 return (_flags & Flag_rematerialize) != 0;
1531 }
1532
1533 //------------------------------needs_anti_dependence_check---------------------
1534 // Nodes which use memory without consuming it, hence need antidependences.
1535 bool Node::needs_anti_dependence_check() const {
1536 if (req() < 2 || (_flags & Flag_needs_anti_dependence_check) == 0) {
1537 return false;
1538 }
1539 return in(1)->bottom_type()->has_memory();
1540 }
1541
1542 // Get an integer constant from a ConNode (or CastIINode).
1543 // Return a default value if there is no apparent constant here.
1544 const TypeInt* Node::find_int_type() const {
1545 if (this->is_Type()) {
1546 return this->as_Type()->type()->isa_int();
1547 } else if (this->is_Con()) {
1548 assert(is_Mach(), "should be ConNode(TypeNode) or else a MachNode");
1549 return this->bottom_type()->isa_int();
1550 }
1551 return nullptr;
1552 }
1553
1554 const TypeInteger* Node::find_integer_type(BasicType bt) const {
1555 if (this->is_Type()) {
1556 return this->as_Type()->type()->isa_integer(bt);
1557 } else if (this->is_Con()) {
1558 assert(is_Mach(), "should be ConNode(TypeNode) or else a MachNode");
1559 return this->bottom_type()->isa_integer(bt);
1560 }
1561 return nullptr;
1562 }
1563
1564 // Get a pointer constant from a ConstNode.
1565 // Returns the constant if it is a pointer ConstNode
1566 intptr_t Node::get_ptr() const {
1567 assert( Opcode() == Op_ConP, "" );
1568 return ((ConPNode*)this)->type()->is_ptr()->get_con();
1569 }
1570
1571 // Get a narrow oop constant from a ConNNode.
1572 intptr_t Node::get_narrowcon() const {
1573 assert( Opcode() == Op_ConN, "" );
1574 return ((ConNNode*)this)->type()->is_narrowoop()->get_con();
1575 }
1576
1577 // Get a long constant from a ConNode.
1578 // Return a default value if there is no apparent constant here.
1579 const TypeLong* Node::find_long_type() const {
1580 if (this->is_Type()) {
1581 return this->as_Type()->type()->isa_long();
1582 } else if (this->is_Con()) {
1583 assert(is_Mach(), "should be ConNode(TypeNode) or else a MachNode");
1584 return this->bottom_type()->isa_long();
1585 }
1586 return nullptr;
1587 }
1588
1589
1590 /**
1591 * Return a ptr type for nodes which should have it.
1592 */
1593 const TypePtr* Node::get_ptr_type() const {
1594 const TypePtr* tp = this->bottom_type()->make_ptr();
1595 #ifdef ASSERT
1596 if (tp == nullptr) {
1597 this->dump(1);
1598 assert((tp != nullptr), "unexpected node type");
1599 }
1600 #endif
1601 return tp;
1602 }
1603
1604 // Get a double constant from a ConstNode.
1605 // Returns the constant if it is a double ConstNode
1606 jdouble Node::getd() const {
1607 assert( Opcode() == Op_ConD, "" );
1608 return ((ConDNode*)this)->type()->is_double_constant()->getd();
1609 }
1610
1611 // Get a float constant from a ConstNode.
1612 // Returns the constant if it is a float ConstNode
1613 jfloat Node::getf() const {
1614 assert( Opcode() == Op_ConF, "" );
1615 return ((ConFNode*)this)->type()->is_float_constant()->getf();
1616 }
1617
1618 // Get a half float constant from a ConstNode.
1619 // Returns the constant if it is a float ConstNode
1620 jshort Node::geth() const {
1621 assert( Opcode() == Op_ConH, "" );
1622 return ((ConHNode*)this)->type()->is_half_float_constant()->geth();
1623 }
1624
1625 #ifndef PRODUCT
1626
1627 // Call this from debugger:
1628 Node* old_root() {
1629 Matcher* matcher = Compile::current()->matcher();
1630 if (matcher != nullptr) {
1631 Node* new_root = Compile::current()->root();
1632 Node* old_root = matcher->find_old_node(new_root);
1633 if (old_root != nullptr) {
1634 return old_root;
1635 }
1636 }
1637 tty->print("old_root: not found.\n");
1638 return nullptr;
1639 }
1640
1641 // BFS traverse all reachable nodes from start, call callback on them
1642 template <typename Callback>
1643 void visit_nodes(Node* start, Callback callback, bool traverse_output, bool only_ctrl) {
1644 Unique_Mixed_Node_List worklist;
1645 worklist.add(start);
1646 for (uint i = 0; i < worklist.size(); i++) {
1647 Node* n = worklist[i];
1648 callback(n);
1649 for (uint i = 0; i < n->len(); i++) {
1650 if (!only_ctrl || n->is_Region() || (n->Opcode() == Op_Root) || (i == TypeFunc::Control)) {
1651 // If only_ctrl is set: Add regions, the root node, or control inputs only
1652 worklist.add(n->in(i));
1653 }
1654 }
1655 if (traverse_output && !only_ctrl) {
1656 for (uint i = 0; i < n->outcnt(); i++) {
1657 worklist.add(n->raw_out(i));
1658 }
1659 }
1660 }
1661 }
1662
1663 // BFS traverse from start, return node with idx
1664 static Node* find_node_by_idx(Node* start, uint idx, bool traverse_output, bool only_ctrl) {
1665 ResourceMark rm;
1666 Node* result = nullptr;
1667 auto callback = [&] (Node* n) {
1668 if (n->_idx == idx) {
1669 if (result != nullptr) {
1670 tty->print("find_node_by_idx: " INTPTR_FORMAT " and " INTPTR_FORMAT " both have idx==%d\n",
1671 (uintptr_t)result, (uintptr_t)n, idx);
1672 }
1673 result = n;
1674 }
1675 };
1676 visit_nodes(start, callback, traverse_output, only_ctrl);
1677 return result;
1678 }
1679
1680 static int node_idx_cmp(const Node** n1, const Node** n2) {
1681 return (*n1)->_idx - (*n2)->_idx;
1682 }
1683
1684 static void find_nodes_by_name(Node* start, const char* name) {
1685 ResourceMark rm;
1686 GrowableArray<const Node*> ns;
1687 auto callback = [&] (const Node* n) {
1688 if (StringUtils::is_star_match(name, n->Name())) {
1689 ns.push(n);
1690 }
1691 };
1692 visit_nodes(start, callback, true, false);
1693 ns.sort(node_idx_cmp);
1694 for (int i = 0; i < ns.length(); i++) {
1695 ns.at(i)->dump();
1696 }
1697 }
1698
1699 static void find_nodes_by_dump(Node* start, const char* pattern) {
1700 ResourceMark rm;
1701 GrowableArray<const Node*> ns;
1702 auto callback = [&] (const Node* n) {
1703 stringStream stream;
1704 n->dump("", false, &stream);
1705 if (StringUtils::is_star_match(pattern, stream.base())) {
1706 ns.push(n);
1707 }
1708 };
1709 visit_nodes(start, callback, true, false);
1710 ns.sort(node_idx_cmp);
1711 for (int i = 0; i < ns.length(); i++) {
1712 ns.at(i)->dump();
1713 }
1714 }
1715
1716 // call from debugger: find node with name pattern in new/current graph
1717 // name can contain "*" in match pattern to match any characters
1718 // the matching is case insensitive
1719 void find_nodes_by_name(const char* name) {
1720 Node* root = Compile::current()->root();
1721 find_nodes_by_name(root, name);
1722 }
1723
1724 // call from debugger: find node with name pattern in old graph
1725 // name can contain "*" in match pattern to match any characters
1726 // the matching is case insensitive
1727 void find_old_nodes_by_name(const char* name) {
1728 Node* root = old_root();
1729 find_nodes_by_name(root, name);
1730 }
1731
1732 // call from debugger: find node with dump pattern in new/current graph
1733 // can contain "*" in match pattern to match any characters
1734 // the matching is case insensitive
1735 void find_nodes_by_dump(const char* pattern) {
1736 Node* root = Compile::current()->root();
1737 find_nodes_by_dump(root, pattern);
1738 }
1739
1740 // call from debugger: find node with name pattern in old graph
1741 // can contain "*" in match pattern to match any characters
1742 // the matching is case insensitive
1743 void find_old_nodes_by_dump(const char* pattern) {
1744 Node* root = old_root();
1745 find_nodes_by_dump(root, pattern);
1746 }
1747
1748 // Call this from debugger, search in same graph as n:
1749 Node* find_node(Node* n, const int idx) {
1750 return n->find(idx);
1751 }
1752
1753 // Call this from debugger, search in new nodes:
1754 Node* find_node(const int idx) {
1755 return Compile::current()->root()->find(idx);
1756 }
1757
1758 // Call this from debugger, search in old nodes:
1759 Node* find_old_node(const int idx) {
1760 Node* root = old_root();
1761 return (root == nullptr) ? nullptr : root->find(idx);
1762 }
1763
1764 // Call this from debugger, search in same graph as n:
1765 Node* find_ctrl(Node* n, const int idx) {
1766 return n->find_ctrl(idx);
1767 }
1768
1769 // Call this from debugger, search in new nodes:
1770 Node* find_ctrl(const int idx) {
1771 return Compile::current()->root()->find_ctrl(idx);
1772 }
1773
1774 // Call this from debugger, search in old nodes:
1775 Node* find_old_ctrl(const int idx) {
1776 Node* root = old_root();
1777 return (root == nullptr) ? nullptr : root->find_ctrl(idx);
1778 }
1779
1780 //------------------------------find_ctrl--------------------------------------
1781 // Find an ancestor to this node in the control history with given _idx
1782 Node* Node::find_ctrl(int idx) {
1783 return find(idx, true);
1784 }
1785
1786 //------------------------------find-------------------------------------------
1787 // Tries to find the node with the index |idx| starting from this node. If idx is negative,
1788 // the search also includes forward (out) edges. Returns null if not found.
1789 // If only_ctrl is set, the search will only be done on control nodes. Returns null if
1790 // not found or if the node to be found is not a control node (search will not find it).
1791 Node* Node::find(const int idx, bool only_ctrl) {
1792 ResourceMark rm;
1793 return find_node_by_idx(this, abs(idx), (idx < 0), only_ctrl);
1794 }
1795
1796 class PrintBFS {
1797 public:
1798 PrintBFS(const Node* start, const int max_distance, const Node* target, const char* options, outputStream* st, const frame* fr)
1799 : _start(start), _max_distance(max_distance), _target(target), _options(options), _output(st), _frame(fr),
1800 _dcc(this), _info_uid(cmpkey, hashkey) {}
1801
1802 void run();
1803 private:
1804 // pipeline steps
1805 bool configure();
1806 void collect();
1807 void select();
1808 void select_all();
1809 void select_all_paths();
1810 void select_shortest_path();
1811 void sort();
1812 void print();
1813
1814 // inputs
1815 const Node* _start;
1816 const int _max_distance;
1817 const Node* _target;
1818 const char* _options;
1819 outputStream* _output;
1820 const frame* _frame;
1821
1822 // options
1823 bool _traverse_inputs = false;
1824 bool _traverse_outputs = false;
1825 struct Filter {
1826 bool _control = false;
1827 bool _memory = false;
1828 bool _data = false;
1829 bool _mixed = false;
1830 bool _other = false;
1831 bool is_empty() const {
1832 return !(_control || _memory || _data || _mixed || _other);
1833 }
1834 void set_all() {
1835 _control = true;
1836 _memory = true;
1837 _data = true;
1838 _mixed = true;
1839 _other = true;
1840 }
1841 // Check if the filter accepts the node. Go by the type categories, but also all CFG nodes
1842 // are considered to have control.
1843 bool accepts(const Node* n) {
1844 const Type* t = n->bottom_type();
1845 return ( _data && t->has_category(Type::Category::Data) ) ||
1846 ( _memory && t->has_category(Type::Category::Memory) ) ||
1847 ( _mixed && t->has_category(Type::Category::Mixed) ) ||
1848 ( _control && (t->has_category(Type::Category::Control) || n->is_CFG()) ) ||
1849 ( _other && t->has_category(Type::Category::Other) );
1850 }
1851 };
1852 Filter _filter_visit;
1853 Filter _filter_boundary;
1854 bool _sort_idx = false;
1855 bool _all_paths = false;
1856 bool _use_color = false;
1857 bool _print_blocks = false;
1858 bool _print_old = false;
1859 bool _dump_only = false;
1860 bool _print_igv = false;
1861
1862 void print_options_help(bool print_examples);
1863 bool parse_options();
1864
1865 public:
1866 class DumpConfigColored : public Node::DumpConfig {
1867 public:
1868 DumpConfigColored(PrintBFS* bfs) : _bfs(bfs) {};
1869 virtual void pre_dump(outputStream* st, const Node* n);
1870 virtual void post_dump(outputStream* st);
1871 private:
1872 PrintBFS* _bfs;
1873 };
1874 private:
1875 DumpConfigColored _dcc;
1876
1877 // node info
1878 static Node* old_node(const Node* n); // mach node -> prior IR node
1879 void print_node_idx(const Node* n);
1880 void print_block_id(const Block* b);
1881 void print_node_block(const Node* n); // _pre_order, head idx, _idom, _dom_depth
1882
1883 // traversal data structures
1884 GrowableArray<const Node*> _worklist; // BFS queue
1885 void maybe_traverse(const Node* src, const Node* dst);
1886
1887 // node info annotation
1888 class Info {
1889 public:
1890 Info() : Info(nullptr, 0) {};
1891 Info(const Node* node, int distance)
1892 : _node(node), _distance_from_start(distance) {};
1893 const Node* node() const { return _node; };
1894 int distance() const { return _distance_from_start; };
1895 int distance_from_target() const { return _distance_from_target; }
1896 void set_distance_from_target(int d) { _distance_from_target = d; }
1897 GrowableArray<const Node*> edge_bwd; // pointing toward _start
1898 bool is_marked() const { return _mark; } // marked to keep during select
1899 void set_mark() { _mark = true; }
1900 private:
1901 const Node* _node;
1902 int _distance_from_start; // distance from _start
1903 int _distance_from_target = 0; // distance from _target if _all_paths
1904 bool _mark = false;
1905 };
1906 Dict _info_uid; // Node -> uid
1907 GrowableArray<Info> _info; // uid -> info
1908
1909 Info* find_info(const Node* n) {
1910 size_t uid = (size_t)_info_uid[n];
1911 if (uid == 0) {
1912 return nullptr;
1913 }
1914 return &_info.at((int)uid);
1915 }
1916
1917 void make_info(const Node* node, const int distance) {
1918 assert(find_info(node) == nullptr, "node does not yet have info");
1919 size_t uid = _info.length() + 1;
1920 _info_uid.Insert((void*)node, (void*)uid);
1921 _info.at_put_grow((int)uid, Info(node, distance));
1922 assert(find_info(node)->node() == node, "stored correct node");
1923 };
1924
1925 // filled by sort, printed by print
1926 GrowableArray<const Node*> _print_list;
1927
1928 // print header + node table
1929 void print_header() const;
1930 void print_node(const Node* n);
1931 };
1932
1933 void PrintBFS::run() {
1934 if (!configure()) {
1935 return;
1936 }
1937 collect();
1938 select();
1939 sort();
1940 print();
1941 }
1942
1943 // set up configuration for BFS and print
1944 bool PrintBFS::configure() {
1945 if (_max_distance < 0) {
1946 _output->print_cr("dump_bfs: max_distance must be non-negative!");
1947 return false;
1948 }
1949 return parse_options();
1950 }
1951
1952 // BFS traverse according to configuration, fill worklist and info
1953 void PrintBFS::collect() {
1954 maybe_traverse(_start, _start);
1955 int pos = 0;
1956 while (pos < _worklist.length()) {
1957 const Node* n = _worklist.at(pos++); // next node to traverse
1958 Info* info = find_info(n);
1959 if (!_filter_visit.accepts(n) && n != _start) {
1960 continue; // we hit boundary, do not traverse further
1961 }
1962 if (n != _start && n->is_Root()) {
1963 continue; // traversing through root node would lead to unrelated nodes
1964 }
1965 if (_traverse_inputs && _max_distance > info->distance()) {
1966 for (uint i = 0; i < n->req(); i++) {
1967 maybe_traverse(n, n->in(i));
1968 }
1969 }
1970 if (_traverse_outputs && _max_distance > info->distance()) {
1971 for (uint i = 0; i < n->outcnt(); i++) {
1972 maybe_traverse(n, n->raw_out(i));
1973 }
1974 }
1975 }
1976 }
1977
1978 // go through work list, mark those that we want to print
1979 void PrintBFS::select() {
1980 if (_target == nullptr ) {
1981 select_all();
1982 } else {
1983 if (find_info(_target) == nullptr) {
1984 _output->print_cr("Could not find target in BFS.");
1985 return;
1986 }
1987 if (_all_paths) {
1988 select_all_paths();
1989 } else {
1990 select_shortest_path();
1991 }
1992 }
1993 }
1994
1995 // take all nodes from BFS
1996 void PrintBFS::select_all() {
1997 for (int i = 0; i < _worklist.length(); i++) {
1998 const Node* n = _worklist.at(i);
1999 Info* info = find_info(n);
2000 info->set_mark();
2001 }
2002 }
2003
2004 // traverse backward from target, along edges found in BFS
2005 void PrintBFS::select_all_paths() {
2006 int pos = 0;
2007 GrowableArray<const Node*> backtrace;
2008 // start from target
2009 backtrace.push(_target);
2010 find_info(_target)->set_mark();
2011 // traverse backward
2012 while (pos < backtrace.length()) {
2013 const Node* n = backtrace.at(pos++);
2014 Info* info = find_info(n);
2015 for (int i = 0; i < info->edge_bwd.length(); i++) {
2016 // all backward edges
2017 const Node* back = info->edge_bwd.at(i);
2018 Info* back_info = find_info(back);
2019 if (!back_info->is_marked()) {
2020 // not yet found this on way back.
2021 back_info->set_distance_from_target(info->distance_from_target() + 1);
2022 if (back_info->distance_from_target() + back_info->distance() <= _max_distance) {
2023 // total distance is small enough
2024 back_info->set_mark();
2025 backtrace.push(back);
2026 }
2027 }
2028 }
2029 }
2030 }
2031
2032 void PrintBFS::select_shortest_path() {
2033 const Node* current = _target;
2034 while (true) {
2035 Info* info = find_info(current);
2036 info->set_mark();
2037 if (current == _start) {
2038 break;
2039 }
2040 // first edge -> leads us one step closer to _start
2041 current = info->edge_bwd.at(0);
2042 }
2043 }
2044
2045 // go through worklist in desired order, put the marked ones in print list
2046 void PrintBFS::sort() {
2047 if (_traverse_inputs && !_traverse_outputs) {
2048 // reverse order
2049 for (int i = _worklist.length() - 1; i >= 0; i--) {
2050 const Node* n = _worklist.at(i);
2051 Info* info = find_info(n);
2052 if (info->is_marked()) {
2053 _print_list.push(n);
2054 }
2055 }
2056 } else {
2057 // same order as worklist
2058 for (int i = 0; i < _worklist.length(); i++) {
2059 const Node* n = _worklist.at(i);
2060 Info* info = find_info(n);
2061 if (info->is_marked()) {
2062 _print_list.push(n);
2063 }
2064 }
2065 }
2066 if (_sort_idx) {
2067 _print_list.sort(node_idx_cmp);
2068 }
2069 }
2070
2071 // go through printlist and print
2072 void PrintBFS::print() {
2073 if (_print_list.length() > 0 ) {
2074 print_header();
2075 for (int i = 0; i < _print_list.length(); i++) {
2076 const Node* n = _print_list.at(i);
2077 print_node(n);
2078 }
2079 if (_print_igv) {
2080 Compile* C = Compile::current();
2081 C->init_igv();
2082 C->igv_print_graph_to_network(nullptr, _print_list, _frame);
2083 }
2084 } else {
2085 _output->print_cr("No nodes to print.");
2086 }
2087 }
2088
2089 void PrintBFS::print_options_help(bool print_examples) {
2090 _output->print_cr("Usage: node->dump_bfs(int max_distance, Node* target, char* options)");
2091 _output->print_cr("");
2092 _output->print_cr("Use cases:");
2093 _output->print_cr(" BFS traversal: no target required");
2094 _output->print_cr(" shortest path: set target");
2095 _output->print_cr(" all paths: set target and put 'A' in options");
2096 _output->print_cr(" detect loop: subcase of all paths, have start==target");
2097 _output->print_cr("");
2098 _output->print_cr("Arguments:");
2099 _output->print_cr(" this/start: staring point of BFS");
2100 _output->print_cr(" target:");
2101 _output->print_cr(" if null: simple BFS");
2102 _output->print_cr(" else: shortest path or all paths between this/start and target");
2103 _output->print_cr(" options:");
2104 _output->print_cr(" if null: same as \"cdmox@B\"");
2105 _output->print_cr(" else: use combination of following characters");
2106 _output->print_cr(" h: display this help info");
2107 _output->print_cr(" H: display this help info, with examples");
2108 _output->print_cr(" +: traverse in-edges (on if neither + nor -)");
2109 _output->print_cr(" -: traverse out-edges");
2110 _output->print_cr(" c: visit control nodes");
2111 _output->print_cr(" d: visit data nodes");
2112 _output->print_cr(" m: visit memory nodes");
2113 _output->print_cr(" o: visit other nodes");
2114 _output->print_cr(" x: visit mixed nodes");
2115 _output->print_cr(" C: boundary control nodes");
2116 _output->print_cr(" D: boundary data nodes");
2117 _output->print_cr(" M: boundary memory nodes");
2118 _output->print_cr(" O: boundary other nodes");
2119 _output->print_cr(" X: boundary mixed nodes");
2120 _output->print_cr(" #: display node category in color (not supported in all terminals)");
2121 _output->print_cr(" S: sort displayed nodes by node idx");
2122 _output->print_cr(" A: all paths (not just shortest path to target)");
2123 _output->print_cr(" @: print old nodes - before matching (if available)");
2124 _output->print_cr(" B: print scheduling blocks (if available)");
2125 _output->print_cr(" $: dump only, no header, no other columns");
2126 _output->print_cr(" !: show nodes on IGV (sent over network stream)");
2127 _output->print_cr(" (use preferably with dump_bfs(int, Node*, char*, void*, void*, void*)");
2128 _output->print_cr(" to produce a C2 stack trace along with the graph dump, see examples below)");
2129 _output->print_cr("");
2130 _output->print_cr("recursively follow edges to nodes with permitted visit types,");
2131 _output->print_cr("on the boundary additionally display nodes allowed in boundary types");
2132 _output->print_cr("Note: the categories can be overlapping. For example a mixed node");
2133 _output->print_cr(" can contain control and memory output. Some from the other");
2134 _output->print_cr(" category are also control (Halt, Return, etc).");
2135 _output->print_cr("");
2136 _output->print_cr("output columns:");
2137 _output->print_cr(" dist: BFS distance to this/start");
2138 _output->print_cr(" apd: all paths distance (d_outputart + d_target)");
2139 _output->print_cr(" block: block identifier, based on _pre_order");
2140 _output->print_cr(" head: first node in block");
2141 _output->print_cr(" idom: head node of idom block");
2142 _output->print_cr(" depth: depth of block (_dom_depth)");
2143 _output->print_cr(" old: old IR node - before matching");
2144 _output->print_cr(" dump: node->dump()");
2145 _output->print_cr("");
2146 _output->print_cr("Note: if none of the \"cmdxo\" characters are in the options string");
2147 _output->print_cr(" then we set all of them.");
2148 _output->print_cr(" This allows for short strings like \"#\" for colored input traversal");
2149 _output->print_cr(" or \"-#\" for colored output traversal.");
2150 if (print_examples) {
2151 _output->print_cr("");
2152 _output->print_cr("Examples:");
2153 _output->print_cr(" if->dump_bfs(10, 0, \"+cxo\")");
2154 _output->print_cr(" starting at some if node, traverse inputs recursively");
2155 _output->print_cr(" only along control (mixed and other can also be control)");
2156 _output->print_cr(" phi->dump_bfs(5, 0, \"-dxo\")");
2157 _output->print_cr(" starting at phi node, traverse outputs recursively");
2158 _output->print_cr(" only along data (mixed and other can also have data flow)");
2159 _output->print_cr(" find_node(385)->dump_bfs(3, 0, \"cdmox+#@B\")");
2160 _output->print_cr(" find inputs of node 385, up to 3 nodes up (+)");
2161 _output->print_cr(" traverse all nodes (cdmox), use colors (#)");
2162 _output->print_cr(" display old nodes and blocks, if they exist");
2163 _output->print_cr(" useful call to start with");
2164 _output->print_cr(" find_node(102)->dump_bfs(10, 0, \"dCDMOX-\")");
2165 _output->print_cr(" find non-data dependencies of a data node");
2166 _output->print_cr(" follow data node outputs until we find another category");
2167 _output->print_cr(" node as the boundary");
2168 _output->print_cr(" x->dump_bfs(10, y, 0)");
2169 _output->print_cr(" find shortest path from x to y, along any edge or node");
2170 _output->print_cr(" will not find a path if it is longer than 10");
2171 _output->print_cr(" useful to find how x and y are related");
2172 _output->print_cr(" find_node(741)->dump_bfs(20, find_node(746), \"c+\")");
2173 _output->print_cr(" find shortest control path between two nodes");
2174 _output->print_cr(" find_node(741)->dump_bfs(8, find_node(746), \"cdmox+A\")");
2175 _output->print_cr(" find all paths (A) between two nodes of length at most 8");
2176 _output->print_cr(" find_node(741)->dump_bfs(7, find_node(741), \"c+A\")");
2177 _output->print_cr(" find all control loops for this node");
2178 _output->print_cr(" find_node(741)->dump_bfs(7, find_node(741), \"c+A!\", $sp, $fp, $pc)");
2179 _output->print_cr(" same as above, but printing the resulting subgraph");
2180 _output->print_cr(" along with a C2 stack trace on IGV");
2181 }
2182 }
2183
2184 bool PrintBFS::parse_options() {
2185 if (_options == nullptr) {
2186 _options = "cdmox@B"; // default options
2187 }
2188 size_t len = strlen(_options);
2189 for (size_t i = 0; i < len; i++) {
2190 switch (_options[i]) {
2191 case '+':
2192 _traverse_inputs = true;
2193 break;
2194 case '-':
2195 _traverse_outputs = true;
2196 break;
2197 case 'c':
2198 _filter_visit._control = true;
2199 break;
2200 case 'm':
2201 _filter_visit._memory = true;
2202 break;
2203 case 'd':
2204 _filter_visit._data = true;
2205 break;
2206 case 'x':
2207 _filter_visit._mixed = true;
2208 break;
2209 case 'o':
2210 _filter_visit._other = true;
2211 break;
2212 case 'C':
2213 _filter_boundary._control = true;
2214 break;
2215 case 'M':
2216 _filter_boundary._memory = true;
2217 break;
2218 case 'D':
2219 _filter_boundary._data = true;
2220 break;
2221 case 'X':
2222 _filter_boundary._mixed = true;
2223 break;
2224 case 'O':
2225 _filter_boundary._other = true;
2226 break;
2227 case 'S':
2228 _sort_idx = true;
2229 break;
2230 case 'A':
2231 _all_paths = true;
2232 break;
2233 case '#':
2234 _use_color = true;
2235 break;
2236 case 'B':
2237 _print_blocks = true;
2238 break;
2239 case '@':
2240 _print_old = true;
2241 break;
2242 case '$':
2243 _dump_only = true;
2244 break;
2245 case '!':
2246 _print_igv = true;
2247 break;
2248 case 'h':
2249 print_options_help(false);
2250 return false;
2251 case 'H':
2252 print_options_help(true);
2253 return false;
2254 default:
2255 _output->print_cr("dump_bfs: Unrecognized option \'%c\'", _options[i]);
2256 _output->print_cr("for help, run: find_node(0)->dump_bfs(0,0,\"H\")");
2257 return false;
2258 }
2259 }
2260 if (!_traverse_inputs && !_traverse_outputs) {
2261 _traverse_inputs = true;
2262 }
2263 if (_filter_visit.is_empty()) {
2264 _filter_visit.set_all();
2265 }
2266 Compile* C = Compile::current();
2267 _print_old &= (C->matcher() != nullptr); // only show old if there are new
2268 _print_blocks &= (C->cfg() != nullptr); // only show blocks if available
2269 return true;
2270 }
2271
2272 void PrintBFS::DumpConfigColored::pre_dump(outputStream* st, const Node* n) {
2273 if (!_bfs->_use_color) {
2274 return;
2275 }
2276 Info* info = _bfs->find_info(n);
2277 if (info == nullptr || !info->is_marked()) {
2278 return;
2279 }
2280
2281 const Type* t = n->bottom_type();
2282 switch (t->category()) {
2283 case Type::Category::Data:
2284 st->print("\u001b[34m");
2285 break;
2286 case Type::Category::Memory:
2287 st->print("\u001b[32m");
2288 break;
2289 case Type::Category::Mixed:
2290 st->print("\u001b[35m");
2291 break;
2292 case Type::Category::Control:
2293 st->print("\u001b[31m");
2294 break;
2295 case Type::Category::Other:
2296 st->print("\u001b[33m");
2297 break;
2298 case Type::Category::Undef:
2299 n->dump();
2300 assert(false, "category undef ??");
2301 break;
2302 default:
2303 n->dump();
2304 assert(false, "not covered");
2305 break;
2306 }
2307 }
2308
2309 void PrintBFS::DumpConfigColored::post_dump(outputStream* st) {
2310 if (!_bfs->_use_color) {
2311 return;
2312 }
2313 st->print("\u001b[0m"); // white
2314 }
2315
2316 Node* PrintBFS::old_node(const Node* n) {
2317 Compile* C = Compile::current();
2318 if (C->matcher() == nullptr || !C->node_arena()->contains(n)) {
2319 return (Node*)nullptr;
2320 } else {
2321 return C->matcher()->find_old_node(n);
2322 }
2323 }
2324
2325 void PrintBFS::print_node_idx(const Node* n) {
2326 Compile* C = Compile::current();
2327 char buf[30];
2328 if (n == nullptr) {
2329 os::snprintf_checked(buf, sizeof(buf), "_"); // null
2330 } else if (C->node_arena()->contains(n)) {
2331 os::snprintf_checked(buf, sizeof(buf), "%d", n->_idx); // new node
2332 } else {
2333 os::snprintf_checked(buf, sizeof(buf), "o%d", n->_idx); // old node
2334 }
2335 _output->print("%6s", buf);
2336 }
2337
2338 void PrintBFS::print_block_id(const Block* b) {
2339 Compile* C = Compile::current();
2340 char buf[30];
2341 os::snprintf_checked(buf, sizeof(buf), "B%d", b->_pre_order);
2342 _output->print("%7s", buf);
2343 }
2344
2345 void PrintBFS::print_node_block(const Node* n) {
2346 Compile* C = Compile::current();
2347 Block* b = C->node_arena()->contains(n)
2348 ? C->cfg()->get_block_for_node(n)
2349 : nullptr; // guard against old nodes
2350 if (b == nullptr) {
2351 _output->print(" _"); // Block
2352 _output->print(" _"); // head
2353 _output->print(" _"); // idom
2354 _output->print(" _"); // depth
2355 } else {
2356 print_block_id(b);
2357 print_node_idx(b->head());
2358 if (b->_idom) {
2359 print_node_idx(b->_idom->head());
2360 } else {
2361 _output->print(" _"); // idom
2362 }
2363 _output->print("%6d ", b->_dom_depth);
2364 }
2365 }
2366
2367 // filter, and add to worklist, add info, note traversal edges
2368 void PrintBFS::maybe_traverse(const Node* src, const Node* dst) {
2369 if (dst != nullptr &&
2370 (_filter_visit.accepts(dst) ||
2371 _filter_boundary.accepts(dst) ||
2372 dst == _start)) { // correct category or start?
2373 if (find_info(dst) == nullptr) {
2374 // never visited - set up info
2375 _worklist.push(dst);
2376 int d = 0;
2377 if (dst != _start) {
2378 d = find_info(src)->distance() + 1;
2379 }
2380 make_info(dst, d);
2381 }
2382 if (src != dst) {
2383 // traversal edges useful during select
2384 find_info(dst)->edge_bwd.push(src);
2385 }
2386 }
2387 }
2388
2389 void PrintBFS::print_header() const {
2390 if (_dump_only) {
2391 return; // no header in dump only mode
2392 }
2393 _output->print("dist"); // distance
2394 if (_all_paths) {
2395 _output->print(" apd"); // all paths distance
2396 }
2397 if (_print_blocks) {
2398 _output->print(" [block head idom depth]"); // block
2399 }
2400 if (_print_old) {
2401 _output->print(" old"); // old node
2402 }
2403 _output->print(" dump\n"); // node dump
2404 _output->print_cr("---------------------------------------------");
2405 }
2406
2407 void PrintBFS::print_node(const Node* n) {
2408 if (_dump_only) {
2409 n->dump("\n", false, _output, &_dcc);
2410 return;
2411 }
2412 _output->print("%4d", find_info(n)->distance());// distance
2413 if (_all_paths) {
2414 Info* info = find_info(n);
2415 int apd = info->distance() + info->distance_from_target();
2416 _output->print("%4d", apd); // all paths distance
2417 }
2418 if (_print_blocks) {
2419 print_node_block(n); // block
2420 }
2421 if (_print_old) {
2422 print_node_idx(old_node(n)); // old node
2423 }
2424 _output->print(" ");
2425 n->dump("\n", false, _output, &_dcc); // node dump
2426 }
2427
2428 //------------------------------dump_bfs--------------------------------------
2429 // Call this from debugger
2430 // Useful for BFS traversal, shortest path, all path, loop detection, etc
2431 // Designed to be more readable, and provide additional info
2432 // To find all options, run:
2433 // find_node(0)->dump_bfs(0,0,"H")
2434 void Node::dump_bfs(const int max_distance, Node* target, const char* options) const {
2435 dump_bfs(max_distance, target, options, tty);
2436 }
2437
2438 // Used to dump to stream.
2439 void Node::dump_bfs(const int max_distance, Node* target, const char* options, outputStream* st, const frame* fr) const {
2440 PrintBFS bfs(this, max_distance, target, options, st, fr);
2441 bfs.run();
2442 }
2443
2444 // Call this from debugger, with default arguments
2445 void Node::dump_bfs(const int max_distance) const {
2446 dump_bfs(max_distance, nullptr, nullptr);
2447 }
2448
2449 // Call this from debugger, with stack handling register arguments for IGV dumps.
2450 // Example: p find_node(741)->dump_bfs(7, find_node(741), "c+A!", $sp, $fp, $pc).
2451 void Node::dump_bfs(const int max_distance, Node* target, const char* options, void* sp, void* fp, void* pc) const {
2452 frame fr(sp, fp, pc);
2453 dump_bfs(max_distance, target, options, tty, &fr);
2454 }
2455
2456 // -----------------------------dump_idx---------------------------------------
2457 void Node::dump_idx(bool align, outputStream* st, DumpConfig* dc) const {
2458 if (dc != nullptr) {
2459 dc->pre_dump(st, this);
2460 }
2461 Compile* C = Compile::current();
2462 bool is_new = C->node_arena()->contains(this);
2463 if (align) { // print prefix empty spaces$
2464 // +1 for leading digit, +1 for "o"
2465 uint max_width = (C->unique() == 0 ? 0 : static_cast<uint>(log10(static_cast<double>(C->unique())))) + 2;
2466 // +1 for leading digit, maybe +1 for "o"
2467 uint width = (_idx == 0 ? 0 : static_cast<uint>(log10(static_cast<double>(_idx)))) + 1 + (is_new ? 0 : 1);
2468 while (max_width > width) {
2469 st->print(" ");
2470 width++;
2471 }
2472 }
2473 if (!is_new) {
2474 st->print("o");
2475 }
2476 st->print("%d", _idx);
2477 if (dc != nullptr) {
2478 dc->post_dump(st);
2479 }
2480 }
2481
2482 // -----------------------------dump_name--------------------------------------
2483 void Node::dump_name(outputStream* st, DumpConfig* dc) const {
2484 if (dc != nullptr) {
2485 dc->pre_dump(st, this);
2486 }
2487 st->print("%s", Name());
2488 if (dc != nullptr) {
2489 dc->post_dump(st);
2490 }
2491 }
2492
2493 // -----------------------------Name-------------------------------------------
2494 extern const char *NodeClassNames[];
2495 const char *Node::Name() const { return NodeClassNames[Opcode()]; }
2496
2497 static bool is_disconnected(const Node* n) {
2498 for (uint i = 0; i < n->req(); i++) {
2499 if (n->in(i) != nullptr) return false;
2500 }
2501 return true;
2502 }
2503
2504 #ifdef ASSERT
2505 void Node::dump_orig(outputStream *st, bool print_key) const {
2506 Compile* C = Compile::current();
2507 Node* orig = _debug_orig;
2508 if (not_a_node(orig)) orig = nullptr;
2509 if (orig != nullptr && !C->node_arena()->contains(orig)) orig = nullptr;
2510 if (orig == nullptr) return;
2511 if (print_key) {
2512 st->print(" !orig=");
2513 }
2514 Node* fast = orig->debug_orig(); // tortoise & hare algorithm to detect loops
2515 if (not_a_node(fast)) fast = nullptr;
2516 while (orig != nullptr) {
2517 bool discon = is_disconnected(orig); // if discon, print [123] else 123
2518 if (discon) st->print("[");
2519 if (!Compile::current()->node_arena()->contains(orig))
2520 st->print("o");
2521 st->print("%d", orig->_idx);
2522 if (discon) st->print("]");
2523 orig = orig->debug_orig();
2524 if (not_a_node(orig)) orig = nullptr;
2525 if (orig != nullptr && !C->node_arena()->contains(orig)) orig = nullptr;
2526 if (orig != nullptr) st->print(",");
2527 if (fast != nullptr) {
2528 // Step fast twice for each single step of orig:
2529 fast = fast->debug_orig();
2530 if (not_a_node(fast)) fast = nullptr;
2531 if (fast != nullptr && fast != orig) {
2532 fast = fast->debug_orig();
2533 if (not_a_node(fast)) fast = nullptr;
2534 }
2535 if (fast == orig) {
2536 st->print("...");
2537 break;
2538 }
2539 }
2540 }
2541 }
2542
2543 void Node::set_debug_orig(Node* orig) {
2544 _debug_orig = orig;
2545 if (BreakAtNode == 0) return;
2546 if (not_a_node(orig)) orig = nullptr;
2547 int trip = 10;
2548 while (orig != nullptr) {
2549 if (orig->debug_idx() == BreakAtNode || (uintx)orig->_idx == BreakAtNode) {
2550 tty->print_cr("BreakAtNode: _idx=%d _debug_idx=" UINT64_FORMAT " orig._idx=%d orig._debug_idx=" UINT64_FORMAT,
2551 this->_idx, this->debug_idx(), orig->_idx, orig->debug_idx());
2552 BREAKPOINT;
2553 }
2554 orig = orig->debug_orig();
2555 if (not_a_node(orig)) orig = nullptr;
2556 if (trip-- <= 0) break;
2557 }
2558 }
2559 #endif //ASSERT
2560
2561 //------------------------------dump------------------------------------------
2562 // Dump a Node
2563 void Node::dump(const char* suffix, bool mark, outputStream* st, DumpConfig* dc) const {
2564 Compile* C = Compile::current();
2565 bool is_new = C->node_arena()->contains(this);
2566 C->_in_dump_cnt++;
2567
2568 // idx mark name ===
2569 dump_idx(true, st, dc);
2570 st->print(mark ? " >" : " ");
2571 dump_name(st, dc);
2572 st->print(" === ");
2573
2574 // Dump the required and precedence inputs
2575 dump_req(st, dc);
2576 dump_prec(st, dc);
2577 // Dump the outputs
2578 dump_out(st, dc);
2579
2580 if (is_disconnected(this)) {
2581 #ifdef ASSERT
2582 st->print(" [" UINT64_FORMAT "]", debug_idx());
2583 dump_orig(st);
2584 #endif
2585 st->cr();
2586 C->_in_dump_cnt--;
2587 return; // don't process dead nodes
2588 }
2589
2590 if (C->clone_map().value(_idx) != 0) {
2591 C->clone_map().dump(_idx, st);
2592 }
2593 // Dump node-specific info
2594 dump_spec(st);
2595 #ifdef ASSERT
2596 // Dump the non-reset _debug_idx
2597 if (Verbose && WizardMode) {
2598 st->print(" [" UINT64_FORMAT "]", debug_idx());
2599 }
2600 #endif
2601
2602 const Type *t = bottom_type();
2603
2604 if (t != nullptr && (t->isa_instptr() || t->isa_instklassptr())) {
2605 const TypeInstPtr *toop = t->isa_instptr();
2606 const TypeInstKlassPtr *tkls = t->isa_instklassptr();
2607 if (toop) {
2608 st->print(" Oop:");
2609 } else if (tkls) {
2610 st->print(" Klass:");
2611 }
2612 t->dump_on(st);
2613 } else if (t == Type::MEMORY) {
2614 st->print(" Memory:");
2615 MemNode::dump_adr_type(this, adr_type(), st);
2616 } else if (Verbose || WizardMode) {
2617 st->print(" Type:");
2618 if (t) {
2619 t->dump_on(st);
2620 } else {
2621 st->print("no type");
2622 }
2623 } else if (t->isa_vect() && this->is_MachSpillCopy()) {
2624 // Dump MachSpillcopy vector type.
2625 t->dump_on(st);
2626 }
2627 if (is_new) {
2628 DEBUG_ONLY(dump_orig(st));
2629 Node_Notes* nn = C->node_notes_at(_idx);
2630 if (nn != nullptr && !nn->is_clear()) {
2631 if (nn->jvms() != nullptr) {
2632 st->print(" !jvms:");
2633 nn->jvms()->dump_spec(st);
2634 }
2635 }
2636 }
2637 if (suffix) st->print("%s", suffix);
2638 C->_in_dump_cnt--;
2639 }
2640
2641 // call from debugger: dump node to tty with newline
2642 void Node::dump() const {
2643 dump("\n");
2644 }
2645
2646 //------------------------------dump_req--------------------------------------
2647 void Node::dump_req(outputStream* st, DumpConfig* dc) const {
2648 // Dump the required input edges
2649 for (uint i = 0; i < req(); i++) { // For all required inputs
2650 Node* d = in(i);
2651 if (d == nullptr) {
2652 st->print("_ ");
2653 } else if (not_a_node(d)) {
2654 st->print("not_a_node "); // uninitialized, sentinel, garbage, etc.
2655 } else {
2656 d->dump_idx(false, st, dc);
2657 st->print(" ");
2658 }
2659 }
2660 }
2661
2662
2663 //------------------------------dump_prec-------------------------------------
2664 void Node::dump_prec(outputStream* st, DumpConfig* dc) const {
2665 // Dump the precedence edges
2666 int any_prec = 0;
2667 for (uint i = req(); i < len(); i++) { // For all precedence inputs
2668 Node* p = in(i);
2669 if (p != nullptr) {
2670 if (!any_prec++) st->print(" |");
2671 if (not_a_node(p)) { st->print("not_a_node "); continue; }
2672 p->dump_idx(false, st, dc);
2673 st->print(" ");
2674 }
2675 }
2676 }
2677
2678 //------------------------------dump_out--------------------------------------
2679 void Node::dump_out(outputStream* st, DumpConfig* dc) const {
2680 // Delimit the output edges
2681 st->print(" [[ ");
2682 // Dump the output edges
2683 for (uint i = 0; i < _outcnt; i++) { // For all outputs
2684 Node* u = _out[i];
2685 if (u == nullptr) {
2686 st->print("_ ");
2687 } else if (not_a_node(u)) {
2688 st->print("not_a_node ");
2689 } else {
2690 u->dump_idx(false, st, dc);
2691 st->print(" ");
2692 }
2693 }
2694 st->print("]] ");
2695 }
2696
2697 //------------------------------dump-------------------------------------------
2698 // call from debugger: dump Node's inputs (or outputs if d negative)
2699 void Node::dump(int d) const {
2700 dump_bfs(abs(d), nullptr, (d > 0) ? "+$" : "-$");
2701 }
2702
2703 //------------------------------dump_ctrl--------------------------------------
2704 // call from debugger: dump Node's control inputs (or outputs if d negative)
2705 void Node::dump_ctrl(int d) const {
2706 dump_bfs(abs(d), nullptr, (d > 0) ? "+$c" : "-$c");
2707 }
2708
2709 //-----------------------------dump_compact------------------------------------
2710 void Node::dump_comp() const {
2711 this->dump_comp("\n");
2712 }
2713
2714 //-----------------------------dump_compact------------------------------------
2715 // Dump a Node in compact representation, i.e., just print its name and index.
2716 // Nodes can specify additional specifics to print in compact representation by
2717 // implementing dump_compact_spec.
2718 void Node::dump_comp(const char* suffix, outputStream *st) const {
2719 Compile* C = Compile::current();
2720 C->_in_dump_cnt++;
2721 st->print("%s(%d)", Name(), _idx);
2722 this->dump_compact_spec(st);
2723 if (suffix) {
2724 st->print("%s", suffix);
2725 }
2726 C->_in_dump_cnt--;
2727 }
2728
2729 // VERIFICATION CODE
2730 // Verify all nodes if verify_depth is negative
2731 void Node::verify(int verify_depth, VectorSet& visited, Node_List& worklist) {
2732 assert(verify_depth != 0, "depth should not be 0");
2733 Compile* C = Compile::current();
2734 uint last_index_on_current_depth = worklist.size() - 1;
2735 verify_depth--; // Visiting the first node on depth 1
2736 // Only add nodes to worklist if verify_depth is negative (visit all nodes) or greater than 0
2737 bool add_to_worklist = verify_depth != 0;
2738
2739 for (uint list_index = 0; list_index < worklist.size(); list_index++) {
2740 Node* n = worklist[list_index];
2741
2742 if (n->is_Con() && n->bottom_type() == Type::TOP) {
2743 if (C->cached_top_node() == nullptr) {
2744 C->set_cached_top_node((Node*)n);
2745 }
2746 assert(C->cached_top_node() == n, "TOP node must be unique");
2747 }
2748
2749 uint in_len = n->len();
2750 for (uint i = 0; i < in_len; i++) {
2751 Node* x = n->_in[i];
2752 if (!x || x->is_top()) {
2753 continue;
2754 }
2755
2756 // Verify my input has a def-use edge to me
2757 // Count use-def edges from n to x
2758 int cnt = 1;
2759 for (uint j = 0; j < i; j++) {
2760 if (n->_in[j] == x) {
2761 cnt++;
2762 break;
2763 }
2764 }
2765 if (cnt == 2) {
2766 // x is already checked as n's previous input, skip its duplicated def-use count checking
2767 continue;
2768 }
2769 for (uint j = i + 1; j < in_len; j++) {
2770 if (n->_in[j] == x) {
2771 cnt++;
2772 }
2773 }
2774
2775 // Count def-use edges from x to n
2776 uint max = x->_outcnt;
2777 for (uint k = 0; k < max; k++) {
2778 if (x->_out[k] == n) {
2779 cnt--;
2780 }
2781 }
2782 assert(cnt == 0, "mismatched def-use edge counts");
2783
2784 if (add_to_worklist && !visited.test_set(x->_idx)) {
2785 worklist.push(x);
2786 }
2787 }
2788
2789 if (verify_depth > 0 && list_index == last_index_on_current_depth) {
2790 // All nodes on this depth were processed and its inputs are on the worklist. Decrement verify_depth and
2791 // store the current last list index which is the last node in the list with the new depth. All nodes
2792 // added afterwards will have a new depth again. Stop adding new nodes if depth limit is reached (=0).
2793 verify_depth--;
2794 if (verify_depth == 0) {
2795 add_to_worklist = false;
2796 }
2797 last_index_on_current_depth = worklist.size() - 1;
2798 }
2799 }
2800 }
2801 #endif // not PRODUCT
2802
2803 //------------------------------Registers--------------------------------------
2804 // Do we Match on this edge index or not? Generally false for Control
2805 // and true for everything else. Weird for calls & returns.
2806 uint Node::match_edge(uint idx) const {
2807 return idx; // True for other than index 0 (control)
2808 }
2809
2810 // Register classes are defined for specific machines
2811 const RegMask &Node::out_RegMask() const {
2812 ShouldNotCallThis();
2813 return RegMask::Empty;
2814 }
2815
2816 const RegMask &Node::in_RegMask(uint) const {
2817 ShouldNotCallThis();
2818 return RegMask::Empty;
2819 }
2820
2821 void Node_Array::grow(uint i) {
2822 assert(i >= _max, "Should have been checked before, use maybe_grow?");
2823 assert(_max > 0, "invariant");
2824 uint old = _max;
2825 _max = next_power_of_2(i);
2826 _nodes = (Node**)_a->Arealloc( _nodes, old*sizeof(Node*),_max*sizeof(Node*));
2827 Copy::zero_to_bytes( &_nodes[old], (_max-old)*sizeof(Node*) );
2828 }
2829
2830 void Node_Array::insert(uint i, Node* n) {
2831 if (_nodes[_max - 1]) {
2832 grow(_max);
2833 }
2834 Copy::conjoint_words_to_higher((HeapWord*)&_nodes[i], (HeapWord*)&_nodes[i + 1], ((_max - i - 1) * sizeof(Node*)));
2835 _nodes[i] = n;
2836 }
2837
2838 void Node_Array::remove(uint i) {
2839 Copy::conjoint_words_to_lower((HeapWord*)&_nodes[i + 1], (HeapWord*)&_nodes[i], ((_max - i - 1) * sizeof(Node*)));
2840 _nodes[_max - 1] = nullptr;
2841 }
2842
2843 void Node_Array::dump() const {
2844 #ifndef PRODUCT
2845 for (uint i = 0; i < _max; i++) {
2846 Node* nn = _nodes[i];
2847 if (nn != nullptr) {
2848 tty->print("%5d--> ",i); nn->dump();
2849 }
2850 }
2851 #endif
2852 }
2853
2854 //--------------------------is_iteratively_computed------------------------------
2855 // Operation appears to be iteratively computed (such as an induction variable)
2856 // It is possible for this operation to return false for a loop-varying
2857 // value, if it appears (by local graph inspection) to be computed by a simple conditional.
2858 bool Node::is_iteratively_computed() {
2859 if (ideal_reg()) { // does operation have a result register?
2860 for (uint i = 1; i < req(); i++) {
2861 Node* n = in(i);
2862 if (n != nullptr && n->is_Phi()) {
2863 for (uint j = 1; j < n->req(); j++) {
2864 if (n->in(j) == this) {
2865 return true;
2866 }
2867 }
2868 }
2869 }
2870 }
2871 return false;
2872 }
2873
2874 //--------------------------find_similar------------------------------
2875 // Return a node with opcode "opc" and same inputs as "this" if one can
2876 // be found; Otherwise return null;
2877 Node* Node::find_similar(int opc) {
2878 if (req() >= 2) {
2879 Node* def = in(1);
2880 if (def && def->outcnt() >= 2) {
2881 for (DUIterator_Fast dmax, i = def->fast_outs(dmax); i < dmax; i++) {
2882 Node* use = def->fast_out(i);
2883 if (use != this &&
2884 use->Opcode() == opc &&
2885 use->req() == req()) {
2886 uint j;
2887 for (j = 0; j < use->req(); j++) {
2888 if (use->in(j) != in(j)) {
2889 break;
2890 }
2891 }
2892 if (j == use->req()) {
2893 return use;
2894 }
2895 }
2896 }
2897 }
2898 }
2899 return nullptr;
2900 }
2901
2902
2903 //--------------------------unique_ctrl_out_or_null-------------------------
2904 // Return the unique control out if only one. Null if none or more than one.
2905 Node* Node::unique_ctrl_out_or_null() const {
2906 Node* found = nullptr;
2907 for (uint i = 0; i < outcnt(); i++) {
2908 Node* use = raw_out(i);
2909 if (use->is_CFG() && use != this) {
2910 if (found != nullptr) {
2911 return nullptr;
2912 }
2913 found = use;
2914 }
2915 }
2916 return found;
2917 }
2918
2919 //--------------------------unique_ctrl_out------------------------------
2920 // Return the unique control out. Asserts if none or more than one control out.
2921 Node* Node::unique_ctrl_out() const {
2922 Node* ctrl = unique_ctrl_out_or_null();
2923 assert(ctrl != nullptr, "control out is assumed to be unique");
2924 return ctrl;
2925 }
2926
2927 void Node::ensure_control_or_add_prec(Node* c) {
2928 if (in(0) == nullptr) {
2929 set_req(0, c);
2930 } else if (in(0) != c) {
2931 add_prec(c);
2932 }
2933 }
2934
2935 void Node::add_prec_from(Node* n) {
2936 for (uint i = n->req(); i < n->len(); i++) {
2937 Node* prec = n->in(i);
2938 if (prec != nullptr) {
2939 add_prec(prec);
2940 }
2941 }
2942 }
2943
2944 bool Node::is_dead_loop_safe() const {
2945 if (is_Phi()) {
2946 return true;
2947 }
2948 if (is_Proj() && in(0) == nullptr) {
2949 return true;
2950 }
2951 if ((_flags & (Flag_is_dead_loop_safe | Flag_is_Con)) != 0) {
2952 if (!is_Proj()) {
2953 return true;
2954 }
2955 if (in(0)->is_Allocate()) {
2956 return false;
2957 }
2958 // MemNode::can_see_stored_value() peeks through the boxing call
2959 if (in(0)->is_CallStaticJava() && in(0)->as_CallStaticJava()->is_boxing_method()) {
2960 return false;
2961 }
2962 return true;
2963 }
2964 return false;
2965 }
2966
2967 bool Node::is_div_or_mod(BasicType bt) const { return Opcode() == Op_Div(bt) || Opcode() == Op_Mod(bt) ||
2968 Opcode() == Op_UDiv(bt) || Opcode() == Op_UMod(bt); }
2969
2970 // `maybe_pure_function` is assumed to be the input of `this`. This is a bit redundant,
2971 // but we already have and need maybe_pure_function in all the call sites, so
2972 // it makes it obvious that the `maybe_pure_function` is the same node as in the caller,
2973 // while it takes more thinking to realize that a locally computed in(0) must be equal to
2974 // the local in the caller.
2975 bool Node::is_data_proj_of_pure_function(const Node* maybe_pure_function) const {
2976 return Opcode() == Op_Proj && as_Proj()->_con == TypeFunc::Parms && maybe_pure_function->is_CallLeafPure();
2977 }
2978
2979 //=============================================================================
2980 //------------------------------yank-------------------------------------------
2981 // Find and remove
2982 void Node_List::yank( Node *n ) {
2983 uint i;
2984 for (i = 0; i < _cnt; i++) {
2985 if (_nodes[i] == n) {
2986 break;
2987 }
2988 }
2989
2990 if (i < _cnt) {
2991 _nodes[i] = _nodes[--_cnt];
2992 }
2993 }
2994
2995 //------------------------------dump-------------------------------------------
2996 void Node_List::dump() const {
2997 #ifndef PRODUCT
2998 for (uint i = 0; i < _cnt; i++) {
2999 if (_nodes[i]) {
3000 tty->print("%5d--> ", i);
3001 _nodes[i]->dump();
3002 }
3003 }
3004 #endif
3005 }
3006
3007 void Node_List::dump_simple() const {
3008 #ifndef PRODUCT
3009 for (uint i = 0; i < _cnt; i++) {
3010 if( _nodes[i] ) {
3011 tty->print(" %d", _nodes[i]->_idx);
3012 } else {
3013 tty->print(" null");
3014 }
3015 }
3016 #endif
3017 }
3018
3019 //=============================================================================
3020 //------------------------------remove-----------------------------------------
3021 void Unique_Node_List::remove(Node* n) {
3022 if (_in_worklist.test(n->_idx)) {
3023 for (uint i = 0; i < size(); i++) {
3024 if (_nodes[i] == n) {
3025 map(i, Node_List::pop());
3026 _in_worklist.remove(n->_idx);
3027 return;
3028 }
3029 }
3030 ShouldNotReachHere();
3031 }
3032 }
3033
3034 //-----------------------remove_useless_nodes----------------------------------
3035 // Remove useless nodes from worklist
3036 void Unique_Node_List::remove_useless_nodes(VectorSet &useful) {
3037 for (uint i = 0; i < size(); ++i) {
3038 Node *n = at(i);
3039 assert( n != nullptr, "Did not expect null entries in worklist");
3040 if (!useful.test(n->_idx)) {
3041 _in_worklist.remove(n->_idx);
3042 map(i, Node_List::pop());
3043 --i; // Visit popped node
3044 // If it was last entry, loop terminates since size() was also reduced
3045 }
3046 }
3047 }
3048
3049 //=============================================================================
3050 void Node_Stack::grow() {
3051 size_t old_top = pointer_delta(_inode_top,_inodes,sizeof(INode)); // save _top
3052 size_t old_max = pointer_delta(_inode_max,_inodes,sizeof(INode));
3053 size_t max = old_max << 1; // max * 2
3054 _inodes = REALLOC_ARENA_ARRAY(_a, INode, _inodes, old_max, max);
3055 _inode_max = _inodes + max;
3056 _inode_top = _inodes + old_top; // restore _top
3057 }
3058
3059 // Node_Stack is used to map nodes.
3060 Node* Node_Stack::find(uint idx) const {
3061 uint sz = size();
3062 for (uint i = 0; i < sz; i++) {
3063 if (idx == index_at(i)) {
3064 return node_at(i);
3065 }
3066 }
3067 return nullptr;
3068 }
3069
3070 //=============================================================================
3071 uint TypeNode::size_of() const { return sizeof(*this); }
3072 #ifndef PRODUCT
3073 void TypeNode::dump_spec(outputStream *st) const {
3074 if (!Verbose && !WizardMode) {
3075 // standard dump does this in Verbose and WizardMode
3076 st->print(" #"); _type->dump_on(st);
3077 }
3078 }
3079
3080 void TypeNode::dump_compact_spec(outputStream *st) const {
3081 st->print("#");
3082 _type->dump_on(st);
3083 }
3084 #endif
3085 uint TypeNode::hash() const {
3086 return Node::hash() + _type->hash();
3087 }
3088 bool TypeNode::cmp(const Node& n) const {
3089 return Type::equals(_type, n.as_Type()->_type);
3090 }
3091 const Type* TypeNode::bottom_type() const { return _type; }
3092 const Type* TypeNode::Value(PhaseGVN* phase) const { return _type; }
3093
3094 //------------------------------ideal_reg--------------------------------------
3095 uint TypeNode::ideal_reg() const {
3096 return _type->ideal_reg();
3097 }
3098
3099 void TypeNode::make_path_dead(PhaseIterGVN* igvn, PhaseIdealLoop* loop, Node* ctrl_use, uint j, const char* phase_str) {
3100 Node* c = ctrl_use->in(j);
3101 if (igvn->type(c) != Type::TOP) {
3102 igvn->replace_input_of(ctrl_use, j, igvn->C->top());
3103 create_halt_path(igvn, c, loop, phase_str);
3104 }
3105 }
3106
3107 // This Type node is dead. It could be because the type that it captures and the type of the node computed from its
3108 // inputs do not intersect anymore. That node has some uses along some control flow paths. Those control flow paths must
3109 // be unreachable as using a dead value makes no sense. For the Type node to capture a narrowed down type, some control
3110 // flow construct must guard the Type node (an If node usually). When the Type node becomes dead, the guard usually
3111 // constant folds and the control flow that leads to the Type node becomes unreachable. There are cases where that
3112 // doesn't happen, however. They are handled here by following uses of the Type node until a CFG or a Phi to find dead
3113 // paths. The dead paths are then replaced by a Halt node.
3114 void TypeNode::make_paths_from_here_dead(PhaseIterGVN* igvn, PhaseIdealLoop* loop, const char* phase_str) {
3115 Unique_Node_List wq;
3116 wq.push(this);
3117 for (uint i = 0; i < wq.size(); ++i) {
3118 Node* n = wq.at(i);
3119 for (DUIterator_Fast kmax, k = n->fast_outs(kmax); k < kmax; k++) {
3120 Node* u = n->fast_out(k);
3121 if (u->is_CFG()) {
3122 assert(!u->is_Region(), "Can't reach a Region without going through a Phi");
3123 make_path_dead(igvn, loop, u, 0, phase_str);
3124 } else if (u->is_Phi()) {
3125 Node* r = u->in(0);
3126 assert(r->is_Region() || r->is_top(), "unexpected Phi's control");
3127 if (r->is_Region()) {
3128 for (uint j = 1; j < u->req(); ++j) {
3129 if (u->in(j) == n && r->in(j) != nullptr) {
3130 make_path_dead(igvn, loop, r, j, phase_str);
3131 }
3132 }
3133 }
3134 } else {
3135 wq.push(u);
3136 }
3137 }
3138 }
3139 }
3140
3141 void TypeNode::create_halt_path(PhaseIterGVN* igvn, Node* c, PhaseIdealLoop* loop, const char* phase_str) const {
3142 Node* frame = new ParmNode(igvn->C->start(), TypeFunc::FramePtr);
3143 if (loop == nullptr) {
3144 igvn->register_new_node_with_optimizer(frame);
3145 } else {
3146 loop->register_new_node(frame, igvn->C->start());
3147 }
3148
3149 stringStream ss;
3150 ss.print("dead path discovered by TypeNode during %s", phase_str);
3151
3152 Node* halt = new HaltNode(c, frame, ss.as_string(igvn->C->comp_arena()));
3153 if (loop == nullptr) {
3154 igvn->register_new_node_with_optimizer(halt);
3155 } else {
3156 loop->register_control(halt, loop->ltree_root(), c);
3157 }
3158 igvn->add_input_to(igvn->C->root(), halt);
3159 }
3160
3161 Node* TypeNode::Ideal(PhaseGVN* phase, bool can_reshape) {
3162 if (KillPathsReachableByDeadTypeNode && can_reshape && Value(phase) == Type::TOP) {
3163 PhaseIterGVN* igvn = phase->is_IterGVN();
3164 Node* top = igvn->C->top();
3165 ResourceMark rm;
3166 make_paths_from_here_dead(igvn, nullptr, "igvn");
3167 return top;
3168 }
3169
3170 return Node::Ideal(phase, can_reshape);
3171 }
3172