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