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