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