1 /*
   2  * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "gc/shared/barrierSet.hpp"
  26 #include "gc/shared/c2/barrierSetC2.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "memory/resourceArea.hpp"
  29 #include "opto/addnode.hpp"
  30 #include "opto/block.hpp"
  31 #include "opto/callnode.hpp"
  32 #include "opto/castnode.hpp"
  33 #include "opto/cfgnode.hpp"
  34 #include "opto/convertnode.hpp"
  35 #include "opto/idealGraphPrinter.hpp"
  36 #include "opto/loopnode.hpp"
  37 #include "opto/machnode.hpp"
  38 #include "opto/opcodes.hpp"
  39 #include "opto/phaseX.hpp"
  40 #include "opto/regalloc.hpp"
  41 #include "opto/rootnode.hpp"
  42 #include "utilities/macros.hpp"
  43 #include "utilities/powerOfTwo.hpp"
  44 
  45 //=============================================================================
  46 #define NODE_HASH_MINIMUM_SIZE    255
  47 
  48 //------------------------------NodeHash---------------------------------------
  49 NodeHash::NodeHash(Arena *arena, uint est_max_size) :
  50   _a(arena),
  51   _max( round_up(est_max_size < NODE_HASH_MINIMUM_SIZE ? NODE_HASH_MINIMUM_SIZE : est_max_size) ),
  52   _inserts(0), _insert_limit( insert_limit() ),
  53   _table( NEW_ARENA_ARRAY( _a , Node* , _max ) )
  54 #ifndef PRODUCT
  55   , _grows(0),_look_probes(0), _lookup_hits(0), _lookup_misses(0),
  56   _insert_probes(0), _delete_probes(0), _delete_hits(0), _delete_misses(0),
  57    _total_inserts(0), _total_insert_probes(0)
  58 #endif
  59 {
  60   // _sentinel must be in the current node space
  61   _sentinel = new ProjNode(nullptr, TypeFunc::Control);
  62   memset(_table,0,sizeof(Node*)*_max);
  63 }
  64 
  65 //------------------------------hash_find--------------------------------------
  66 // Find in hash table
  67 Node *NodeHash::hash_find( const Node *n ) {
  68   // ((Node*)n)->set_hash( n->hash() );
  69   uint hash = n->hash();
  70   if (hash == Node::NO_HASH) {
  71     NOT_PRODUCT( _lookup_misses++ );
  72     return nullptr;
  73   }
  74   uint key = hash & (_max-1);
  75   uint stride = key | 0x01;
  76   NOT_PRODUCT( _look_probes++ );
  77   Node *k = _table[key];        // Get hashed value
  78   if( !k ) {                    // ?Miss?
  79     NOT_PRODUCT( _lookup_misses++ );
  80     return nullptr;             // Miss!
  81   }
  82 
  83   int op = n->Opcode();
  84   uint req = n->req();
  85   while( 1 ) {                  // While probing hash table
  86     if( k->req() == req &&      // Same count of inputs
  87         k->Opcode() == op ) {   // Same Opcode
  88       for( uint i=0; i<req; i++ )
  89         if( n->in(i)!=k->in(i)) // Different inputs?
  90           goto collision;       // "goto" is a speed hack...
  91       if( n->cmp(*k) ) {        // Check for any special bits
  92         NOT_PRODUCT( _lookup_hits++ );
  93         return k;               // Hit!
  94       }
  95     }
  96   collision:
  97     NOT_PRODUCT( _look_probes++ );
  98     key = (key + stride/*7*/) & (_max-1); // Stride through table with relative prime
  99     k = _table[key];            // Get hashed value
 100     if( !k ) {                  // ?Miss?
 101       NOT_PRODUCT( _lookup_misses++ );
 102       return nullptr;           // Miss!
 103     }
 104   }
 105   ShouldNotReachHere();
 106   return nullptr;
 107 }
 108 
 109 //------------------------------hash_find_insert-------------------------------
 110 // Find in hash table, insert if not already present
 111 // Used to preserve unique entries in hash table
 112 Node *NodeHash::hash_find_insert( Node *n ) {
 113   // n->set_hash( );
 114   uint hash = n->hash();
 115   if (hash == Node::NO_HASH) {
 116     NOT_PRODUCT( _lookup_misses++ );
 117     return nullptr;
 118   }
 119   uint key = hash & (_max-1);
 120   uint stride = key | 0x01;     // stride must be relatively prime to table siz
 121   uint first_sentinel = 0;      // replace a sentinel if seen.
 122   NOT_PRODUCT( _look_probes++ );
 123   Node *k = _table[key];        // Get hashed value
 124   if( !k ) {                    // ?Miss?
 125     NOT_PRODUCT( _lookup_misses++ );
 126     _table[key] = n;            // Insert into table!
 127     DEBUG_ONLY(n->enter_hash_lock()); // Lock down the node while in the table.
 128     check_grow();               // Grow table if insert hit limit
 129     return nullptr;             // Miss!
 130   }
 131   else if( k == _sentinel ) {
 132     first_sentinel = key;      // Can insert here
 133   }
 134 
 135   int op = n->Opcode();
 136   uint req = n->req();
 137   while( 1 ) {                  // While probing hash table
 138     if( k->req() == req &&      // Same count of inputs
 139         k->Opcode() == op ) {   // Same Opcode
 140       for( uint i=0; i<req; i++ )
 141         if( n->in(i)!=k->in(i)) // Different inputs?
 142           goto collision;       // "goto" is a speed hack...
 143       if( n->cmp(*k) ) {        // Check for any special bits
 144         NOT_PRODUCT( _lookup_hits++ );
 145         return k;               // Hit!
 146       }
 147     }
 148   collision:
 149     NOT_PRODUCT( _look_probes++ );
 150     key = (key + stride) & (_max-1); // Stride through table w/ relative prime
 151     k = _table[key];            // Get hashed value
 152     if( !k ) {                  // ?Miss?
 153       NOT_PRODUCT( _lookup_misses++ );
 154       key = (first_sentinel == 0) ? key : first_sentinel; // ?saw sentinel?
 155       _table[key] = n;          // Insert into table!
 156       DEBUG_ONLY(n->enter_hash_lock()); // Lock down the node while in the table.
 157       check_grow();             // Grow table if insert hit limit
 158       return nullptr;           // Miss!
 159     }
 160     else if( first_sentinel == 0 && k == _sentinel ) {
 161       first_sentinel = key;    // Can insert here
 162     }
 163 
 164   }
 165   ShouldNotReachHere();
 166   return nullptr;
 167 }
 168 
 169 //------------------------------hash_insert------------------------------------
 170 // Insert into hash table
 171 void NodeHash::hash_insert( Node *n ) {
 172   // // "conflict" comments -- print nodes that conflict
 173   // bool conflict = false;
 174   // n->set_hash();
 175   uint hash = n->hash();
 176   if (hash == Node::NO_HASH) {
 177     return;
 178   }
 179   check_grow();
 180   uint key = hash & (_max-1);
 181   uint stride = key | 0x01;
 182 
 183   while( 1 ) {                  // While probing hash table
 184     NOT_PRODUCT( _insert_probes++ );
 185     Node *k = _table[key];      // Get hashed value
 186     if( !k || (k == _sentinel) ) break;       // Found a slot
 187     assert( k != n, "already inserted" );
 188     // if( PrintCompilation && PrintOptoStatistics && Verbose ) { tty->print("  conflict: "); k->dump(); conflict = true; }
 189     key = (key + stride) & (_max-1); // Stride through table w/ relative prime
 190   }
 191   _table[key] = n;              // Insert into table!
 192   DEBUG_ONLY(n->enter_hash_lock()); // Lock down the node while in the table.
 193   // if( conflict ) { n->dump(); }
 194 }
 195 
 196 //------------------------------hash_delete------------------------------------
 197 // Replace in hash table with sentinel
 198 bool NodeHash::hash_delete( const Node *n ) {
 199   Node *k;
 200   uint hash = n->hash();
 201   if (hash == Node::NO_HASH) {
 202     NOT_PRODUCT( _delete_misses++ );
 203     return false;
 204   }
 205   uint key = hash & (_max-1);
 206   uint stride = key | 0x01;
 207   DEBUG_ONLY( uint counter = 0; );
 208   for( ; /* (k != nullptr) && (k != _sentinel) */; ) {
 209     DEBUG_ONLY( counter++ );
 210     NOT_PRODUCT( _delete_probes++ );
 211     k = _table[key];            // Get hashed value
 212     if( !k ) {                  // Miss?
 213       NOT_PRODUCT( _delete_misses++ );
 214       return false;             // Miss! Not in chain
 215     }
 216     else if( n == k ) {
 217       NOT_PRODUCT( _delete_hits++ );
 218       _table[key] = _sentinel;  // Hit! Label as deleted entry
 219       DEBUG_ONLY(((Node*)n)->exit_hash_lock()); // Unlock the node upon removal from table.
 220       return true;
 221     }
 222     else {
 223       // collision: move through table with prime offset
 224       key = (key + stride/*7*/) & (_max-1);
 225       assert( counter <= _insert_limit, "Cycle in hash-table");
 226     }
 227   }
 228   ShouldNotReachHere();
 229   return false;
 230 }
 231 
 232 //------------------------------round_up---------------------------------------
 233 // Round up to nearest power of 2
 234 uint NodeHash::round_up(uint x) {
 235   x += (x >> 2);                  // Add 25% slop
 236   return MAX2(16U, round_up_power_of_2(x));
 237 }
 238 
 239 //------------------------------grow-------------------------------------------
 240 // Grow _table to next power of 2 and insert old entries
 241 void  NodeHash::grow() {
 242   // Record old state
 243   uint   old_max   = _max;
 244   Node **old_table = _table;
 245   // Construct new table with twice the space
 246 #ifndef PRODUCT
 247   _grows++;
 248   _total_inserts       += _inserts;
 249   _total_insert_probes += _insert_probes;
 250   _insert_probes   = 0;
 251 #endif
 252   _inserts         = 0;
 253   _max     = _max << 1;
 254   _table   = NEW_ARENA_ARRAY( _a , Node* , _max ); // (Node**)_a->Amalloc( _max * sizeof(Node*) );
 255   memset(_table,0,sizeof(Node*)*_max);
 256   _insert_limit = insert_limit();
 257   // Insert old entries into the new table
 258   for( uint i = 0; i < old_max; i++ ) {
 259     Node *m = *old_table++;
 260     if( !m || m == _sentinel ) continue;
 261     DEBUG_ONLY(m->exit_hash_lock()); // Unlock the node upon removal from old table.
 262     hash_insert(m);
 263   }
 264 }
 265 
 266 //------------------------------clear------------------------------------------
 267 // Clear all entries in _table to null but keep storage
 268 void  NodeHash::clear() {
 269 #ifdef ASSERT
 270   // Unlock all nodes upon removal from table.
 271   for (uint i = 0; i < _max; i++) {
 272     Node* n = _table[i];
 273     if (!n || n == _sentinel)  continue;
 274     n->exit_hash_lock();
 275   }
 276 #endif
 277 
 278   memset( _table, 0, _max * sizeof(Node*) );
 279 }
 280 
 281 //-----------------------remove_useless_nodes----------------------------------
 282 // Remove useless nodes from value table,
 283 // implementation does not depend on hash function
 284 void NodeHash::remove_useless_nodes(VectorSet &useful) {
 285 
 286   // Dead nodes in the hash table inherited from GVN should not replace
 287   // existing nodes, remove dead nodes.
 288   uint max = size();
 289   Node *sentinel_node = sentinel();
 290   for( uint i = 0; i < max; ++i ) {
 291     Node *n = at(i);
 292     if(n != nullptr && n != sentinel_node && !useful.test(n->_idx)) {
 293       DEBUG_ONLY(n->exit_hash_lock()); // Unlock the node when removed
 294       _table[i] = sentinel_node;       // Replace with placeholder
 295     }
 296   }
 297 }
 298 
 299 
 300 void NodeHash::check_no_speculative_types() {
 301 #ifdef ASSERT
 302   uint max = size();
 303   Unique_Node_List live_nodes;
 304   Compile::current()->identify_useful_nodes(live_nodes);
 305   Node *sentinel_node = sentinel();
 306   for (uint i = 0; i < max; ++i) {
 307     Node *n = at(i);
 308     if (n != nullptr &&
 309         n != sentinel_node &&
 310         n->is_Type() &&
 311         live_nodes.member(n)) {
 312       TypeNode* tn = n->as_Type();
 313       const Type* t = tn->type();
 314       const Type* t_no_spec = t->remove_speculative();
 315       assert(t == t_no_spec, "dead node in hash table or missed node during speculative cleanup");
 316     }
 317   }
 318 #endif
 319 }
 320 
 321 #ifndef PRODUCT
 322 //------------------------------dump-------------------------------------------
 323 // Dump statistics for the hash table
 324 void NodeHash::dump() {
 325   _total_inserts       += _inserts;
 326   _total_insert_probes += _insert_probes;
 327   if (PrintCompilation && PrintOptoStatistics && Verbose && (_inserts > 0)) {
 328     if (WizardMode) {
 329       for (uint i=0; i<_max; i++) {
 330         if (_table[i])
 331           tty->print("%d/%d/%d ",i,_table[i]->hash()&(_max-1),_table[i]->_idx);
 332       }
 333     }
 334     tty->print("\nGVN Hash stats:  %d grows to %d max_size\n", _grows, _max);
 335     tty->print("  %d/%d (%8.1f%% full)\n", _inserts, _max, (double)_inserts/_max*100.0);
 336     tty->print("  %dp/(%dh+%dm) (%8.2f probes/lookup)\n", _look_probes, _lookup_hits, _lookup_misses, (double)_look_probes/(_lookup_hits+_lookup_misses));
 337     tty->print("  %dp/%di (%8.2f probes/insert)\n", _total_insert_probes, _total_inserts, (double)_total_insert_probes/_total_inserts);
 338     // sentinels increase lookup cost, but not insert cost
 339     assert((_lookup_misses+_lookup_hits)*4+100 >= _look_probes, "bad hash function");
 340     assert( _inserts+(_inserts>>3) < _max, "table too full" );
 341     assert( _inserts*3+100 >= _insert_probes, "bad hash function" );
 342   }
 343 }
 344 
 345 Node *NodeHash::find_index(uint idx) { // For debugging
 346   // Find an entry by its index value
 347   for( uint i = 0; i < _max; i++ ) {
 348     Node *m = _table[i];
 349     if( !m || m == _sentinel ) continue;
 350     if( m->_idx == (uint)idx ) return m;
 351   }
 352   return nullptr;
 353 }
 354 #endif
 355 
 356 #ifdef ASSERT
 357 NodeHash::~NodeHash() {
 358   // Unlock all nodes upon destruction of table.
 359   if (_table != (Node**)badAddress)  clear();
 360 }
 361 #endif
 362 
 363 // Add users of 'n' that match 'predicate' to worklist
 364 template <class Predicate>
 365 static void add_users_to_worklist_if(Unique_Node_List& worklist, const Node* n, Predicate predicate) {
 366   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 367     Node* u = n->fast_out(i);
 368     if (predicate(u)) {
 369       worklist.push(u);
 370     }
 371   }
 372 }
 373 
 374 //=============================================================================
 375 //------------------------------PhaseRemoveUseless-----------------------------
 376 // 1) Use a breadthfirst walk to collect useful nodes reachable from root.
 377 PhaseRemoveUseless::PhaseRemoveUseless(PhaseGVN* gvn, Unique_Node_List& worklist, PhaseNumber phase_num) : Phase(phase_num) {
 378   C->print_method(PHASE_BEFORE_REMOVEUSELESS, 3);
 379   // Implementation requires an edge from root to each SafePointNode
 380   // at a backward branch. Inserted in add_safepoint().
 381 
 382   // Identify nodes that are reachable from below, useful.
 383   C->identify_useful_nodes(_useful);
 384   // Update dead node list
 385   C->update_dead_node_list(_useful);
 386 
 387   // Remove all useless nodes from PhaseValues' recorded types
 388   // Must be done before disconnecting nodes to preserve hash-table-invariant
 389   gvn->remove_useless_nodes(_useful.member_set());
 390 
 391   // Remove all useless nodes from future worklist
 392   worklist.remove_useless_nodes(_useful.member_set());
 393 
 394   // Disconnect 'useless' nodes that are adjacent to useful nodes
 395   C->disconnect_useless_nodes(_useful, worklist);
 396 }
 397 
 398 //=============================================================================
 399 //------------------------------PhaseRenumberLive------------------------------
 400 // First, remove useless nodes (equivalent to identifying live nodes).
 401 // Then, renumber live nodes.
 402 //
 403 // The set of live nodes is returned by PhaseRemoveUseless in the _useful structure.
 404 // If the number of live nodes is 'x' (where 'x' == _useful.size()), then the
 405 // PhaseRenumberLive updates the node ID of each node (the _idx field) with a unique
 406 // value in the range [0, x).
 407 //
 408 // At the end of the PhaseRenumberLive phase, the compiler's count of unique nodes is
 409 // updated to 'x' and the list of dead nodes is reset (as there are no dead nodes).
 410 //
 411 // The PhaseRenumberLive phase updates two data structures with the new node IDs.
 412 // (1) The "worklist" is "C->igvn_worklist()", which is to collect which nodes need to
 413 //     be processed by IGVN after removal of the useless nodes.
 414 // (2) Type information "gvn->types()" (same as "C->types()") maps every node ID to
 415 //     the node's type. The mapping is updated to use the new node IDs as well. We
 416 //     create a new map, and swap it with the old one.
 417 //
 418 // Other data structures used by the compiler are not updated. The hash table for value
 419 // numbering ("C->node_hash()", referenced by PhaseValue::_table) is not updated because
 420 // computing the hash values is not based on node IDs.
 421 PhaseRenumberLive::PhaseRenumberLive(PhaseGVN* gvn,
 422                                      Unique_Node_List& worklist,
 423                                      PhaseNumber phase_num) :
 424   PhaseRemoveUseless(gvn, worklist, Remove_Useless_And_Renumber_Live),
 425   _new_type_array(C->comp_arena()),
 426   _old2new_map(C->unique(), C->unique(), -1),
 427   _is_pass_finished(false),
 428   _live_node_count(C->live_nodes())
 429 {
 430   assert(RenumberLiveNodes, "RenumberLiveNodes must be set to true for node renumbering to take place");
 431   assert(C->live_nodes() == _useful.size(), "the number of live nodes must match the number of useful nodes");
 432   assert(_delayed.size() == 0, "should be empty");
 433   assert(&worklist == C->igvn_worklist(), "reference still same as the one from Compile");
 434   assert(&gvn->types() == C->types(), "reference still same as that from Compile");
 435 
 436   GrowableArray<Node_Notes*>* old_node_note_array = C->node_note_array();
 437   if (old_node_note_array != nullptr) {
 438     int new_size = (_useful.size() >> 8) + 1; // The node note array uses blocks, see C->_log2_node_notes_block_size
 439     new_size = MAX2(8, new_size);
 440     C->set_node_note_array(new (C->comp_arena()) GrowableArray<Node_Notes*> (C->comp_arena(), new_size, 0, nullptr));
 441     C->grow_node_notes(C->node_note_array(), new_size);
 442   }
 443 
 444   assert(worklist.is_subset_of(_useful), "only useful nodes should still be in the worklist");
 445 
 446   // Iterate over the set of live nodes.
 447   for (uint current_idx = 0; current_idx < _useful.size(); current_idx++) {
 448     Node* n = _useful.at(current_idx);
 449 
 450     const Type* type = gvn->type_or_null(n);
 451     _new_type_array.map(current_idx, type);
 452 
 453     assert(_old2new_map.at(n->_idx) == -1, "already seen");
 454     _old2new_map.at_put(n->_idx, current_idx);
 455 
 456     if (old_node_note_array != nullptr) {
 457       Node_Notes* nn = C->locate_node_notes(old_node_note_array, n->_idx);
 458       C->set_node_notes_at(current_idx, nn);
 459     }
 460 
 461     n->set_idx(current_idx); // Update node ID.
 462 
 463     if (update_embedded_ids(n) < 0) {
 464       _delayed.push(n); // has embedded IDs; handle later
 465     }
 466   }
 467 
 468   // VectorSet in Unique_Node_Set must be recomputed, since IDs have changed.
 469   worklist.recompute_idx_set();
 470 
 471   assert(_live_node_count == _useful.size(), "all live nodes must be processed");
 472 
 473   _is_pass_finished = true; // pass finished; safe to process delayed updates
 474 
 475   while (_delayed.size() > 0) {
 476     Node* n = _delayed.pop();
 477     int no_of_updates = update_embedded_ids(n);
 478     assert(no_of_updates > 0, "should be updated");
 479   }
 480 
 481   // Replace the compiler's type information with the updated type information.
 482   gvn->types().swap(_new_type_array);
 483 
 484   // Update the unique node count of the compilation to the number of currently live nodes.
 485   C->set_unique(_live_node_count);
 486 
 487   // Set the dead node count to 0 and reset dead node list.
 488   C->reset_dead_node_list();
 489 }
 490 
 491 int PhaseRenumberLive::new_index(int old_idx) {
 492   assert(_is_pass_finished, "not finished");
 493   if (_old2new_map.at(old_idx) == -1) { // absent
 494     // Allocate a placeholder to preserve uniqueness
 495     _old2new_map.at_put(old_idx, _live_node_count);
 496     _live_node_count++;
 497   }
 498   return _old2new_map.at(old_idx);
 499 }
 500 
 501 int PhaseRenumberLive::update_embedded_ids(Node* n) {
 502   int no_of_updates = 0;
 503   if (n->is_Phi()) {
 504     PhiNode* phi = n->as_Phi();
 505     if (phi->_inst_id != -1) {
 506       if (!_is_pass_finished) {
 507         return -1; // delay
 508       }
 509       int new_idx = new_index(phi->_inst_id);
 510       assert(new_idx != -1, "");
 511       phi->_inst_id = new_idx;
 512       no_of_updates++;
 513     }
 514     if (phi->_inst_mem_id != -1) {
 515       if (!_is_pass_finished) {
 516         return -1; // delay
 517       }
 518       int new_idx = new_index(phi->_inst_mem_id);
 519       assert(new_idx != -1, "");
 520       phi->_inst_mem_id = new_idx;
 521       no_of_updates++;
 522     }
 523   }
 524 
 525   const Type* type = _new_type_array.fast_lookup(n->_idx);
 526   if (type != nullptr && type->isa_oopptr() && type->is_oopptr()->is_known_instance()) {
 527     if (!_is_pass_finished) {
 528         return -1; // delay
 529     }
 530     int old_idx = type->is_oopptr()->instance_id();
 531     int new_idx = new_index(old_idx);
 532     const Type* new_type = type->is_oopptr()->with_instance_id(new_idx);
 533     _new_type_array.map(n->_idx, new_type);
 534     no_of_updates++;
 535   }
 536 
 537   return no_of_updates;
 538 }
 539 
 540 void PhaseValues::init_con_caches() {
 541   memset(_icons,0,sizeof(_icons));
 542   memset(_lcons,0,sizeof(_lcons));
 543   memset(_zcons,0,sizeof(_zcons));
 544 }
 545 
 546 PhaseIterGVN* PhaseValues::is_IterGVN() {
 547   return (_phase == PhaseValuesType::iter_gvn || _phase == PhaseValuesType::ccp) ? static_cast<PhaseIterGVN*>(this) : nullptr;
 548 }
 549 
 550 //--------------------------------find_int_type--------------------------------
 551 const TypeInt* PhaseValues::find_int_type(Node* n) {
 552   if (n == nullptr)  return nullptr;
 553   // Call type_or_null(n) to determine node's type since we might be in
 554   // parse phase and call n->Value() may return wrong type.
 555   // (For example, a phi node at the beginning of loop parsing is not ready.)
 556   const Type* t = type_or_null(n);
 557   if (t == nullptr)  return nullptr;
 558   return t->isa_int();
 559 }
 560 
 561 
 562 //-------------------------------find_long_type--------------------------------
 563 const TypeLong* PhaseValues::find_long_type(Node* n) {
 564   if (n == nullptr)  return nullptr;
 565   // (See comment above on type_or_null.)
 566   const Type* t = type_or_null(n);
 567   if (t == nullptr)  return nullptr;
 568   return t->isa_long();
 569 }
 570 
 571 //------------------------------~PhaseValues-----------------------------------
 572 #ifndef PRODUCT
 573 PhaseValues::~PhaseValues() {
 574   // Statistics for NodeHash
 575   _table.dump();
 576   // Statistics for value progress and efficiency
 577   if( PrintCompilation && Verbose && WizardMode ) {
 578     tty->print("\n%sValues: %d nodes ---> " UINT64_FORMAT "/%d (%d)",
 579       is_IterGVN() ? "Iter" : "    ", C->unique(), made_progress(), made_transforms(), made_new_values());
 580     if( made_transforms() != 0 ) {
 581       tty->print_cr("  ratio %f", made_progress()/(float)made_transforms() );
 582     } else {
 583       tty->cr();
 584     }
 585   }
 586 }
 587 #endif
 588 
 589 //------------------------------makecon----------------------------------------
 590 ConNode* PhaseValues::makecon(const Type* t) {
 591   assert(t->singleton(), "must be a constant");
 592   assert(!t->empty() || t == Type::TOP, "must not be vacuous range");
 593   switch (t->base()) {  // fast paths
 594   case Type::Half:
 595   case Type::Top:  return (ConNode*) C->top();
 596   case Type::Int:  return intcon( t->is_int()->get_con() );
 597   case Type::Long: return longcon( t->is_long()->get_con() );
 598   default:         break;
 599   }
 600   if (t->is_zero_type())
 601     return zerocon(t->basic_type());
 602   return uncached_makecon(t);
 603 }
 604 
 605 //--------------------------uncached_makecon-----------------------------------
 606 // Make an idealized constant - one of ConINode, ConPNode, etc.
 607 ConNode* PhaseValues::uncached_makecon(const Type *t) {
 608   assert(t->singleton(), "must be a constant");
 609   ConNode* x = ConNode::make(t);
 610   ConNode* k = (ConNode*)hash_find_insert(x); // Value numbering
 611   if (k == nullptr) {
 612     set_type(x, t);             // Missed, provide type mapping
 613     GrowableArray<Node_Notes*>* nna = C->node_note_array();
 614     if (nna != nullptr) {
 615       Node_Notes* loc = C->locate_node_notes(nna, x->_idx, true);
 616       loc->clear(); // do not put debug info on constants
 617     }
 618   } else {
 619     x->destruct(this);          // Hit, destroy duplicate constant
 620     x = k;                      // use existing constant
 621   }
 622   return x;
 623 }
 624 
 625 //------------------------------intcon-----------------------------------------
 626 // Fast integer constant.  Same as "transform(new ConINode(TypeInt::make(i)))"
 627 ConINode* PhaseValues::intcon(jint i) {
 628   // Small integer?  Check cache! Check that cached node is not dead
 629   if (i >= _icon_min && i <= _icon_max) {
 630     ConINode* icon = _icons[i-_icon_min];
 631     if (icon != nullptr && icon->in(TypeFunc::Control) != nullptr)
 632       return icon;
 633   }
 634   ConINode* icon = (ConINode*) uncached_makecon(TypeInt::make(i));
 635   assert(icon->is_Con(), "");
 636   if (i >= _icon_min && i <= _icon_max)
 637     _icons[i-_icon_min] = icon;   // Cache small integers
 638   return icon;
 639 }
 640 
 641 //------------------------------longcon----------------------------------------
 642 // Fast long constant.
 643 ConLNode* PhaseValues::longcon(jlong l) {
 644   // Small integer?  Check cache! Check that cached node is not dead
 645   if (l >= _lcon_min && l <= _lcon_max) {
 646     ConLNode* lcon = _lcons[l-_lcon_min];
 647     if (lcon != nullptr && lcon->in(TypeFunc::Control) != nullptr)
 648       return lcon;
 649   }
 650   ConLNode* lcon = (ConLNode*) uncached_makecon(TypeLong::make(l));
 651   assert(lcon->is_Con(), "");
 652   if (l >= _lcon_min && l <= _lcon_max)
 653     _lcons[l-_lcon_min] = lcon;      // Cache small integers
 654   return lcon;
 655 }
 656 ConNode* PhaseValues::integercon(jlong l, BasicType bt) {
 657   if (bt == T_INT) {
 658     return intcon(checked_cast<jint>(l));
 659   }
 660   assert(bt == T_LONG, "not an integer");
 661   return longcon(l);
 662 }
 663 
 664 
 665 //------------------------------zerocon-----------------------------------------
 666 // Fast zero or null constant. Same as "transform(ConNode::make(Type::get_zero_type(bt)))"
 667 ConNode* PhaseValues::zerocon(BasicType bt) {
 668   assert((uint)bt <= _zcon_max, "domain check");
 669   ConNode* zcon = _zcons[bt];
 670   if (zcon != nullptr && zcon->in(TypeFunc::Control) != nullptr)
 671     return zcon;
 672   zcon = (ConNode*) uncached_makecon(Type::get_zero_type(bt));
 673   _zcons[bt] = zcon;
 674   return zcon;
 675 }
 676 
 677 
 678 
 679 //=============================================================================
 680 Node* PhaseGVN::apply_ideal(Node* k, bool can_reshape) {
 681   Node* i = BarrierSet::barrier_set()->barrier_set_c2()->ideal_node(this, k, can_reshape);
 682   if (i == nullptr) {
 683     i = k->Ideal(this, can_reshape);
 684   }
 685   return i;
 686 }
 687 
 688 //------------------------------transform--------------------------------------
 689 // Return a node which computes the same function as this node, but
 690 // in a faster or cheaper fashion.
 691 Node* PhaseGVN::transform(Node* n) {
 692   NOT_PRODUCT( set_transforms(); )
 693 
 694   // Apply the Ideal call in a loop until it no longer applies
 695   Node* k = n;
 696   Node* i = apply_ideal(k, /*can_reshape=*/false);
 697   NOT_PRODUCT(uint loop_count = 1;)
 698   while (i != nullptr) {
 699     assert(i->_idx >= k->_idx, "Idealize should return new nodes, use Identity to return old nodes" );
 700     k = i;
 701 #ifdef ASSERT
 702     if (loop_count >= K + C->live_nodes()) {
 703       dump_infinite_loop_info(i, "PhaseGVN::transform");
 704     }
 705 #endif
 706     i = apply_ideal(k, /*can_reshape=*/false);
 707     NOT_PRODUCT(loop_count++;)
 708   }
 709   NOT_PRODUCT(if (loop_count != 0) { set_progress(); })
 710 
 711   // If brand new node, make space in type array.
 712   ensure_type_or_null(k);
 713 
 714   // Since I just called 'Value' to compute the set of run-time values
 715   // for this Node, and 'Value' is non-local (and therefore expensive) I'll
 716   // cache Value.  Later requests for the local phase->type of this Node can
 717   // use the cached Value instead of suffering with 'bottom_type'.
 718   const Type* t = k->Value(this); // Get runtime Value set
 719   assert(t != nullptr, "value sanity");
 720   if (type_or_null(k) != t) {
 721 #ifndef PRODUCT
 722     // Do not count initial visit to node as a transformation
 723     if (type_or_null(k) == nullptr) {
 724       inc_new_values();
 725       set_progress();
 726     }
 727 #endif
 728     set_type(k, t);
 729     // If k is a TypeNode, capture any more-precise type permanently into Node
 730     k->raise_bottom_type(t);
 731   }
 732 
 733   if (t->singleton() && !k->is_Con()) {
 734     set_progress();
 735     return makecon(t);          // Turn into a constant
 736   }
 737 
 738   // Now check for Identities
 739   i = k->Identity(this);        // Look for a nearby replacement
 740   if (i != k) {                 // Found? Return replacement!
 741     set_progress();
 742     return i;
 743   }
 744 
 745   // Global Value Numbering
 746   i = hash_find_insert(k);      // Insert if new
 747   if (i && (i != k)) {
 748     // Return the pre-existing node
 749     set_progress();
 750     return i;
 751   }
 752 
 753   // Return Idealized original
 754   return k;
 755 }
 756 
 757 bool PhaseGVN::is_dominator_helper(Node *d, Node *n, bool linear_only) {
 758   if (d->is_top() || (d->is_Proj() && d->in(0)->is_top())) {
 759     return false;
 760   }
 761   if (n->is_top() || (n->is_Proj() && n->in(0)->is_top())) {
 762     return false;
 763   }
 764   assert(d->is_CFG() && n->is_CFG(), "must have CFG nodes");
 765   int i = 0;
 766   while (d != n) {
 767     n = IfNode::up_one_dom(n, linear_only);
 768     i++;
 769     if (n == nullptr || i >= 100) {
 770       return false;
 771     }
 772   }
 773   return true;
 774 }
 775 
 776 #ifdef ASSERT
 777 //------------------------------dead_loop_check--------------------------------
 778 // Check for a simple dead loop when a data node references itself directly
 779 // or through an other data node excluding cons and phis.
 780 void PhaseGVN::dead_loop_check(Node* n) {
 781   // Phi may reference itself in a loop.
 782   if (n == nullptr || n->is_dead_loop_safe() || n->is_CFG()) {
 783     return;
 784   }
 785 
 786   // Do 2 levels check and only data inputs.
 787   for (uint i = 1; i < n->req(); i++) {
 788     Node* in = n->in(i);
 789     if (in == n) {
 790       n->dump_bfs(100, nullptr, "");
 791       fatal("Dead loop detected, node references itself: %s (%d)",
 792             n->Name(), n->_idx);
 793     }
 794 
 795     if (in == nullptr || in->is_dead_loop_safe()) {
 796       continue;
 797     }
 798     for (uint j = 1; j < in->req(); j++) {
 799       if (in->in(j) == n) {
 800         n->dump_bfs(100, nullptr, "");
 801         fatal("Dead loop detected, node input references current node: %s (%d) -> %s (%d)",
 802               in->Name(), in->_idx, n->Name(), n->_idx);
 803       }
 804       if (in->in(j) == in) {
 805         n->dump_bfs(100, nullptr, "");
 806         fatal("Dead loop detected, node input references itself: %s (%d)",
 807               in->Name(), in->_idx);
 808       }
 809     }
 810   }
 811 }
 812 
 813 
 814 /**
 815  * Dumps information that can help to debug the problem. A debug
 816  * build fails with an assert.
 817  */
 818 void PhaseGVN::dump_infinite_loop_info(Node* n, const char* where) {
 819   n->dump(4);
 820   assert(false, "infinite loop in %s", where);
 821 }
 822 #endif
 823 
 824 //=============================================================================
 825 //------------------------------PhaseIterGVN-----------------------------------
 826 // Initialize with previous PhaseIterGVN info; used by PhaseCCP
 827 PhaseIterGVN::PhaseIterGVN(PhaseIterGVN* igvn) : _delay_transform(igvn->_delay_transform),
 828                                                  _worklist(*C->igvn_worklist())
 829 {
 830   _phase = PhaseValuesType::iter_gvn;
 831   assert(&_worklist == &igvn->_worklist, "sanity");
 832 }
 833 
 834 //------------------------------PhaseIterGVN-----------------------------------
 835 // Initialize from scratch
 836 PhaseIterGVN::PhaseIterGVN() : _delay_transform(false),
 837                                _worklist(*C->igvn_worklist())
 838 {
 839   _phase = PhaseValuesType::iter_gvn;
 840   uint max;
 841 
 842   // Dead nodes in the hash table inherited from GVN were not treated as
 843   // roots during def-use info creation; hence they represent an invisible
 844   // use.  Clear them out.
 845   max = _table.size();
 846   for( uint i = 0; i < max; ++i ) {
 847     Node *n = _table.at(i);
 848     if(n != nullptr && n != _table.sentinel() && n->outcnt() == 0) {
 849       if( n->is_top() ) continue;
 850       // If remove_useless_nodes() has run, we expect no such nodes left.
 851       assert(false, "remove_useless_nodes missed this node");
 852       hash_delete(n);
 853     }
 854   }
 855 
 856   // Any Phis or Regions on the worklist probably had uses that could not
 857   // make more progress because the uses were made while the Phis and Regions
 858   // were in half-built states.  Put all uses of Phis and Regions on worklist.
 859   max = _worklist.size();
 860   for( uint j = 0; j < max; j++ ) {
 861     Node *n = _worklist.at(j);
 862     uint uop = n->Opcode();
 863     if( uop == Op_Phi || uop == Op_Region ||
 864         n->is_Type() ||
 865         n->is_Mem() )
 866       add_users_to_worklist(n);
 867   }
 868 }
 869 
 870 void PhaseIterGVN::shuffle_worklist() {
 871   if (_worklist.size() < 2) return;
 872   for (uint i = _worklist.size() - 1; i >= 1; i--) {
 873     uint j = C->random() % (i + 1);
 874     swap(_worklist.adr()[i], _worklist.adr()[j]);
 875   }
 876 }
 877 
 878 #ifndef PRODUCT
 879 void PhaseIterGVN::verify_step(Node* n) {
 880   if (is_verify_def_use()) {
 881     ResourceMark rm;
 882     VectorSet visited;
 883     Node_List worklist;
 884 
 885     _verify_window[_verify_counter % _verify_window_size] = n;
 886     ++_verify_counter;
 887     if (C->unique() < 1000 || 0 == _verify_counter % (C->unique() < 10000 ? 10 : 100)) {
 888       ++_verify_full_passes;
 889       worklist.push(C->root());
 890       Node::verify(-1, visited, worklist);
 891       return;
 892     }
 893     for (int i = 0; i < _verify_window_size; i++) {
 894       Node* n = _verify_window[i];
 895       if (n == nullptr) {
 896         continue;
 897       }
 898       if (n->in(0) == NodeSentinel) { // xform_idom
 899         _verify_window[i] = n->in(1);
 900         --i;
 901         continue;
 902       }
 903       // Typical fanout is 1-2, so this call visits about 6 nodes.
 904       if (!visited.test_set(n->_idx)) {
 905         worklist.push(n);
 906       }
 907     }
 908     Node::verify(4, visited, worklist);
 909   }
 910 }
 911 
 912 void PhaseIterGVN::trace_PhaseIterGVN(Node* n, Node* nn, const Type* oldtype) {
 913   const Type* newtype = type_or_null(n);
 914   if (nn != n || oldtype != newtype) {
 915     C->print_method(PHASE_AFTER_ITER_GVN_STEP, 5, n);
 916   }
 917   if (TraceIterativeGVN) {
 918     uint wlsize = _worklist.size();
 919     if (nn != n) {
 920       // print old node
 921       tty->print("< ");
 922       if (oldtype != newtype && oldtype != nullptr) {
 923         oldtype->dump();
 924       }
 925       do { tty->print("\t"); } while (tty->position() < 16);
 926       tty->print("<");
 927       n->dump();
 928     }
 929     if (oldtype != newtype || nn != n) {
 930       // print new node and/or new type
 931       if (oldtype == nullptr) {
 932         tty->print("* ");
 933       } else if (nn != n) {
 934         tty->print("> ");
 935       } else {
 936         tty->print("= ");
 937       }
 938       if (newtype == nullptr) {
 939         tty->print("null");
 940       } else {
 941         newtype->dump();
 942       }
 943       do { tty->print("\t"); } while (tty->position() < 16);
 944       nn->dump();
 945     }
 946     if (Verbose && wlsize < _worklist.size()) {
 947       tty->print("  Push {");
 948       while (wlsize != _worklist.size()) {
 949         Node* pushed = _worklist.at(wlsize++);
 950         tty->print(" %d", pushed->_idx);
 951       }
 952       tty->print_cr(" }");
 953     }
 954     if (nn != n) {
 955       // ignore n, it might be subsumed
 956       verify_step((Node*) nullptr);
 957     }
 958   }
 959 }
 960 
 961 void PhaseIterGVN::init_verifyPhaseIterGVN() {
 962   _verify_counter = 0;
 963   _verify_full_passes = 0;
 964   for (int i = 0; i < _verify_window_size; i++) {
 965     _verify_window[i] = nullptr;
 966   }
 967 #ifdef ASSERT
 968   // Verify that all modified nodes are on _worklist
 969   Unique_Node_List* modified_list = C->modified_nodes();
 970   while (modified_list != nullptr && modified_list->size()) {
 971     Node* n = modified_list->pop();
 972     if (!n->is_Con() && !_worklist.member(n)) {
 973       n->dump();
 974       fatal("modified node is not on IGVN._worklist");
 975     }
 976   }
 977 #endif
 978 }
 979 
 980 void PhaseIterGVN::verify_PhaseIterGVN(bool deep_revisit_converged) {
 981 #ifdef ASSERT
 982   // Verify nodes with changed inputs.
 983   Unique_Node_List* modified_list = C->modified_nodes();
 984   while (modified_list != nullptr && modified_list->size()) {
 985     Node* n = modified_list->pop();
 986     if (!n->is_Con()) { // skip Con nodes
 987       n->dump();
 988       fatal("modified node was not processed by IGVN.transform_old()");
 989     }
 990   }
 991 #endif
 992 
 993   C->verify_graph_edges();
 994   if (is_verify_def_use() && PrintOpto) {
 995     if (_verify_counter == _verify_full_passes) {
 996       tty->print_cr("VerifyIterativeGVN: %d transforms and verify passes",
 997                     (int) _verify_full_passes);
 998     } else {
 999       tty->print_cr("VerifyIterativeGVN: %d transforms, %d full verify passes",
1000                   (int) _verify_counter, (int) _verify_full_passes);
1001     }
1002   }
1003 
1004 #ifdef ASSERT
1005   if (modified_list != nullptr) {
1006     while (modified_list->size() > 0) {
1007       Node* n = modified_list->pop();
1008       n->dump();
1009       assert(false, "VerifyIterativeGVN: new modified node was added");
1010     }
1011   }
1012 
1013   verify_optimize(deep_revisit_converged);
1014 #endif
1015 }
1016 #endif /* PRODUCT */
1017 
1018 #ifdef ASSERT
1019 /**
1020  * Dumps information that can help to debug the problem. A debug
1021  * build fails with an assert.
1022  */
1023 void PhaseIterGVN::dump_infinite_loop_info(Node* n, const char* where) {
1024   n->dump(4);
1025   _worklist.dump();
1026   assert(false, "infinite loop in %s", where);
1027 }
1028 
1029 /**
1030  * Prints out information about IGVN if the 'verbose' option is used.
1031  */
1032 void PhaseIterGVN::trace_PhaseIterGVN_verbose(Node* n, int num_processed) {
1033   if (TraceIterativeGVN && Verbose) {
1034     tty->print("  Pop ");
1035     n->dump();
1036     if ((num_processed % 100) == 0) {
1037       _worklist.print_set();
1038     }
1039   }
1040 }
1041 #endif /* ASSERT */
1042 
1043 bool PhaseIterGVN::needs_deep_revisit(const Node* n) const {
1044   // LoadNode::Value() -> can_see_stored_value() walks up through many memory
1045   // nodes. LoadNode::Ideal() -> find_previous_store() also walks up to 50
1046   // nodes through stores and arraycopy nodes.
1047   if (n->is_Load()) {
1048     return true;
1049   }
1050   // CmpPNode::sub() -> detect_ptr_independence() -> all_controls_dominate()
1051   // walks CFG dominator relationships extensively. This only triggers when
1052   // both inputs are oop pointers (subnode.cpp:984).
1053   if (n->Opcode() == Op_CmpP) {
1054     const Type* t1 = type_or_null(n->in(1));
1055     const Type* t2 = type_or_null(n->in(2));
1056     return t1 != nullptr && t1->isa_oopptr() &&
1057            t2 != nullptr && t2->isa_oopptr();
1058   }
1059   // IfNode::Ideal() -> search_identical() walks up the CFG dominator tree.
1060   // RangeCheckNode::Ideal() scans up to ~999 nodes up the chain.
1061   // CountedLoopEndNode/LongCountedLoopEndNode::Ideal() via simple_subsuming
1062   // looks for dominating test that subsumes the current test.
1063   switch (n->Opcode()) {
1064   case Op_If:
1065   case Op_RangeCheck:
1066   case Op_CountedLoopEnd:
1067   case Op_LongCountedLoopEnd:
1068     return true;
1069   default:
1070     break;
1071   }
1072   return false;
1073 }
1074 
1075 bool PhaseIterGVN::drain_worklist() {
1076   uint loop_count = 1;
1077   const int max_live_nodes_increase_per_iteration = NodeLimitFudgeFactor * 5;
1078   while (_worklist.size() != 0) {
1079     if (C->check_node_count(max_live_nodes_increase_per_iteration, "Out of nodes")) {
1080       C->print_method(PHASE_AFTER_ITER_GVN, 3);
1081       return true;
1082     }
1083     Node* n  = _worklist.pop();
1084     if (loop_count >= K * C->live_nodes()) {
1085       DEBUG_ONLY(dump_infinite_loop_info(n, "PhaseIterGVN::drain_worklist");)
1086       C->record_method_not_compilable("infinite loop in PhaseIterGVN::drain_worklist");
1087       C->print_method(PHASE_AFTER_ITER_GVN, 3);
1088       return true;
1089     }
1090     DEBUG_ONLY(trace_PhaseIterGVN_verbose(n, _num_processed++);)
1091     if (n->outcnt() != 0) {
1092       NOT_PRODUCT(const Type* oldtype = type_or_null(n));
1093       // Do the transformation
1094       DEBUG_ONLY(int live_nodes_before = C->live_nodes();)
1095       Node* nn = transform_old(n);
1096       DEBUG_ONLY(int live_nodes_after = C->live_nodes();)
1097       // Ensure we did not increase the live node count with more than
1098       // max_live_nodes_increase_per_iteration during the call to transform_old.
1099       DEBUG_ONLY(int increase = live_nodes_after - live_nodes_before;)
1100       assert(increase < max_live_nodes_increase_per_iteration,
1101              "excessive live node increase in single iteration of IGVN: %d "
1102              "(should be at most %d)",
1103              increase, max_live_nodes_increase_per_iteration);
1104       NOT_PRODUCT(trace_PhaseIterGVN(n, nn, oldtype);)
1105     } else if (!n->is_top()) {
1106       remove_dead_node(n, NodeOrigin::Graph);
1107     }
1108     loop_count++;
1109   }
1110   return false;
1111 }
1112 
1113 void PhaseIterGVN::push_deep_revisit_candidates() {
1114   ResourceMark rm;
1115   Unique_Node_List all_nodes;
1116   all_nodes.push(C->root());
1117   for (uint j = 0; j < all_nodes.size(); j++) {
1118     Node* n = all_nodes.at(j);
1119     if (needs_deep_revisit(n)) {
1120       _worklist.push(n);
1121     }
1122     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1123       all_nodes.push(n->fast_out(i));
1124     }
1125   }
1126 }
1127 
1128 bool PhaseIterGVN::deep_revisit() {
1129   // Re-process nodes that inspect the graph deeply. After the main worklist drains, walk
1130   // the graph to find all live deep-inspection nodes and push them to the worklist
1131   // for re-evaluation. If any produce changes, drain the worklist again.
1132   // Repeat until stable. This mirrors PhaseCCP::analyze()'s revisit loop.
1133   const uint max_deep_revisit_rounds = 10; // typically converges in <2 rounds
1134   uint round = 0;
1135   for (; round < max_deep_revisit_rounds; round++) {
1136     push_deep_revisit_candidates();
1137     if (_worklist.size() == 0) {
1138       break; // No deep-inspection nodes to revisit, done.
1139     }
1140 
1141 #ifndef PRODUCT
1142     uint candidates = _worklist.size();
1143     uint n_if = 0; uint n_rc = 0; uint n_load = 0; uint n_cmpp = 0; uint n_cle = 0; uint n_lcle = 0;
1144     if (TraceIterativeGVN) {
1145       for (uint i = 0; i < _worklist.size(); i++) {
1146         Node* n = _worklist.at(i);
1147         switch (n->Opcode()) {
1148         case Op_If:                 n_if++;   break;
1149         case Op_RangeCheck:         n_rc++;   break;
1150         case Op_CountedLoopEnd:     n_cle++;  break;
1151         case Op_LongCountedLoopEnd: n_lcle++; break;
1152         case Op_CmpP:               n_cmpp++; break;
1153         default: if (n->is_Load())  n_load++; break;
1154         }
1155       }
1156     }
1157 #endif
1158 
1159     // Convergence: if the drain does not make progress (no Ideal, Value, Identity or GVN changes),
1160     // we are at a fixed point. We use made_progress() rather than live_nodes because live_nodes
1161     // misses non-structural changes like a LoadNode dropping its control input.
1162     uint progress_before = made_progress();
1163     if (drain_worklist()) {
1164       return false;
1165     }
1166     uint progress = made_progress() - progress_before;
1167 
1168 #ifndef PRODUCT
1169     if (TraceIterativeGVN) {
1170       tty->print("deep_revisit round %u: %u candidates (If=%u RC=%u Load=%u CmpP=%u CLE=%u LCLE=%u), progress=%u (%s)",
1171                  round, candidates, n_if, n_rc, n_load, n_cmpp, n_cle, n_lcle, progress, progress != 0 ? "changed" : "converged");
1172       if (C->method() != nullptr) {
1173         tty->print(", ");
1174         C->method()->print_short_name(tty);
1175       }
1176       tty->cr();
1177     }
1178 #endif
1179 
1180     if (progress == 0) {
1181       break;
1182     }
1183   }
1184   return round < max_deep_revisit_rounds;
1185 }
1186 
1187 void PhaseIterGVN::optimize(bool deep) {
1188   bool deep_revisit_converged = false;
1189   DEBUG_ONLY(_num_processed = 0;)
1190   NOT_PRODUCT(init_verifyPhaseIterGVN();)
1191   NOT_PRODUCT(C->reset_igv_phase_iter(PHASE_AFTER_ITER_GVN_STEP);)
1192   C->print_method(PHASE_BEFORE_ITER_GVN, 3);
1193   if (StressIGVN) {
1194     shuffle_worklist();
1195   }
1196 
1197   // Pull from worklist and transform the node.
1198   if (drain_worklist()) {
1199     return;
1200   }
1201 
1202   if (deep && UseDeepIGVNRevisit) {
1203     deep_revisit_converged = deep_revisit();
1204     if (C->failing()) {
1205       return;
1206     }
1207   }
1208 
1209   NOT_PRODUCT(verify_PhaseIterGVN(deep_revisit_converged);)
1210   C->print_method(PHASE_AFTER_ITER_GVN, 3);
1211 }
1212 
1213 #ifdef ASSERT
1214 void PhaseIterGVN::verify_optimize(bool deep_revisit_converged) {
1215   assert(_worklist.size() == 0, "igvn worklist must be empty before verify");
1216 
1217   if (is_verify_Value() ||
1218       is_verify_Ideal() ||
1219       is_verify_Identity() ||
1220       is_verify_invariants()) {
1221     ResourceMark rm;
1222     Unique_Node_List worklist;
1223     // BFS all nodes, starting at root
1224     worklist.push(C->root());
1225     for (uint j = 0; j < worklist.size(); ++j) {
1226       Node* n = worklist.at(j);
1227       // If we get an assert here, check why the reported node was not processed again in IGVN.
1228       // We should either make sure that this node is properly added back to the IGVN worklist
1229       // in PhaseIterGVN::add_users_to_worklist to update it again or add an exception
1230       // in the verification methods below if that is not possible for some reason (like Load nodes).
1231       if (is_verify_Value()) {
1232         verify_Value_for(n, deep_revisit_converged /* strict */);
1233       }
1234       if (is_verify_Ideal()) {
1235         verify_Ideal_for(n, false /* can_reshape */, deep_revisit_converged);
1236         verify_Ideal_for(n, true  /* can_reshape */, deep_revisit_converged);
1237       }
1238       if (is_verify_Identity()) {
1239         verify_Identity_for(n);
1240       }
1241       if (is_verify_invariants()) {
1242         verify_node_invariants_for(n);
1243       }
1244 
1245       // traverse all inputs and outputs
1246       for (uint i = 0; i < n->req(); i++) {
1247         if (n->in(i) != nullptr) {
1248           worklist.push(n->in(i));
1249         }
1250       }
1251       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1252         worklist.push(n->fast_out(i));
1253       }
1254     }
1255   }
1256 
1257   verify_empty_worklist(nullptr);
1258 }
1259 
1260 void PhaseIterGVN::verify_empty_worklist(Node* node) {
1261   // Verify that the igvn worklist is empty. If no optimization happened, then
1262   // nothing needs to be on the worklist.
1263   if (_worklist.size() == 0) { return; }
1264 
1265   stringStream ss; // Print as a block without tty lock.
1266   for (uint j = 0; j < _worklist.size(); j++) {
1267     Node* n = _worklist.at(j);
1268     ss.print("igvn.worklist[%d] ", j);
1269     n->dump("\n", false, &ss);
1270   }
1271   if (_worklist.size() != 0 && node != nullptr) {
1272     ss.print_cr("Previously optimized:");
1273     node->dump("\n", false, &ss);
1274   }
1275   tty->print_cr("%s", ss.as_string());
1276   assert(false, "igvn worklist must still be empty after verify");
1277 }
1278 
1279 // Check that type(n) == n->Value(), asserts if we have a failure.
1280 // We have a list of exceptions, see detailed comments in code.
1281 // (1) Integer "widen" changes, but the range is the same.
1282 // (2) LoadNode performs deep traversals. Load is not notified for changes far away.
1283 // (3) CmpPNode performs deep traversals if it compares oopptr. CmpP is not notified for changes far away.
1284 void PhaseIterGVN::verify_Value_for(const Node* n, bool strict) {
1285   // If we assert inside type(n), because the type is still a null, then maybe
1286   // the node never went through gvn.transform, which would be a bug.
1287   const Type* told = type(n);
1288   const Type* tnew = n->Value(this);
1289   if (told == tnew) {
1290     return;
1291   }
1292   // Exception (1)
1293   // Integer "widen" changes, but range is the same.
1294   if (told->isa_integer(tnew->basic_type()) != nullptr) { // both either int or long
1295     const TypeInteger* t0 = told->is_integer(tnew->basic_type());
1296     const TypeInteger* t1 = tnew->is_integer(tnew->basic_type());
1297     if (t0->lo_as_long() == t1->lo_as_long() &&
1298         t0->hi_as_long() == t1->hi_as_long()) {
1299       return; // ignore integer widen
1300     }
1301   }
1302   // Exception (2)
1303   // LoadNode performs deep traversals. Load is not notified for changes far away.
1304   if (!strict && n->is_Load() && !told->singleton()) {
1305     // MemNode::can_see_stored_value looks up through many memory nodes,
1306     // which means we would need to notify modifications from far up in
1307     // the inputs all the way down to the LoadNode. We don't do that.
1308     return;
1309   }
1310   // Exception (3)
1311   // CmpPNode performs deep traversals if it compares oopptr. CmpP is not notified for changes far away.
1312   if (!strict && n->Opcode() == Op_CmpP && type(n->in(1))->isa_oopptr() && type(n->in(2))->isa_oopptr()) {
1313     // SubNode::Value
1314     // CmpPNode::sub
1315     // MemNode::detect_ptr_independence
1316     // MemNode::all_controls_dominate
1317     // We find all controls of a pointer load, and see if they dominate the control of
1318     // an allocation. If they all dominate, we know the allocation is after (independent)
1319     // of the pointer load, and we can say the pointers are different. For this we call
1320     // n->dominates(sub, nlist) to check if controls n of the pointer load dominate the
1321     // control sub of the allocation. The problems is that sometimes dominates answers
1322     // false conservatively, and later it can determine that it is indeed true. Loops with
1323     // Region heads can lead to giving up, whereas LoopNodes can be skipped easier, and
1324     // so the traversal becomes more powerful. This is difficult to remedy, we would have
1325     // to notify the CmpP of CFG updates. Luckily, we recompute CmpP::Value during CCP
1326     // after loop-opts, so that should take care of many of these cases.
1327     return;
1328   }
1329 
1330   stringStream ss; // Print as a block without tty lock.
1331   ss.cr();
1332   ss.print_cr("Missed Value optimization:");
1333   n->dump_bfs(3, nullptr, "", &ss);
1334   ss.print_cr("Current type:");
1335   told->dump_on(&ss);
1336   ss.cr();
1337   ss.print_cr("Optimized type:");
1338   tnew->dump_on(&ss);
1339   ss.cr();
1340   tty->print_cr("%s", ss.as_string());
1341 
1342   switch (_phase) {
1343     case PhaseValuesType::iter_gvn:
1344       assert(false, "Missed Value optimization opportunity in PhaseIterGVN for %s",n->Name());
1345       break;
1346     case PhaseValuesType::ccp:
1347       assert(false, "PhaseCCP not at fixpoint: analysis result may be unsound for %s", n->Name());
1348       break;
1349     default:
1350       assert(false, "Unexpected phase");
1351       break;
1352   }
1353 }
1354 
1355 // Check that all Ideal optimizations that could be done were done.
1356 // Asserts if it found missed optimization opportunities or encountered unexpected changes, and
1357 //         returns normally otherwise (no missed optimization, or skipped verification).
1358 void PhaseIterGVN::verify_Ideal_for(Node* n, bool can_reshape, bool deep_revisit_converged) {
1359   if (!deep_revisit_converged && needs_deep_revisit(n)) {
1360     return;
1361   }
1362 
1363   // First, we check a list of exceptions, where we skip verification,
1364   // because there are known cases where Ideal can optimize after IGVN.
1365   // Some may be expected and cannot be fixed, and others should be fixed.
1366   switch (n->Opcode()) {
1367     // RegionNode::Ideal does "Skip around the useless IF diamond".
1368     //   245  IfTrue  === 244
1369     //   258  If  === 245 257
1370     //   259  IfTrue  === 258  [[ 263 ]]
1371     //   260  IfFalse  === 258  [[ 263 ]]
1372     //   263  Region  === 263 260 259  [[ 263 268 ]]
1373     // to
1374     //   245  IfTrue  === 244
1375     //   263  Region  === 263 245 _  [[ 263 268 ]]
1376     //
1377     // "Useless" means that there is no code in either branch of the If.
1378     // I found a case where this was not done yet during IGVN.
1379     // Why does the Region not get added to IGVN worklist when the If diamond becomes useless?
1380     //
1381     // Found with:
1382     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1383     case Op_Region:
1384       return;
1385 
1386     // In AddNode::Ideal, we call "commute", which swaps the inputs so
1387     // that smaller idx are first. Tracking it back, it led me to
1388     // PhaseIdealLoop::remix_address_expressions which swapped the edges.
1389     //
1390     // Example:
1391     //   Before PhaseIdealLoop::remix_address_expressions
1392     //     154  AddI  === _ 12 144
1393     //   After PhaseIdealLoop::remix_address_expressions
1394     //     154  AddI  === _ 144 12
1395     //   After AddNode::Ideal
1396     //     154  AddI  === _ 12 144
1397     //
1398     // I suspect that the node should be added to the IGVN worklist after
1399     // PhaseIdealLoop::remix_address_expressions
1400     //
1401     // This is the only case I looked at, there may be others. Found like this:
1402     //   java -XX:VerifyIterativeGVN=0100 -Xbatch --version
1403     //
1404     // The following hit the same logic in PhaseIdealLoop::remix_address_expressions.
1405     //
1406     // Note: currently all of these fail also for other reasons, for example
1407     // because of "commute" doing the reordering with the phi below. Once
1408     // that is resolved, we can come back to this issue here.
1409     //
1410     // case Op_AddD:
1411     // case Op_AddI:
1412     // case Op_AddL:
1413     // case Op_AddF:
1414     // case Op_MulI:
1415     // case Op_MulL:
1416     // case Op_MulF:
1417     // case Op_MulD:
1418     //   if (n->in(1)->_idx > n->in(2)->_idx) {
1419     //     // Expect "commute" to revert this case.
1420     //     return false;
1421     //   }
1422     //   break; // keep verifying
1423 
1424     // AddFNode::Ideal calls "commute", which can reorder the inputs for this:
1425     //   Check for tight loop increments: Loop-phi of Add of loop-phi
1426     // It wants to take the phi into in(1):
1427     //    471  Phi  === 435 38 390
1428     //    390  AddF  === _ 471 391
1429     //
1430     // Other Associative operators are also affected equally.
1431     //
1432     // Investigate why this does not happen earlier during IGVN.
1433     //
1434     // Found with:
1435     //   test/hotspot/jtreg/compiler/loopopts/superword/ReductionPerf.java
1436     //   -XX:VerifyIterativeGVN=1110
1437     case Op_AddD:
1438     //case Op_AddI: // Also affected for other reasons, see case further down.
1439     //case Op_AddL: // Also affected for other reasons, see case further down.
1440     case Op_AddF:
1441     case Op_MulI:
1442     case Op_MulL:
1443     case Op_MulF:
1444     case Op_MulD:
1445     case Op_MinF:
1446     case Op_MinD:
1447     case Op_MaxF:
1448     case Op_MaxD:
1449     // XorINode::Ideal
1450     // Found with:
1451     //   compiler/intrinsics/chacha/TestChaCha20.java
1452     //   -XX:VerifyIterativeGVN=1110
1453     case Op_XorI:
1454     case Op_XorL:
1455     // It seems we may have similar issues with the HF cases.
1456     // Found with aarch64:
1457     //   compiler/vectorization/TestFloat16VectorOperations.java
1458     //   -XX:VerifyIterativeGVN=1110
1459     case Op_AddHF:
1460     case Op_MulHF:
1461     case Op_MaxHF:
1462     case Op_MinHF:
1463       return;
1464 
1465     // In MulNode::Ideal the edges can be swapped to help value numbering:
1466     //
1467     //    // We are OK if right is a constant, or right is a load and
1468     //    // left is a non-constant.
1469     //    if( !(t2->singleton() ||
1470     //          (in(2)->is_Load() && !(t1->singleton() || in(1)->is_Load())) ) ) {
1471     //      if( t1->singleton() ||       // Left input is a constant?
1472     //          // Otherwise, sort inputs (commutativity) to help value numbering.
1473     //          (in(1)->_idx > in(2)->_idx) ) {
1474     //        swap_edges(1, 2);
1475     //
1476     // Why was this not done earlier during IGVN?
1477     //
1478     // Found with:
1479     //    test/hotspot/jtreg/gc/stress/gcbasher/TestGCBasherWithG1.java
1480     //    -XX:VerifyIterativeGVN=1110
1481     case Op_AndI:
1482     // Same for AndL.
1483     // Found with:
1484     //   compiler/intrinsics/bigInteger/MontgomeryMultiplyTest.java
1485     //    -XX:VerifyIterativeGVN=1110
1486     case Op_AndL:
1487       return;
1488 
1489     // SubLNode::Ideal does transform like:
1490     //   Convert "c1 - (y+c0)" into "(c1-c0) - y"
1491     //
1492     // In IGVN before verification:
1493     //   8423  ConvI2L  === _ 3519  [[ 8424 ]]  #long:-2
1494     //   8422  ConvI2L  === _ 8399  [[ 8424 ]]  #long:3..256:www
1495     //   8424  AddL  === _ 8422 8423  [[ 8383 ]]  !orig=[8382]
1496     //   8016  ConL  === 0  [[ 8383 ]]  #long:0
1497     //   8383  SubL  === _ 8016 8424  [[ 8156 ]]  !orig=[8154]
1498     //
1499     // And then in verification:
1500     //   8338  ConL  === 0  [[ 8339 8424 ]]  #long:-2     <----- Was constant folded.
1501     //   8422  ConvI2L  === _ 8399  [[ 8424 ]]  #long:3..256:www
1502     //   8424  AddL  === _ 8422 8338  [[ 8383 ]]  !orig=[8382]
1503     //   8016  ConL  === 0  [[ 8383 ]]  #long:0
1504     //   8383  SubL  === _ 8016 8424  [[ 8156 ]]  !orig=[8154]
1505     //
1506     // So the form changed from:
1507     //   c1 - (y + [8423  ConvI2L])
1508     // to
1509     //   c1 - (y + -2)
1510     // but the SubL was not added to the IGVN worklist. Investigate why.
1511     // There could be other issues too.
1512     //
1513     // There seems to be a related AddL IGVN optimization that triggers
1514     // the same SubL optimization, so investigate that too.
1515     //
1516     // Found with:
1517     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1518     case Op_SubL:
1519       return;
1520 
1521     // SubINode::Ideal does
1522     // Convert "x - (y+c0)" into "(x-y) - c0" AND
1523     // Convert "c1 - (y+c0)" into "(c1-c0) - y"
1524     //
1525     // Investigate why this does not yet happen during IGVN.
1526     //
1527     // Found with:
1528     //   test/hotspot/jtreg/compiler/c2/IVTest.java
1529     //   -XX:VerifyIterativeGVN=1110
1530     case Op_SubI:
1531       return;
1532 
1533     // AddNode::IdealIL does transform like:
1534     //   Convert x + (con - y) into "(x - y) + con"
1535     //
1536     // In IGVN before verification:
1537     //   8382  ConvI2L
1538     //   8381  ConvI2L  === _ 791  [[ 8383 ]]  #long:0
1539     //   8383  SubL  === _ 8381 8382
1540     //   8168  ConvI2L
1541     //   8156  AddL  === _ 8168 8383  [[ 8158 ]]
1542     //
1543     // And then in verification:
1544     //   8424  AddL
1545     //   8016  ConL  === 0  [[ 8383 ]]  #long:0  <--- Was constant folded.
1546     //   8383  SubL  === _ 8016 8424
1547     //   8168  ConvI2L
1548     //   8156  AddL  === _ 8168 8383  [[ 8158 ]]
1549     //
1550     // So the form changed from:
1551     //   x + (ConvI2L(0) - [8382  ConvI2L])
1552     // to
1553     //   x + (0 - [8424  AddL])
1554     // but the AddL was not added to the IGVN worklist. Investigate why.
1555     // There could be other issues, too. For example with "commute", see above.
1556     //
1557     // Found with:
1558     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1559     case Op_AddL:
1560       return;
1561 
1562     // SubTypeCheckNode::Ideal calls SubTypeCheckNode::verify_helper, which does
1563     //   Node* cmp = phase->transform(new CmpPNode(subklass, in(SuperKlass)));
1564     //   record_for_cleanup(cmp, phase);
1565     // This verification code in the Ideal code creates new nodes, and checks
1566     // if they fold in unexpected ways. This means some nodes are created and
1567     // added to the worklist, even if the SubTypeCheck is not optimized. This
1568     // goes agains the assumption of the verification here, which assumes that
1569     // if the node is not optimized, then no new nodes should be created, and
1570     // also no nodes should be added to the worklist.
1571     // I see two options:
1572     //  1) forbid what verify_helper does, because for each Ideal call it
1573     //     uses memory and that is suboptimal. But it is not clear how that
1574     //     verification can be done otherwise.
1575     //  2) Special case the verification here. Probably the new nodes that
1576     //     were just created are dead, i.e. they are not connected down to
1577     //     root. We could verify that, and remove those nodes from the graph
1578     //     by setting all their inputs to nullptr. And of course we would
1579     //     have to remove those nodes from the worklist.
1580     // Maybe there are other options too, I did not dig much deeper yet.
1581     //
1582     // Found with:
1583     //   java -XX:VerifyIterativeGVN=0100 -Xbatch --version
1584     case Op_SubTypeCheck:
1585       return;
1586 
1587     // LoopLimitNode::Ideal when stride is constant power-of-2, we can do a lowering
1588     // to other nodes: Conv, Add, Sub, Mul, And ...
1589     //
1590     //  107  ConI  === 0  [[ ... ]]  #int:2
1591     //   84  LoadRange  === _ 7 83
1592     //   50  ConI  === 0  [[ ... ]]  #int:0
1593     //  549  LoopLimit  === _ 50 84 107
1594     //
1595     // I stepped backward, to see how the node was generated, and I found that it was
1596     // created in PhaseIdealLoop::exact_limit and not changed since. It is added to the
1597     // IGVN worklist. I quickly checked when it goes into LoopLimitNode::Ideal after
1598     // that, and it seems we want to skip lowering it until after loop-opts, but never
1599     // add call record_for_post_loop_opts_igvn. This would be an easy fix, but there
1600     // could be other issues too.
1601     //
1602     // Fond with:
1603     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1604     case Op_LoopLimit:
1605       return;
1606 
1607     // PhiNode::Ideal calls split_flow_path, which tries to do this:
1608     // "This optimization tries to find two or more inputs of phi with the same constant
1609     // value. It then splits them into a separate Phi, and according Region."
1610     //
1611     // Example:
1612     //   130  DecodeN  === _ 129
1613     //    50  ConP  === 0  [[ 18 91 99 18 ]]  #null
1614     //    18  Phi  === 14 50 130 50  [[ 133 ]]  #java/lang/Object *  Oop:java/lang/Object *
1615     //
1616     //  turns into:
1617     //
1618     //    50  ConP  === 0  [[ 99 91 18 ]]  #null
1619     //   130  DecodeN  === _ 129  [[ 18 ]]
1620     //    18  Phi  === 14 130 50  [[ 133 ]]  #java/lang/Object *  Oop:java/lang/Object *
1621     //
1622     // We would have to investigate why this optimization does not happen during IGVN.
1623     // There could also be other issues - I did not investigate further yet.
1624     //
1625     // Found with:
1626     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1627     case Op_Phi:
1628       return;
1629 
1630     // MemBarNode::Ideal does "Eliminate volatile MemBars for scalar replaced objects".
1631     // For examle "The allocated object does not escape".
1632     //
1633     // It seems the difference to earlier calls to MemBarNode::Ideal, is that there
1634     // alloc->as_Allocate()->does_not_escape_thread() returned false, but in verification
1635     // it returned true. Why does the MemBarStoreStore not get added to the IGVN
1636     // worklist when this change happens?
1637     //
1638     // Found with:
1639     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1640     case Op_MemBarStoreStore:
1641       return;
1642 
1643     // ConvI2LNode::Ideal converts
1644     //   648  AddI  === _ 583 645  [[ 661 ]]
1645     //   661  ConvI2L  === _ 648  [[ 664 ]]  #long:0..maxint-1:www
1646     // into
1647     //   772  ConvI2L  === _ 645  [[ 773 ]]  #long:-120..maxint-61:www
1648     //   771  ConvI2L  === _ 583  [[ 773 ]]  #long:60..120:www
1649     //   773  AddL  === _ 771 772  [[ ]]
1650     //
1651     // We have to investigate why this does not happen during IGVN in this case.
1652     // There could also be other issues - I did not investigate further yet.
1653     //
1654     // Found with:
1655     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1656     case Op_ConvI2L:
1657       return;
1658 
1659     // AddNode::IdealIL can do this transform (and similar other ones):
1660     //   Convert "a*b+a*c into a*(b+c)
1661     // The example had AddI(MulI(a, b), MulI(a, c)). Why did this not happen
1662     // during IGVN? There was a mutation for one of the MulI, and only
1663     // after that the pattern was as needed for the optimization. The MulI
1664     // was added to the IGVN worklist, but not the AddI. This probably
1665     // can be fixed by adding the correct pattern in add_users_of_use_to_worklist.
1666     //
1667     // Found with:
1668     //   test/hotspot/jtreg/compiler/loopopts/superword/ReductionPerf.java
1669     //   -XX:VerifyIterativeGVN=1110
1670     case Op_AddI:
1671       return;
1672 
1673     // ArrayCopyNode::Ideal
1674     //    calls ArrayCopyNode::prepare_array_copy
1675     //    calls Compile::conv_I2X_index        -> is called with sizetype = intcon(0), I think that
1676     //                                            is not expected, and we create a range int:0..-1
1677     //    calls Compile::constrained_convI2L   -> creates ConvI2L(intcon(1), int:0..-1)
1678     //                                            note: the type is already empty!
1679     //    calls PhaseIterGVN::transform
1680     //    calls PhaseIterGVN::transform_old
1681     //    calls PhaseIterGVN::subsume_node     -> subsume ConvI2L with TOP
1682     //    calls Unique_Node_List::push         -> pushes TOP to worklist
1683     //
1684     // Once we get back to ArrayCopyNode::prepare_array_copy, we get back TOP, and
1685     // return false. This means we eventually return nullptr from ArrayCopyNode::Ideal.
1686     //
1687     // Question: is it ok to push anything to the worklist during ::Ideal, if we will
1688     //           return nullptr, indicating nothing happened?
1689     //           Is it smart to do transform in Compile::constrained_convI2L, and then
1690     //           check for TOP in calls ArrayCopyNode::prepare_array_copy?
1691     //           Should we just allow TOP to land on the worklist, as an exception?
1692     //
1693     // Found with:
1694     //   compiler/arraycopy/TestArrayCopyAsLoadsStores.java
1695     //   -XX:VerifyIterativeGVN=1110
1696     case Op_ArrayCopy:
1697       return;
1698 
1699     // CastLLNode::Ideal
1700     //    calls ConstraintCastNode::optimize_integer_cast -> pushes CastLL through SubL
1701     //
1702     // Could be a notification issue, where updates inputs of CastLL do not notify
1703     // down through SubL to CastLL.
1704     //
1705     // Found With:
1706     //   compiler/c2/TestMergeStoresMemorySegment.java#byte-array
1707     //   -XX:VerifyIterativeGVN=1110
1708     case Op_CastLL:
1709       return;
1710 
1711     // Similar case happens to CastII
1712     //
1713     // Found With:
1714     //   compiler/c2/TestScalarReplacementMaxLiveNodes.java
1715     //   -XX:VerifyIterativeGVN=1110
1716     case Op_CastII:
1717       return;
1718 
1719     // MaxLNode::Ideal
1720     //   calls AddNode::Ideal
1721     //   calls commute -> decides to swap edges
1722     //
1723     // Another notification issue, because we check inputs of inputs?
1724     // MaxL -> Phi -> Loop
1725     // MaxL -> Phi -> MaxL
1726     //
1727     // Found with:
1728     //   compiler/c2/irTests/TestIfMinMax.java
1729     //   -XX:VerifyIterativeGVN=1110
1730     case Op_MaxL:
1731     case Op_MinL:
1732       return;
1733 
1734     // OrINode::Ideal
1735     //   calls AddNode::Ideal
1736     //   calls commute -> left is Load, right not -> commute.
1737     //
1738     // Not sure why notification does not work here, seems like
1739     // the depth is only 1, so it should work. Needs investigation.
1740     //
1741     // Found with:
1742     //   compiler/codegen/TestCharVect2.java#id0
1743     //   -XX:VerifyIterativeGVN=1110
1744     case Op_OrI:
1745     case Op_OrL:
1746       return;
1747 
1748     // Bool -> constant folded to 1.
1749     // Issue with notification?
1750     //
1751     // Found with:
1752     //   compiler/c2/irTests/TestVectorizationMismatchedAccess.java
1753     //   -XX:VerifyIterativeGVN=1110
1754     case Op_Bool:
1755       return;
1756 
1757     // LShiftLNode::Ideal
1758     // Looks at pattern: "(x + x) << c0", converts it to "x << (c0 + 1)"
1759     // Probably a notification issue.
1760     //
1761     // Found with:
1762     //   compiler/conversions/TestMoveConvI2LOrCastIIThruAddIs.java
1763     //   -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1764     case Op_LShiftL:
1765       return;
1766 
1767     // LShiftINode::Ideal
1768     // pattern: ((x + con1) << con2) -> x << con2 + con1 << con2
1769     // Could be issue with notification of inputs of inputs
1770     //
1771     // Side-note: should cases like these not be shared between
1772     //            LShiftI and LShiftL?
1773     //
1774     // Found with:
1775     //   compiler/escapeAnalysis/Test6689060.java
1776     //   -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110 -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1777     case Op_LShiftI:
1778       return;
1779 
1780     // AddPNode::Ideal seems to do set_req without removing lock first.
1781     // Found with various vector tests tier1-tier3.
1782     case Op_AddP:
1783       return;
1784 
1785     // StrIndexOfNode::Ideal
1786     // Found in tier1-3.
1787     case Op_StrIndexOf:
1788     case Op_StrIndexOfChar:
1789       return;
1790 
1791     // StrEqualsNode::Identity
1792     //
1793     // Found (linux x64 only?) with:
1794     //   serviceability/sa/ClhsdbThreadContext.java
1795     //   -XX:+UnlockExperimentalVMOptions -XX:LockingMode=1 -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1796     //   Note: The -XX:LockingMode option is not available anymore.
1797     case Op_StrEquals:
1798       return;
1799 
1800     // AryEqNode::Ideal
1801     // Not investigated. Reshapes itself and adds lots of nodes to the worklist.
1802     //
1803     // Found with:
1804     //   vmTestbase/vm/mlvm/meth/stress/compiler/i2c_c2i/Test.java
1805     //   -XX:+UnlockDiagnosticVMOptions -XX:-TieredCompilation -XX:+StressUnstableIfTraps -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1806     case Op_AryEq:
1807       return;
1808 
1809     // MergeMemNode::Ideal
1810     // Found in tier1-3. Did not investigate further yet.
1811     case Op_MergeMem:
1812       return;
1813 
1814     // CMoveINode::Ideal
1815     // Found in tier1-3. Did not investigate further yet.
1816     case Op_CMoveI:
1817       return;
1818 
1819     // CmpPNode::Ideal calls isa_const_java_mirror
1820     // and generates new constant nodes, even if no progress is made.
1821     // We can probably rewrite this so that only types are generated.
1822     // It seems that object types are not hashed, we could investigate
1823     // if that is an option as well.
1824     //
1825     // Found with:
1826     //   java -XX:VerifyIterativeGVN=1110 -Xcomp --version
1827     case Op_CmpP:
1828       return;
1829 
1830     // MinINode::Ideal
1831     // Did not investigate, but there are some patterns that might
1832     // need more notification.
1833     case Op_MinI:
1834     case Op_MaxI: // preemptively removed it as well.
1835       return;
1836   }
1837 
1838   if (n->is_Store()) {
1839     // StoreNode::Ideal can do this:
1840     //  // Capture an unaliased, unconditional, simple store into an initializer.
1841     //  // Or, if it is independent of the allocation, hoist it above the allocation.
1842     // That replaces the Store with a MergeMem.
1843     //
1844     // We have to investigate why this does not happen during IGVN in this case.
1845     // There could also be other issues - I did not investigate further yet.
1846     //
1847     // Found with:
1848     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1849     return;
1850   }
1851 
1852   if (n->is_Vector()) {
1853     // VectorNode::Ideal swaps edges, but only for ops
1854     // that are deemed commutable. But swap_edges
1855     // requires the hash to be invariant when the edges
1856     // are swapped, which is not implemented for these
1857     // vector nodes. This seems not to create any trouble
1858     // usually, but we can also get graphs where in the
1859     // end the nodes are not all commuted, so there is
1860     // definitively an issue here.
1861     //
1862     // Probably we have two options: kill the hash, or
1863     // properly make the hash commutation friendly.
1864     //
1865     // Found with:
1866     //   compiler/vectorapi/TestMaskedMacroLogicVector.java
1867     //   -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110 -XX:+UseParallelGC -XX:+UseNUMA
1868     return;
1869   }
1870 
1871   if (n->is_Region()) {
1872     // LoopNode::Ideal calls RegionNode::Ideal.
1873     // CountedLoopNode::Ideal calls RegionNode::Ideal too.
1874     // But I got an issue because RegionNode::optimize_trichotomy
1875     // then modifies another node, and pushes nodes to the worklist
1876     // Not sure if this is ok, modifying another node like that.
1877     // Maybe it is, then we need to look into what to do with
1878     // the nodes that are now on the worklist, maybe just clear
1879     // them out again. But maybe modifying other nodes like that
1880     // is also bad design. In the end, we return nullptr for
1881     // the current CountedLoop. But the extra nodes on the worklist
1882     // trip the asserts later on.
1883     //
1884     // Found with:
1885     //   compiler/eliminateAutobox/TestShortBoxing.java
1886     //   -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1887     return;
1888   }
1889 
1890   if (n->is_CallJava()) {
1891     // CallStaticJavaNode::Ideal
1892     // Led to a crash:
1893     //   assert((is_CallStaticJava() && cg->is_mh_late_inline()) || (is_CallDynamicJava() && cg->is_virtual_late_inline())) failed: mismatch
1894     //
1895     // Did not investigate yet, could be a bug.
1896     // Or maybe it does not expect to be called during verification.
1897     //
1898     // Found with:
1899     //   test/jdk/jdk/incubator/vector/VectorRuns.java
1900     //   -XX:VerifyIterativeGVN=1110
1901 
1902     // CallDynamicJavaNode::Ideal, and I think also for CallStaticJavaNode::Ideal
1903     //  and possibly their subclasses.
1904     // During late inlining it can call CallJavaNode::register_for_late_inline
1905     // That means we do more rounds of late inlining, but might fail.
1906     // Then we do IGVN again, and register the node again for late inlining.
1907     // This creates an endless cycle. Everytime we try late inlining, we
1908     // are also creating more nodes, especially SafePoint and MergeMem.
1909     // These nodes are immediately rejected when the inlining fails in the
1910     // do_late_inline_check, but they still grow the memory, until we hit
1911     // the MemLimit and crash.
1912     // The assumption here seems that CallDynamicJavaNode::Ideal does not get
1913     // called repeatedly, and eventually we terminate. I fear this is not
1914     // a great assumption to make. We should investigate more.
1915     //
1916     // Found with:
1917     //   compiler/loopopts/superword/TestDependencyOffsets.java#vanilla-U
1918     //   -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1919     return;
1920   }
1921 
1922   // Ideal should not make progress if it returns nullptr.
1923   // We use made_progress() rather than unique() or live_nodes() because some
1924   // Ideal implementations speculatively create nodes and kill them before
1925   // returning nullptr (e.g. split_if clones a Cmp to check is_canonical).
1926   // unique() is a high-water mark that is not decremented by remove_dead_node,
1927   // so it would cause false-positives. live_nodes() accounts for dead nodes but can
1928   // decrease when Ideal removes existing nodes as side effects.
1929   // made_progress() precisely tracks meaningful transforms, and speculative
1930   // work killed via NodeOrigin::Speculative does not increment it.
1931   uint old_progress = made_progress();
1932   // The hash of a node should not change, this would indicate different inputs
1933   uint old_hash = n->hash();
1934   // Remove 'n' from hash table in case it gets modified. We want to avoid
1935   // hitting the "Need to remove from hash before changing edges" assert if
1936   // a change occurs. Instead, we would like to proceed with the optimization,
1937   // return and finally hit the assert in PhaseIterGVN::verify_optimize to get
1938   // a more meaningful message
1939   _table.hash_delete(n);
1940   Node* i = n->Ideal(this, can_reshape);
1941   // If there was no new Idealization, we are probably happy.
1942   if (i == nullptr) {
1943     uint progress = made_progress() - old_progress;
1944     if (progress != 0) {
1945       stringStream ss; // Print as a block without tty lock.
1946       ss.cr();
1947       ss.print_cr("Ideal optimization did not make progress but had side effects.");
1948       ss.print_cr("  %u transforms made progress", progress);
1949       n->dump_bfs(1, nullptr, "", &ss);
1950       tty->print_cr("%s", ss.as_string());
1951       assert(false, "Unexpected side effects from applying Ideal optimization on %s", n->Name());
1952     }
1953 
1954     if (old_hash != n->hash()) {
1955       stringStream ss; // Print as a block without tty lock.
1956       ss.cr();
1957       ss.print_cr("Ideal optimization did not make progress but node hash changed.");
1958       ss.print_cr("  old_hash = %d, hash = %d", old_hash, n->hash());
1959       n->dump_bfs(1, nullptr, "", &ss);
1960       tty->print_cr("%s", ss.as_string());
1961       assert(false, "Unexpected hash change from applying Ideal optimization on %s", n->Name());
1962     }
1963 
1964     // Some nodes try to push itself back to the worklist if can_reshape is
1965     // false
1966     if (!can_reshape && _worklist.size() > 0 && _worklist.pop() != n) {
1967       stringStream ss;
1968       ss.cr();
1969       ss.print_cr("Previously optimized:");
1970       n->dump_bfs(1, nullptr, "", &ss);
1971       tty->print_cr("%s", ss.as_string());
1972       assert(false, "should only push itself on worklist");
1973     }
1974     verify_empty_worklist(n);
1975 
1976     // Everything is good.
1977     hash_find_insert(n);
1978     return;
1979   }
1980 
1981   // We just saw a new Idealization which was not done during IGVN.
1982   stringStream ss; // Print as a block without tty lock.
1983   ss.cr();
1984   ss.print_cr("Missed Ideal optimization (can_reshape=%s):", can_reshape ? "true": "false");
1985   if (i == n) {
1986     ss.print_cr("The node was reshaped by Ideal.");
1987   } else {
1988     ss.print_cr("The node was replaced by Ideal.");
1989     ss.print_cr("Old node:");
1990     n->dump_bfs(1, nullptr, "", &ss);
1991   }
1992   ss.print_cr("The result after Ideal:");
1993   i->dump_bfs(1, nullptr, "", &ss);
1994   tty->print_cr("%s", ss.as_string());
1995 
1996   assert(false, "Missed Ideal optimization opportunity in PhaseIterGVN for %s", n->Name());
1997 }
1998 
1999 // Check that all Identity optimizations that could be done were done.
2000 // Asserts if it found missed optimization opportunities, and
2001 //         returns normally otherwise (no missed optimization, or skipped verification).
2002 void PhaseIterGVN::verify_Identity_for(Node* n) {
2003   // First, we check a list of exceptions, where we skip verification,
2004   // because there are known cases where Ideal can optimize after IGVN.
2005   // Some may be expected and cannot be fixed, and others should be fixed.
2006   switch (n->Opcode()) {
2007     // SafePointNode::Identity can remove SafePoints, but wants to wait until
2008     // after loopopts:
2009     //   // Transforming long counted loops requires a safepoint node. Do not
2010     //   // eliminate a safepoint until loop opts are over.
2011     //   if (in(0)->is_Proj() && !phase->C->major_progress()) {
2012     //
2013     // I think the check for major_progress does delay it until after loopopts
2014     // but it does not ensure that the node is on the IGVN worklist after
2015     // loopopts. I think we should try to instead check for
2016     // phase->C->post_loop_opts_phase() and call record_for_post_loop_opts_igvn.
2017     //
2018     // Found with:
2019     //   java -XX:VerifyIterativeGVN=1000 -Xcomp --version
2020     case Op_SafePoint:
2021       return;
2022 
2023     // MergeMemNode::Identity replaces the MergeMem with its base_memory if it
2024     // does not record any other memory splits.
2025     //
2026     // I did not deeply investigate, but it looks like MergeMemNode::Identity
2027     // never got called during IGVN for this node, investigate why.
2028     //
2029     // Found with:
2030     //   java -XX:VerifyIterativeGVN=1000 -Xcomp --version
2031     case Op_MergeMem:
2032       return;
2033 
2034     // ConstraintCastNode::Identity finds casts that are the same, except that
2035     // the control is "higher up", i.e. dominates. The call goes via
2036     // ConstraintCastNode::dominating_cast to PhaseGVN::is_dominator_helper,
2037     // which traverses up to 100 idom steps. If anything gets optimized somewhere
2038     // away from the cast, but within 100 idom steps, the cast may not be
2039     // put on the IGVN worklist any more.
2040     //
2041     // Found with:
2042     //   java -XX:VerifyIterativeGVN=1000 -Xcomp --version
2043     case Op_CastPP:
2044     case Op_CastII:
2045     case Op_CastLL:
2046       return;
2047 
2048     // Same issue for CheckCastPP, uses ConstraintCastNode::Identity and
2049     // checks dominator, which may be changed, but too far up for notification
2050     // to work.
2051     //
2052     // Found with:
2053     //   compiler/c2/irTests/TestSkeletonPredicates.java
2054     //   -XX:VerifyIterativeGVN=1110
2055     case Op_CheckCastPP:
2056       return;
2057 
2058     // In SubNode::Identity, we do:
2059     //   Convert "(X+Y) - Y" into X and "(X+Y) - X" into Y
2060     // In the example, the AddI had an input replaced, the AddI is
2061     // added to the IGVN worklist, but the SubI is one link further
2062     // down and is not added. I checked add_users_of_use_to_worklist
2063     // where I would expect the SubI would be added, and I cannot
2064     // find the pattern, only this one:
2065     //   If changed AddI/SubI inputs, check CmpU for range check optimization.
2066     //
2067     // Fix this "notification" issue and check if there are any other
2068     // issues.
2069     //
2070     // Found with:
2071     //   java -XX:VerifyIterativeGVN=1000 -Xcomp --version
2072     case Op_SubI:
2073     case Op_SubL:
2074       return;
2075 
2076     // PhiNode::Identity checks for patterns like:
2077     //   r = (x != con) ? x : con;
2078     // that can be constant folded to "x".
2079     //
2080     // Call goes through PhiNode::is_cmove_id and CMoveNode::is_cmove_id.
2081     // I suspect there was some earlier change to one of the inputs, but
2082     // not all relevant outputs were put on the IGVN worklist.
2083     //
2084     // Found with:
2085     //   test/hotspot/jtreg/gc/stress/gcbasher/TestGCBasherWithG1.java
2086     //   -XX:VerifyIterativeGVN=1110
2087     case Op_Phi:
2088       return;
2089 
2090     // ConvI2LNode::Identity does
2091     // convert I2L(L2I(x)) => x
2092     //
2093     // Investigate why this did not already happen during IGVN.
2094     //
2095     // Found with:
2096     //   compiler/loopopts/superword/TestDependencyOffsets.java#vanilla-A
2097     //   -XX:VerifyIterativeGVN=1110
2098     case Op_ConvI2L:
2099       return;
2100 
2101     // AbsINode::Identity
2102     // Not investigated yet.
2103     case Op_AbsI:
2104       return;
2105   }
2106 
2107   if (n->is_Load()) {
2108     // LoadNode::Identity tries to look for an earlier store value via
2109     // can_see_stored_value. I found an example where this led to
2110     // an Allocation, where we could assume the value was still zero.
2111     // So the LoadN can be replaced with a zerocon.
2112     //
2113     // Investigate why this was not already done during IGVN.
2114     // A similar issue happens with Ideal.
2115     //
2116     // Found with:
2117     //   java -XX:VerifyIterativeGVN=1000 -Xcomp --version
2118     return;
2119   }
2120 
2121   if (n->is_Store()) {
2122     // StoreNode::Identity
2123     // Not investigated, but found missing optimization for StoreI.
2124     // Looks like a StoreI is replaced with an InitializeNode.
2125     //
2126     // Found with:
2127     //   applications/ctw/modules/java_base_2.java
2128     //   -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -Djava.awt.headless=true -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
2129     return;
2130   }
2131 
2132   if (n->is_Vector()) {
2133     // Found with tier1-3. Not investigated yet.
2134     // The observed issue was with AndVNode::Identity
2135     return;
2136   }
2137 
2138   Node* i = n->Identity(this);
2139   // If we cannot find any other Identity, we are happy.
2140   if (i == n) {
2141     verify_empty_worklist(n);
2142     return;
2143   }
2144 
2145   // The verification just found a new Identity that was not found during IGVN.
2146   stringStream ss; // Print as a block without tty lock.
2147   ss.cr();
2148   ss.print_cr("Missed Identity optimization:");
2149   ss.print_cr("Old node:");
2150   n->dump_bfs(1, nullptr, "", &ss);
2151   ss.print_cr("New node:");
2152   i->dump_bfs(1, nullptr, "", &ss);
2153   tty->print_cr("%s", ss.as_string());
2154 
2155   assert(false, "Missed Identity optimization opportunity in PhaseIterGVN for %s", n->Name());
2156 }
2157 
2158 // Some other verifications that are not specific to a particular transformation.
2159 void PhaseIterGVN::verify_node_invariants_for(const Node* n) {
2160   if (n->is_AddP()) {
2161     if (!n->as_AddP()->address_input_has_same_base()) {
2162       stringStream ss; // Print as a block without tty lock.
2163       ss.cr();
2164       ss.print_cr("Base pointers must match for AddP chain:");
2165       n->dump_bfs(2, nullptr, "", &ss);
2166       tty->print_cr("%s", ss.as_string());
2167 
2168       assert(false, "Broken node invariant for %s", n->Name());
2169     }
2170   }
2171 }
2172 #endif
2173 
2174 /**
2175  * Register a new node with the optimizer.  Update the types array, the def-use
2176  * info.  Put on worklist.
2177  */
2178 Node* PhaseIterGVN::register_new_node_with_optimizer(Node* n, Node* orig) {
2179   set_type_bottom(n);
2180   _worklist.push(n);
2181   if (orig != nullptr)  C->copy_node_notes_to(n, orig);
2182   return n;
2183 }
2184 
2185 //------------------------------transform--------------------------------------
2186 // Non-recursive: idealize Node 'n' with respect to its inputs and its value
2187 Node *PhaseIterGVN::transform( Node *n ) {
2188   // If brand new node, make space in type array, and give it a type.
2189   ensure_type_or_null(n);
2190   if (type_or_null(n) == nullptr) {
2191     set_type_bottom(n);
2192   }
2193 
2194   if (_delay_transform) {
2195     // Add the node to the worklist but don't optimize for now
2196     _worklist.push(n);
2197     return n;
2198   }
2199 
2200   return transform_old(n);
2201 }
2202 
2203 Node *PhaseIterGVN::transform_old(Node* n) {
2204   NOT_PRODUCT(set_transforms());
2205   // Remove 'n' from hash table in case it gets modified
2206   _table.hash_delete(n);
2207 #ifdef ASSERT
2208   if (is_verify_def_use()) {
2209     assert(!_table.find_index(n->_idx), "found duplicate entry in table");
2210   }
2211 #endif
2212 
2213   // Allow Bool -> Cmp idealisation in late inlining intrinsics that return a bool
2214   if (n->is_Cmp()) {
2215     add_users_to_worklist(n);
2216   }
2217 
2218   // Apply the Ideal call in a loop until it no longer applies
2219   Node* k = n;
2220   DEBUG_ONLY(dead_loop_check(k);)
2221   DEBUG_ONLY(bool is_new = (k->outcnt() == 0);)
2222   C->remove_modified_node(k);
2223 #ifndef PRODUCT
2224   uint hash_before = is_verify_Ideal_return() ? k->hash() : 0;
2225 #endif
2226   Node* i = apply_ideal(k, /*can_reshape=*/true);
2227   assert(i != k || is_new || i->outcnt() > 0, "don't return dead nodes");
2228 #ifndef PRODUCT
2229   if (is_verify_Ideal_return()) {
2230     assert(k->outcnt() == 0 || i != nullptr || hash_before == k->hash(), "hash changed after Ideal returned nullptr for %s", k->Name());
2231   }
2232   verify_step(k);
2233 #endif
2234 
2235   DEBUG_ONLY(uint loop_count = 1;)
2236   if (i != nullptr) {
2237     set_progress();
2238   }
2239   while (i != nullptr) {
2240 #ifdef ASSERT
2241     if (loop_count >= K + C->live_nodes()) {
2242       dump_infinite_loop_info(i, "PhaseIterGVN::transform_old");
2243     }
2244 #endif
2245     assert((i->_idx >= k->_idx) || i->is_top(), "Idealize should return new nodes, use Identity to return old nodes");
2246     // Made a change; put users of original Node on worklist
2247     add_users_to_worklist(k);
2248     // Replacing root of transform tree?
2249     if (k != i) {
2250       // Make users of old Node now use new.
2251       subsume_node(k, i);
2252       k = i;
2253     }
2254     DEBUG_ONLY(dead_loop_check(k);)
2255     // Try idealizing again
2256     DEBUG_ONLY(is_new = (k->outcnt() == 0);)
2257     C->remove_modified_node(k);
2258 #ifndef PRODUCT
2259     uint hash_before = is_verify_Ideal_return() ? k->hash() : 0;
2260 #endif
2261     i = apply_ideal(k, /*can_reshape=*/true);
2262     assert(i != k || is_new || (i->outcnt() > 0), "don't return dead nodes");
2263 #ifndef PRODUCT
2264     if (is_verify_Ideal_return()) {
2265       assert(k->outcnt() == 0 || i != nullptr || hash_before == k->hash(), "hash changed after Ideal returned nullptr for %s", k->Name());
2266     }
2267     verify_step(k);
2268 #endif
2269     DEBUG_ONLY(loop_count++;)
2270   }
2271 
2272   // If brand new node, make space in type array.
2273   ensure_type_or_null(k);
2274 
2275   // See what kind of values 'k' takes on at runtime
2276   const Type* t = k->Value(this);
2277   assert(t != nullptr, "value sanity");
2278 
2279   // Since I just called 'Value' to compute the set of run-time values
2280   // for this Node, and 'Value' is non-local (and therefore expensive) I'll
2281   // cache Value.  Later requests for the local phase->type of this Node can
2282   // use the cached Value instead of suffering with 'bottom_type'.
2283   if (type_or_null(k) != t) {
2284     NOT_PRODUCT(inc_new_values();)
2285     set_progress();
2286     set_type(k, t);
2287     // If k is a TypeNode, capture any more-precise type permanently into Node
2288     k->raise_bottom_type(t);
2289     // Move users of node to worklist
2290     add_users_to_worklist(k);
2291   }
2292   // If 'k' computes a constant, replace it with a constant
2293   if (t->singleton() && !k->is_Con()) {
2294     set_progress();
2295     Node* con = makecon(t);     // Make a constant
2296     add_users_to_worklist(k);
2297     subsume_node(k, con);       // Everybody using k now uses con
2298     return con;
2299   }
2300 
2301   // Now check for Identities
2302   i = k->Identity(this);      // Look for a nearby replacement
2303   if (i != k) {                // Found? Return replacement!
2304     set_progress();
2305     add_users_to_worklist(k);
2306     subsume_node(k, i);       // Everybody using k now uses i
2307     return i;
2308   }
2309 
2310   // Global Value Numbering
2311   i = hash_find_insert(k);      // Check for pre-existing node
2312   if (i && (i != k)) {
2313     // Return the pre-existing node if it isn't dead
2314     set_progress();
2315     add_users_to_worklist(k);
2316     subsume_node(k, i);       // Everybody using k now uses i
2317     return i;
2318   }
2319 
2320   // Return Idealized original
2321   return k;
2322 }
2323 
2324 //---------------------------------saturate------------------------------------
2325 const Type* PhaseIterGVN::saturate(const Type* new_type, const Type* old_type,
2326                                    const Type* limit_type) const {
2327   return new_type->narrow(old_type);
2328 }
2329 
2330 //------------------------------remove_globally_dead_node----------------------
2331 // Kill a globally dead Node.  All uses are also globally dead and are
2332 // aggressively trimmed.
2333 void PhaseIterGVN::remove_globally_dead_node(Node* dead, NodeOrigin origin) {
2334   enum DeleteProgress {
2335     PROCESS_INPUTS,
2336     PROCESS_OUTPUTS
2337   };
2338   ResourceMark rm;
2339   Node_Stack stack(32);
2340   stack.push(dead, PROCESS_INPUTS);
2341 
2342   while (stack.is_nonempty()) {
2343     dead = stack.node();
2344     if (dead->Opcode() == Op_SafePoint) {
2345       dead->as_SafePoint()->disconnect_from_root(this);
2346     }
2347     uint progress_state = stack.index();
2348     assert(dead != C->root(), "killing root, eh?");
2349     assert(!dead->is_top(), "add check for top when pushing");
2350     if (progress_state == PROCESS_INPUTS) {
2351       // After following inputs, continue to outputs
2352       stack.set_index(PROCESS_OUTPUTS);
2353       if (!dead->is_Con()) { // Don't kill cons but uses
2354         if (origin != NodeOrigin::Speculative) {
2355           set_progress();
2356         }
2357         bool recurse = false;
2358         // Remove from hash table
2359         _table.hash_delete( dead );
2360         // Smash all inputs to 'dead', isolating him completely
2361         for (uint i = 0; i < dead->req(); i++) {
2362           Node *in = dead->in(i);
2363           if (in != nullptr && in != C->top()) {  // Points to something?
2364             int nrep = dead->replace_edge(in, nullptr, this);  // Kill edges
2365             assert((nrep > 0), "sanity");
2366             if (in->outcnt() == 0) { // Made input go dead?
2367               stack.push(in, PROCESS_INPUTS); // Recursively remove
2368               recurse = true;
2369             } else if (in->outcnt() == 1 &&
2370                        in->has_special_unique_user()) {
2371               _worklist.push(in->unique_out());
2372             } else if (in->outcnt() <= 2 && dead->is_Phi()) {
2373               if (in->Opcode() == Op_Region) {
2374                 _worklist.push(in);
2375               } else if (in->is_Store()) {
2376                 DUIterator_Fast imax, i = in->fast_outs(imax);
2377                 _worklist.push(in->fast_out(i));
2378                 i++;
2379                 if (in->outcnt() == 2) {
2380                   _worklist.push(in->fast_out(i));
2381                   i++;
2382                 }
2383                 assert(!(i < imax), "sanity");
2384               }
2385             } else if (dead->is_data_proj_of_pure_function(in)) {
2386               _worklist.push(in);
2387             } else {
2388               BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(this, in);
2389             }
2390             if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory &&
2391                 in->is_Proj() && in->in(0) != nullptr && in->in(0)->is_Initialize()) {
2392               // A Load that directly follows an InitializeNode is
2393               // going away. The Stores that follow are candidates
2394               // again to be captured by the InitializeNode.
2395               add_users_to_worklist_if(_worklist, in, [](Node* n) { return n->is_Store(); });
2396             }
2397           } // if (in != nullptr && in != C->top())
2398         } // for (uint i = 0; i < dead->req(); i++)
2399         if (recurse) {
2400           continue;
2401         }
2402       } // if (!dead->is_Con())
2403     } // if (progress_state == PROCESS_INPUTS)
2404 
2405     // Aggressively kill globally dead uses
2406     // (Rather than pushing all the outs at once, we push one at a time,
2407     // plus the parent to resume later, because of the indefinite number
2408     // of edge deletions per loop trip.)
2409     if (dead->outcnt() > 0) {
2410       // Recursively remove output edges
2411       stack.push(dead->raw_out(0), PROCESS_INPUTS);
2412     } else {
2413       // Finished disconnecting all input and output edges.
2414       stack.pop();
2415       // Remove dead node from iterative worklist
2416       _worklist.remove(dead);
2417       C->remove_useless_node(dead);
2418     }
2419   } // while (stack.is_nonempty())
2420 }
2421 
2422 //------------------------------subsume_node-----------------------------------
2423 // Remove users from node 'old' and add them to node 'nn'.
2424 void PhaseIterGVN::subsume_node( Node *old, Node *nn ) {
2425   if (old->Opcode() == Op_SafePoint) {
2426     old->as_SafePoint()->disconnect_from_root(this);
2427   }
2428   assert( old != hash_find(old), "should already been removed" );
2429   assert( old != C->top(), "cannot subsume top node");
2430   // Copy debug or profile information to the new version:
2431   C->copy_node_notes_to(nn, old);
2432   // Move users of node 'old' to node 'nn'
2433   for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
2434     Node* use = old->last_out(i);  // for each use...
2435     // use might need re-hashing (but it won't if it's a new node)
2436     rehash_node_delayed(use);
2437     // Update use-def info as well
2438     // We remove all occurrences of old within use->in,
2439     // so as to avoid rehashing any node more than once.
2440     // The hash table probe swamps any outer loop overhead.
2441     uint num_edges = 0;
2442     for (uint jmax = use->len(), j = 0; j < jmax; j++) {
2443       if (use->in(j) == old) {
2444         use->set_req(j, nn);
2445         ++num_edges;
2446       }
2447     }
2448     i -= num_edges;    // we deleted 1 or more copies of this edge
2449   }
2450 
2451   // Search for instance field data PhiNodes in the same region pointing to the old
2452   // memory PhiNode and update their instance memory ids to point to the new node.
2453   if (old->is_Phi() && old->as_Phi()->type()->has_memory() && old->in(0) != nullptr) {
2454     Node* region = old->in(0);
2455     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2456       PhiNode* phi = region->fast_out(i)->isa_Phi();
2457       if (phi != nullptr && phi->inst_mem_id() == (int)old->_idx) {
2458         phi->set_inst_mem_id((int)nn->_idx);
2459       }
2460     }
2461   }
2462 
2463   // Smash all inputs to 'old', isolating him completely
2464   Node *temp = new Node(1);
2465   temp->init_req(0,nn);     // Add a use to nn to prevent him from dying
2466   remove_dead_node(old, NodeOrigin::Graph);
2467   temp->del_req(0);         // Yank bogus edge
2468   if (nn != nullptr && nn->outcnt() == 0) {
2469     _worklist.push(nn);
2470   }
2471 #ifndef PRODUCT
2472   if (is_verify_def_use()) {
2473     for ( int i = 0; i < _verify_window_size; i++ ) {
2474       if ( _verify_window[i] == old )
2475         _verify_window[i] = nn;
2476     }
2477   }
2478 #endif
2479   temp->destruct(this);     // reuse the _idx of this little guy
2480 }
2481 
2482 void PhaseIterGVN::replace_in_uses(Node* n, Node* m) {
2483   assert(n != nullptr, "sanity");
2484   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2485     Node* u = n->fast_out(i);
2486     if (u != n) {
2487       rehash_node_delayed(u);
2488       int nb = u->replace_edge(n, m);
2489       --i, imax -= nb;
2490     }
2491   }
2492   assert(n->outcnt() == 0, "all uses must be deleted");
2493 }
2494 
2495 //------------------------------add_users_to_worklist--------------------------
2496 void PhaseIterGVN::add_users_to_worklist0(Node* n, Unique_Node_List& worklist) {
2497   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2498     worklist.push(n->fast_out(i));  // Push on worklist
2499   }
2500 }
2501 
2502 // Return counted loop Phi if as a counted loop exit condition, cmp
2503 // compares the induction variable with n
2504 static PhiNode* countedloop_phi_from_cmp(CmpNode* cmp, Node* n) {
2505   for (DUIterator_Fast imax, i = cmp->fast_outs(imax); i < imax; i++) {
2506     Node* bol = cmp->fast_out(i);
2507     for (DUIterator_Fast i2max, i2 = bol->fast_outs(i2max); i2 < i2max; i2++) {
2508       Node* iff = bol->fast_out(i2);
2509       if (iff->is_BaseCountedLoopEnd()) {
2510         BaseCountedLoopEndNode* cle = iff->as_BaseCountedLoopEnd();
2511         if (cle->limit() == n) {
2512           PhiNode* phi = cle->phi();
2513           if (phi != nullptr) {
2514             return phi;
2515           }
2516         }
2517       }
2518     }
2519   }
2520   return nullptr;
2521 }
2522 
2523 void PhaseIterGVN::add_users_to_worklist(Node *n) {
2524   add_users_to_worklist0(n, _worklist);
2525 
2526   Unique_Node_List& worklist = _worklist;
2527   // Move users of node to worklist
2528   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2529     Node* use = n->fast_out(i); // Get use
2530     add_users_of_use_to_worklist(n, use, worklist);
2531   }
2532 }
2533 
2534 void PhaseIterGVN::add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_List& worklist) {
2535   if(use->is_Multi() ||      // Multi-definer?  Push projs on worklist
2536       use->is_Store() )       // Enable store/load same address
2537     add_users_to_worklist0(use, worklist);
2538 
2539   // If we changed the receiver type to a call, we need to revisit
2540   // the Catch following the call.  It's looking for a non-null
2541   // receiver to know when to enable the regular fall-through path
2542   // in addition to the NullPtrException path.
2543   if (use->is_CallDynamicJava() && n == use->in(TypeFunc::Parms)) {
2544     Node* p = use->as_CallDynamicJava()->proj_out_or_null(TypeFunc::Control);
2545     if (p != nullptr) {
2546       add_users_to_worklist0(p, worklist);
2547     }
2548   }
2549 
2550   // AndLNode::Ideal folds GraphKit::mark_word_test patterns. Give it a chance to run.
2551   if (n->is_Load() && use->is_Phi()) {
2552     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
2553       Node* u = use->fast_out(i);
2554       if (u->Opcode() == Op_AndL) {
2555         worklist.push(u);
2556       }
2557     }
2558   }
2559 
2560   uint use_op = use->Opcode();
2561   if(use->is_Cmp()) {       // Enable CMP/BOOL optimization
2562     add_users_to_worklist0(use, worklist); // Put Bool on worklist
2563     if (use->outcnt() > 0) {
2564       Node* bol = use->raw_out(0);
2565       if (bol->outcnt() > 0) {
2566         Node* iff = bol->raw_out(0);
2567         if (iff->outcnt() == 2) {
2568           // Look for the 'is_x2logic' pattern: "x ? : 0 : 1" and put the
2569           // phi merging either 0 or 1 onto the worklist
2570           Node* ifproj0 = iff->raw_out(0);
2571           Node* ifproj1 = iff->raw_out(1);
2572           if (ifproj0->outcnt() > 0 && ifproj1->outcnt() > 0) {
2573             Node* region0 = ifproj0->raw_out(0);
2574             Node* region1 = ifproj1->raw_out(0);
2575             if( region0 == region1 )
2576               add_users_to_worklist0(region0, worklist);
2577           }
2578         }
2579       }
2580     }
2581     if (use_op == Op_CmpI || use_op == Op_CmpL) {
2582       Node* phi = countedloop_phi_from_cmp(use->as_Cmp(), n);
2583       if (phi != nullptr) {
2584         // Input to the cmp of a loop exit check has changed, thus
2585         // the loop limit may have changed, which can then change the
2586         // range values of the trip-count Phi.
2587         worklist.push(phi);
2588       }
2589     }
2590     if (use_op == Op_CmpI) {
2591       Node* cmp = use;
2592       Node* in1 = cmp->in(1);
2593       Node* in2 = cmp->in(2);
2594       // Notify CmpI / If pattern from CastIINode::Value (left pattern).
2595       // Must also notify if in1 is modified and possibly turns into X (right pattern).
2596       //
2597       // in1  in2                   in1  in2
2598       //  |    |                     |    |
2599       //  +--- | --+                 |    |
2600       //  |    |   |                 |    |
2601       // CmpINode  |                CmpINode
2602       //    |      |                   |
2603       // BoolNode  |                BoolNode
2604       //    |      |        OR         |
2605       //  IfNode   |                 IfNode
2606       //    |      |                   |
2607       //  IfProj   |                 IfProj   X
2608       //    |      |                   |      |
2609       //   CastIINode                 CastIINode
2610       //
2611       if (in1 != in2) { // if they are equal, the CmpI can fold them away
2612         if (in1 == n) {
2613           // in1 modified -> could turn into X -> do traversal based on right pattern.
2614           for (DUIterator_Fast i2max, i2 = cmp->fast_outs(i2max); i2 < i2max; i2++) {
2615             Node* bol = cmp->fast_out(i2); // For each Bool
2616             if (bol->is_Bool()) {
2617               for (DUIterator_Fast i3max, i3 = bol->fast_outs(i3max); i3 < i3max; i3++) {
2618                 Node* iff = bol->fast_out(i3); // For each If
2619                 if (iff->is_If()) {
2620                   for (DUIterator_Fast i4max, i4 = iff->fast_outs(i4max); i4 < i4max; i4++) {
2621                     Node* if_proj = iff->fast_out(i4); // For each IfProj
2622                     assert(if_proj->is_IfProj(), "If only has IfTrue and IfFalse as outputs");
2623                     for (DUIterator_Fast i5max, i5 = if_proj->fast_outs(i5max); i5 < i5max; i5++) {
2624                       Node* castii = if_proj->fast_out(i5); // For each CastII
2625                       if (castii->is_CastII() &&
2626                           castii->as_CastII()->carry_dependency()) {
2627                         worklist.push(castii);
2628                       }
2629                     }
2630                   }
2631                 }
2632               }
2633             }
2634           }
2635         } else {
2636           // Only in2 modified -> can assume X == in2 (left pattern).
2637           assert(n == in2, "only in2 modified");
2638           // Find all CastII with input in1.
2639           for (DUIterator_Fast jmax, j = in1->fast_outs(jmax); j < jmax; j++) {
2640             Node* castii = in1->fast_out(j);
2641             if (castii->is_CastII() && castii->as_CastII()->carry_dependency()) {
2642               // Find If.
2643               if (castii->in(0) != nullptr && castii->in(0)->in(0) != nullptr && castii->in(0)->in(0)->is_If()) {
2644                 Node* ifnode = castii->in(0)->in(0);
2645                 // Check that if connects to the cmp
2646                 if (ifnode->in(1) != nullptr && ifnode->in(1)->is_Bool() && ifnode->in(1)->in(1) == cmp) {
2647                   worklist.push(castii);
2648                 }
2649               }
2650             }
2651           }
2652         }
2653       }
2654     }
2655   }
2656 
2657   // Inline type nodes can have other inline types as users. If an input gets
2658   // updated, make sure that inline type users get a chance for optimization.
2659   if (use->is_InlineType() || use->is_DecodeN()) {
2660     auto push_the_uses_to_worklist = [&](Node* n){
2661       if (n->is_InlineType()) {
2662         worklist.push(n);
2663       }
2664     };
2665     auto is_boundary = [](Node* n){ return !n->is_InlineType(); };
2666     use->visit_uses(push_the_uses_to_worklist, is_boundary, true);
2667   }
2668   // If changed Cast input, notify down for Phi, Sub, and Xor - all do "uncast"
2669   // Patterns:
2670   // ConstraintCast+ -> Sub
2671   // ConstraintCast+ -> Phi
2672   // ConstraintCast+ -> Xor
2673   if (use->is_ConstraintCast()) {
2674     auto push_the_uses_to_worklist = [&](Node* n){
2675       if (n->is_Phi() || n->is_Sub() || n->Opcode() == Op_XorI || n->Opcode() == Op_XorL) {
2676         worklist.push(n);
2677       }
2678     };
2679     auto is_boundary = [](Node* n){ return !n->is_ConstraintCast(); };
2680     use->visit_uses(push_the_uses_to_worklist, is_boundary);
2681   }
2682   // If changed LShift inputs, check RShift/URShift users for
2683   // "(X << C) >> C" sign-ext and "(X << C) >>> C" zero-ext optimizations.
2684   if (use_op == Op_LShiftI || use_op == Op_LShiftL) {
2685     add_users_to_worklist_if(worklist, use, [](Node* u) {
2686       return u->Opcode() == Op_RShiftI || u->Opcode() == Op_RShiftL ||
2687              u->Opcode() == Op_URShiftI || u->Opcode() == Op_URShiftL;
2688     });
2689   }
2690   // If changed LShift inputs, check And users for shift and mask (And) operation
2691   if (use_op == Op_LShiftI || use_op == Op_LShiftL) {
2692     add_users_to_worklist_if(worklist, use, [](Node* u) {
2693       return u->Opcode() == Op_AndI || u->Opcode() == Op_AndL;
2694     });
2695   }
2696   // If changed AddI/SubI inputs, check CmpU for range check optimization.
2697   if (use_op == Op_AddI || use_op == Op_SubI) {
2698     add_users_to_worklist_if(worklist, use, [](Node* u) {
2699       return u->Opcode() == Op_CmpU;
2700     });
2701   }
2702   // If changed AddI/AddL inputs, check URShift users for
2703   // "((X << z) + Y) >>> z" optimization in URShift{I,L}Node::Ideal.
2704   if (use_op == Op_AddI || use_op == Op_AddL) {
2705     add_users_to_worklist_if(worklist, use, [](Node* u) {
2706       return u->Opcode() == Op_URShiftI || u->Opcode() == Op_URShiftL;
2707     });
2708   }
2709   // If changed LShiftI/LShiftL inputs, check AddI/AddL users for their
2710   // URShiftI/URShiftL users for "((x << z) + y) >>> z" optimization opportunity
2711   // (see URShiftINode::Ideal). Handles the case where the LShift input changes.
2712   if (use_op == Op_LShiftI || use_op == Op_LShiftL) {
2713     for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2714       Node* add = use->fast_out(i2);
2715       if (add->Opcode() == Op_AddI || add->Opcode() == Op_AddL) {
2716         add_users_to_worklist_if(worklist, add, [](Node* u) {
2717           return u->Opcode() == Op_URShiftI || u->Opcode() == Op_URShiftL;
2718         });
2719       }
2720     }
2721   }
2722   // If changed AndI/AndL inputs, check RShift/URShift users for "(x & mask) >> shift" optimization opportunity
2723   if (use_op == Op_AndI || use_op == Op_AndL) {
2724     add_users_to_worklist_if(worklist, use, [](Node* u) {
2725       return u->Opcode() == Op_RShiftI || u->Opcode() == Op_RShiftL ||
2726              u->Opcode() == Op_URShiftI || u->Opcode() == Op_URShiftL;
2727     });
2728   }
2729   // Check for redundant conversion patterns:
2730   // ConvD2L->ConvL2D->ConvD2L
2731   // ConvF2I->ConvI2F->ConvF2I
2732   // ConvF2L->ConvL2F->ConvF2L
2733   // ConvI2F->ConvF2I->ConvI2F
2734   // Note: there may be other 3-nodes conversion chains that would require to be added here, but these
2735   // are the only ones that are known to trigger missed optimizations otherwise
2736   if (use_op == Op_ConvL2D ||
2737       use_op == Op_ConvI2F ||
2738       use_op == Op_ConvL2F ||
2739       use_op == Op_ConvF2I) {
2740     add_users_to_worklist_if(worklist, use, [=](Node* u) {
2741       return (use_op == Op_ConvL2D && u->Opcode() == Op_ConvD2L) ||
2742              (use_op == Op_ConvI2F && u->Opcode() == Op_ConvF2I) ||
2743              (use_op == Op_ConvL2F && u->Opcode() == Op_ConvF2L) ||
2744              (use_op == Op_ConvF2I && u->Opcode() == Op_ConvI2F);
2745     });
2746   }
2747   // ConvD2F::Ideal matches ConvD2F(SqrtD(ConvF2D(x))) => SqrtF(x).
2748   // Notify ConvD2F users of SqrtD when any input of the SqrtD changes.
2749   if (use_op == Op_SqrtD) {
2750     add_users_to_worklist_if(worklist, use, [](Node* u) { return u->Opcode() == Op_ConvD2F; });
2751   }
2752   // ConvF2HF::Ideal matches ConvF2HF(binopF(ConvHF2F(...))) => FP16BinOp(...).
2753   // Notify ConvF2HF users of float binary ops when any input changes.
2754   if (Float16NodeFactory::is_float32_binary_oper(use_op)) {
2755     add_users_to_worklist_if(worklist, use, [](Node* u) { return u->Opcode() == Op_ConvF2HF; });
2756   }
2757   // If changed AddP inputs:
2758   // - check Stores for loop invariant, and
2759   // - if the changed input is the offset, check constant-offset AddP users for
2760   //   address expression flattening.
2761   if (use_op == Op_AddP) {
2762     bool offset_changed = n == use->in(AddPNode::Offset);
2763     add_users_to_worklist_if(worklist, use, [=](Node* u) {
2764       return u->is_Mem() ||
2765              (offset_changed && u->is_AddP() && u->in(AddPNode::Offset)->is_Con());
2766     });
2767   }
2768   // Check for "abs(0-x)" into "abs(x)" conversion
2769   if (use->is_Sub()) {
2770     add_users_to_worklist_if(worklist, use, [](Node* u) {
2771       return u->Opcode() == Op_AbsD || u->Opcode() == Op_AbsF ||
2772              u->Opcode() == Op_AbsL || u->Opcode() == Op_AbsI;
2773     });
2774   }
2775   // Check for Max/Min(A, Max/Min(B, C)) where A == B or A == C
2776   if (use->is_MinMax()) {
2777     add_users_to_worklist_if(worklist, use, [](Node* u) { return u->is_MinMax(); });
2778   }
2779   auto enqueue_init_mem_projs = [&](ProjNode* proj) {
2780     add_users_to_worklist0(proj, worklist);
2781   };
2782   // If changed initialization activity, check dependent Stores
2783   if (use_op == Op_Allocate || use_op == Op_AllocateArray) {
2784     InitializeNode* init = use->as_Allocate()->initialization();
2785     if (init != nullptr) {
2786       init->for_each_proj(enqueue_init_mem_projs, TypeFunc::Memory);
2787     }
2788   }
2789   // If the ValidLengthTest input changes then the fallthrough path out of the AllocateArray may have become dead.
2790   // CatchNode::Value() is responsible for killing that path. The CatchNode has to be explicitly enqueued for igvn
2791   // to guarantee the change is not missed.
2792   if (use_op == Op_AllocateArray && n == use->in(AllocateNode::ValidLengthTest)) {
2793     Node* p = use->as_AllocateArray()->proj_out_or_null(TypeFunc::Control);
2794     if (p != nullptr) {
2795       add_users_to_worklist0(p, worklist);
2796     }
2797   }
2798 
2799   if (use_op == Op_Initialize) {
2800     InitializeNode* init = use->as_Initialize();
2801     init->for_each_proj(enqueue_init_mem_projs, TypeFunc::Memory);
2802   }
2803   // Loading the java mirror from a Klass requires two loads and the type
2804   // of the mirror load depends on the type of 'n'. See LoadNode::Value().
2805   //   LoadBarrier?(LoadP(LoadP(AddP(foo:Klass, #java_mirror))))
2806   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2807   bool has_load_barrier_nodes = bs->has_load_barrier_nodes();
2808 
2809   if (use_op == Op_CastP2X) {
2810     for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2811       Node* u = use->fast_out(i2);
2812       // TODO 8350865 Still needed? Yes, I think this is from PhaseMacroExpand::expand_mh_intrinsic_return
2813       if (u->Opcode() == Op_AndX) {
2814         worklist.push(u);
2815       }
2816       // Search for CmpL(OrL(CastP2X(..), CastP2X(..)), 0L)
2817       if (u->Opcode() == Op_OrL) {
2818         for (DUIterator_Fast i3max, i3 = u->fast_outs(i3max); i3 < i3max; i3++) {
2819           Node* cmp = u->fast_out(i3);
2820           if (cmp->Opcode() == Op_CmpL) {
2821             worklist.push(cmp);
2822           }
2823         }
2824       }
2825     }
2826   }
2827   if (use_op == Op_LoadP && use->bottom_type()->isa_rawptr()) {
2828     for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2829       Node* u = use->fast_out(i2);
2830       const Type* ut = u->bottom_type();
2831       if (u->Opcode() == Op_LoadP && ut->isa_instptr()) {
2832         if (has_load_barrier_nodes) {
2833           // Search for load barriers behind the load
2834           add_users_to_worklist_if(worklist, u, [&](Node* b) {
2835             return bs->is_gc_barrier_node(b);
2836           });
2837         }
2838         worklist.push(u);
2839       }
2840     }
2841   }
2842   // Give CallStaticJavaNode::remove_useless_allocation a chance to run
2843   if (use->is_Region()) {
2844     Node* c = use;
2845     do {
2846       c = c->unique_ctrl_out_or_null();
2847     } while (c != nullptr && c->is_Region());
2848     if (c != nullptr && c->is_CallStaticJava() && c->as_CallStaticJava()->uncommon_trap_request() != 0) {
2849       worklist.push(c);
2850     }
2851   }
2852   if (use->Opcode() == Op_OpaqueZeroTripGuard) {
2853     assert(use->outcnt() <= 1, "OpaqueZeroTripGuard can't be shared");
2854     if (use->outcnt() == 1) {
2855       Node* cmp = use->unique_out();
2856       worklist.push(cmp);
2857     }
2858   }
2859   // VectorMaskToLongNode::Ideal_MaskAll looks through VectorStoreMask
2860   // to fold constant masks.
2861   if (use_op == Op_VectorStoreMask) {
2862     add_users_to_worklist_if(worklist, use, [](Node* u) { return u->Opcode() == Op_VectorMaskToLong; });
2863   }
2864 
2865   // From CastX2PNode::Ideal
2866   // CastX2P(AddX(x, y))
2867   // CastX2P(SubX(x, y))
2868   if (use->Opcode() == Op_AddX || use->Opcode() == Op_SubX) {
2869     add_users_to_worklist_if(worklist, use, [](Node* u) { return u->Opcode() == Op_CastX2P; });
2870   }
2871 
2872   /* AndNode has a special handling when one of the operands is a LShiftNode:
2873    * (LHS << s) & RHS
2874    * if RHS fits in less than s bits, the value of this expression is 0.
2875    * The difficulty is that there might be a conversion node (ConvI2L) between
2876    * the LShiftINode and the AndLNode, like so:
2877    * AndLNode(ConvI2L(LShiftI(LHS, s)), RHS)
2878    * This case is handled by And[IL]Node::Value(PhaseGVN*)
2879    * (see `AndIL_min_trailing_zeros`).
2880    *
2881    * But, when the shift is updated during IGVN, pushing the user (ConvI2L)
2882    * is not enough: there might be no update happening there. We need to
2883    * directly push the And[IL]Node on the worklist, jumping over ConvI2L.
2884    *
2885    * Moreover we can have ConstraintCasts in between. It may look like
2886    * ConstraintCast+ -> ConvI2L -> ConstraintCast+ -> And
2887    * and And[IL]Node::Value(PhaseGVN*) still handles that by looking through casts.
2888    * So we must deal with that as well.
2889    */
2890   if (use->is_ConstraintCast() || use_op == Op_ConvI2L) {
2891     auto is_boundary = [](Node* n){ return !n->is_ConstraintCast() && n->Opcode() != Op_ConvI2L; };
2892     auto push_and_to_worklist = [&worklist](Node* n){
2893       if (n->Opcode() == Op_AndL || n->Opcode() == Op_AndI) {
2894         worklist.push(n);
2895       }
2896     };
2897     use->visit_uses(push_and_to_worklist, is_boundary);
2898   }
2899 
2900   // If changed Sub inputs, check Add for identity.
2901   // e.g., (x - y) + y -> x; x + (y - x) -> y.
2902   if (use_op == Op_SubI || use_op == Op_SubL) {
2903     const int add_op = (use_op == Op_SubI) ? Op_AddI : Op_AddL;
2904     add_users_to_worklist_if(worklist, use, [=](Node* u) { return u->Opcode() == add_op; });
2905   }
2906 }
2907 
2908 /**
2909  * Remove the speculative part of all types that we know of
2910  */
2911 void PhaseIterGVN::remove_speculative_types()  {
2912   assert(UseTypeSpeculation, "speculation is off");
2913   for (uint i = 0; i < _types.Size(); i++)  {
2914     const Type* t = _types.fast_lookup(i);
2915     if (t != nullptr) {
2916       _types.map(i, t->remove_speculative());
2917     }
2918   }
2919   _table.check_no_speculative_types();
2920 }
2921 
2922 //=============================================================================
2923 #ifndef PRODUCT
2924 uint PhaseCCP::_total_invokes   = 0;
2925 uint PhaseCCP::_total_constants = 0;
2926 #endif
2927 //------------------------------PhaseCCP---------------------------------------
2928 // Conditional Constant Propagation, ala Wegman & Zadeck
2929 PhaseCCP::PhaseCCP( PhaseIterGVN *igvn ) : PhaseIterGVN(igvn) {
2930   NOT_PRODUCT( clear_constants(); )
2931   assert( _worklist.size() == 0, "" );
2932   _phase = PhaseValuesType::ccp;
2933   analyze();
2934 }
2935 
2936 #ifndef PRODUCT
2937 //------------------------------~PhaseCCP--------------------------------------
2938 PhaseCCP::~PhaseCCP() {
2939   inc_invokes();
2940   _total_constants += count_constants();
2941 }
2942 #endif
2943 
2944 
2945 #ifdef ASSERT
2946 void PhaseCCP::verify_type(Node* n, const Type* tnew, const Type* told) {
2947   if (tnew->meet(told) != tnew->remove_speculative()) {
2948     n->dump(3);
2949     tty->print("told = "); told->dump(); tty->cr();
2950     tty->print("tnew = "); tnew->dump(); tty->cr();
2951     fatal("Not monotonic");
2952   }
2953   assert(!told->isa_int() || !tnew->isa_int() || told->is_int()->_widen <= tnew->is_int()->_widen, "widen increases");
2954   assert(!told->isa_long() || !tnew->isa_long() || told->is_long()->_widen <= tnew->is_long()->_widen, "widen increases");
2955 }
2956 #endif //ASSERT
2957 
2958 // In this analysis, all types are initially set to TOP. We iteratively call Value() on all nodes of the graph until
2959 // we reach a fixed-point (i.e. no types change anymore). We start with a list that only contains the root node. Each time
2960 // a new type is set, we push all uses of that node back to the worklist (in some cases, we also push grandchildren
2961 // or nodes even further down back to the worklist because their type could change as a result of the current type
2962 // change).
2963 void PhaseCCP::analyze() {
2964   // Initialize all types to TOP, optimistic analysis
2965   for (uint i = 0; i < C->unique(); i++)  {
2966     _types.map(i, Type::TOP);
2967   }
2968 
2969   // CCP worklist is placed on a local arena, so that we can allow ResourceMarks on "Compile::current()->resource_arena()".
2970   // We also do not want to put the worklist on "Compile::current()->comp_arena()", as that one only gets de-allocated after
2971   // Compile is over. The local arena gets de-allocated at the end of its scope.
2972   ResourceArea local_arena(mtCompiler);
2973   Unique_Node_List worklist(&local_arena);
2974   Unique_Node_List worklist_revisit(&local_arena);
2975   DEBUG_ONLY(Unique_Node_List worklist_verify(&local_arena);)
2976 
2977   // Push root onto worklist
2978   worklist.push(C->root());
2979 
2980   assert(_root_and_safepoints.size() == 0, "must be empty (unused)");
2981   _root_and_safepoints.push(C->root());
2982 
2983   // This is the meat of CCP: pull from worklist; compute new value; push changes out.
2984 
2985   // Do the first round. Since all initial types are TOP, this will visit all alive nodes.
2986   while (worklist.size() != 0) {
2987     Node* n = fetch_next_node(worklist);
2988     DEBUG_ONLY(worklist_verify.push(n);)
2989     if (needs_revisit(n)) {
2990       worklist_revisit.push(n);
2991     }
2992     if (n->is_SafePoint()) {
2993       // Make sure safepoints are processed by PhaseCCP::transform even if they are
2994       // not reachable from the bottom. Otherwise, infinite loops would be removed.
2995       _root_and_safepoints.push(n);
2996     }
2997     analyze_step(worklist, n);
2998   }
2999 
3000   // More rounds to catch updates far in the graph.
3001   // Revisit nodes that might be able to refine their types at the end of the round.
3002   // If so, process these nodes. If there is remaining work, start another round.
3003   do {
3004     while (worklist.size() != 0) {
3005       Node* n = fetch_next_node(worklist);
3006       analyze_step(worklist, n);
3007     }
3008     for (uint t = 0; t < worklist_revisit.size(); t++) {
3009       Node* n = worklist_revisit.at(t);
3010       analyze_step(worklist, n);
3011     }
3012   } while (worklist.size() != 0);
3013 
3014   DEBUG_ONLY(verify_analyze(worklist_verify);)
3015 }
3016 
3017 void PhaseCCP::analyze_step(Unique_Node_List& worklist, Node* n) {
3018   const Type* new_type = n->Value(this);
3019   if (new_type != type(n)) {
3020     DEBUG_ONLY(verify_type(n, new_type, type(n));)
3021     dump_type_and_node(n, new_type);
3022     set_type(n, new_type);
3023     push_child_nodes_to_worklist(worklist, n);
3024   }
3025   if (KillPathsReachableByDeadTypeNode && n->is_Type() && new_type == Type::TOP) {
3026     // Keep track of Type nodes to kill CFG paths that use Type
3027     // nodes that become dead.
3028     _maybe_top_type_nodes.push(n);
3029   }
3030 }
3031 
3032 // Some nodes can refine their types due to type change somewhere deep
3033 // in the graph. We will need to revisit them before claiming convergence.
3034 // Add nodes here if particular *Node::Value is doing deep graph traversals
3035 // not handled by PhaseCCP::push_more_uses().
3036 bool PhaseCCP::needs_revisit(Node* n) const {
3037   // LoadNode performs deep traversals. Load is not notified for changes far away.
3038   if (n->is_Load()) {
3039     return true;
3040   }
3041   // CmpPNode performs deep traversals if it compares oopptr. CmpP is not notified for changes far away.
3042   if (n->Opcode() == Op_CmpP && type(n->in(1))->isa_oopptr() && type(n->in(2))->isa_oopptr()) {
3043     return true;
3044   }
3045   return false;
3046 }
3047 
3048 #ifdef ASSERT
3049 // For every node n on verify list, check if type(n) == n->Value()
3050 // Note for CCP the non-convergence can lead to unsound analysis and mis-compilation.
3051 // Therefore, we are verifying Value convergence strictly.
3052 void PhaseCCP::verify_analyze(Unique_Node_List& worklist_verify) {
3053   while (worklist_verify.size()) {
3054     Node* n = worklist_verify.pop();
3055 
3056     // An assert in verify_Value_for means that PhaseCCP is not at fixpoint
3057     // and that the analysis result may be unsound.
3058     // If this happens, check why the reported nodes were not processed again in CCP.
3059     // We should either make sure that these nodes are properly added back to the CCP worklist
3060     // in PhaseCCP::push_child_nodes_to_worklist() to update their type in the same round,
3061     // or that they are added in PhaseCCP::needs_revisit() so that analysis revisits
3062     // them at the end of the round.
3063     verify_Value_for(n, true);
3064   }
3065 }
3066 #endif
3067 
3068 // Fetch next node from worklist to be examined in this iteration.
3069 Node* PhaseCCP::fetch_next_node(Unique_Node_List& worklist) {
3070   if (StressCCP) {
3071     return worklist.remove(C->random() % worklist.size());
3072   } else {
3073     return worklist.pop();
3074   }
3075 }
3076 
3077 #ifndef PRODUCT
3078 void PhaseCCP::dump_type_and_node(const Node* n, const Type* t) {
3079   if (TracePhaseCCP) {
3080     t->dump();
3081     do {
3082       tty->print("\t");
3083     } while (tty->position() < 16);
3084     n->dump();
3085   }
3086 }
3087 #endif
3088 
3089 bool PhaseCCP::not_bottom_type(Node* n) const {
3090   return n->bottom_type() != type(n);
3091 }
3092 
3093 // We need to propagate the type change of 'n' to all its uses. Depending on the kind of node, additional nodes
3094 // (grandchildren or even further down) need to be revisited as their types could also be improved as a result
3095 // of the new type of 'n'. Push these nodes to the worklist.
3096 void PhaseCCP::push_child_nodes_to_worklist(Unique_Node_List& worklist, Node* n) const {
3097   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3098     Node* use = n->fast_out(i);
3099     push_if_not_bottom_type(worklist, use);
3100     push_more_uses(worklist, n, use);
3101   }
3102 }
3103 
3104 void PhaseCCP::push_if_not_bottom_type(Unique_Node_List& worklist, Node* n) const {
3105   if (not_bottom_type(n)) {
3106     worklist.push(n);
3107   }
3108 }
3109 
3110 // For some nodes, we need to propagate the type change to grandchildren or even further down.
3111 // Add them back to the worklist.
3112 void PhaseCCP::push_more_uses(Unique_Node_List& worklist, Node* parent, const Node* use) const {
3113   push_phis(worklist, use);
3114   push_catch(worklist, use);
3115   push_cmpu(worklist, use);
3116   push_counted_loop_phi(worklist, parent, use);
3117   push_cast(worklist, use);
3118   push_loadp(worklist, use);
3119   push_and(worklist, parent, use);
3120   push_cast_ii(worklist, parent, use);
3121   push_opaque_zero_trip_guard(worklist, use);
3122   push_bool_with_cmpu_and_mask(worklist, use);
3123 }
3124 
3125 
3126 // We must recheck Phis too if use is a Region.
3127 void PhaseCCP::push_phis(Unique_Node_List& worklist, const Node* use) const {
3128   if (use->is_Region()) {
3129     add_users_to_worklist_if(worklist, use, [&](Node* u) {
3130       return not_bottom_type(u);
3131     });
3132   }
3133 }
3134 
3135 // If we changed the receiver type to a call, we need to revisit the Catch node following the call. It's looking for a
3136 // non-null receiver to know when to enable the regular fall-through path in addition to the NullPtrException path.
3137 // Same is true if the type of a ValidLengthTest input to an AllocateArrayNode changes.
3138 void PhaseCCP::push_catch(Unique_Node_List& worklist, const Node* use) {
3139   if (use->is_Call()) {
3140     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
3141       Node* proj = use->fast_out(i);
3142       if (proj->is_Proj() && proj->as_Proj()->_con == TypeFunc::Control) {
3143         Node* catch_node = proj->find_out_with(Op_Catch);
3144         if (catch_node != nullptr) {
3145           worklist.push(catch_node);
3146         }
3147       }
3148     }
3149   }
3150 }
3151 
3152 // CmpU nodes can get their type information from two nodes up in the graph (instead of from the nodes immediately
3153 // above). Make sure they are added to the worklist if nodes they depend on are updated since they could be missed
3154 // and get wrong types otherwise.
3155 void PhaseCCP::push_cmpu(Unique_Node_List& worklist, const Node* use) const {
3156   uint use_op = use->Opcode();
3157   if (use_op == Op_AddI || use_op == Op_SubI) {
3158     // Got a CmpU or CmpU3 which might need the new type information from node n.
3159     add_users_to_worklist_if(worklist, use, [&](Node* u) {
3160       uint op = u->Opcode();
3161       return (op == Op_CmpU || op == Op_CmpU3) && not_bottom_type(u);
3162     });
3163   }
3164 }
3165 
3166 // Look for the following shape, which can be optimized by BoolNode::Value_cmpu_and_mask() (i.e. corresponds to case
3167 // (1b): "(m & x) <u (m + 1))".
3168 // If any of the inputs on the level (%%) change, we need to revisit Bool because we could have prematurely found that
3169 // the Bool is constant (i.e. case (1b) can be applied) which could become invalid with new type information during CCP.
3170 //
3171 //  m    x  m    1  (%%)
3172 //   \  /    \  /
3173 //   AndI    AddI
3174 //      \    /
3175 //       CmpU
3176 //        |
3177 //       Bool
3178 //
3179 void PhaseCCP::push_bool_with_cmpu_and_mask(Unique_Node_List& worklist, const Node* use) const {
3180   uint use_op = use->Opcode();
3181   if (use_op != Op_AndI && (use_op != Op_AddI || use->in(2)->find_int_con(0) != 1)) {
3182     // Not "m & x" or "m + 1"
3183     return;
3184   }
3185   for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
3186     Node* cmpu = use->fast_out(i);
3187     if (cmpu->Opcode() == Op_CmpU) {
3188       push_bool_matching_case1b(worklist, cmpu);
3189     }
3190   }
3191 }
3192 
3193 // Push any Bool below 'cmpu' that matches case (1b) of BoolNode::Value_cmpu_and_mask().
3194 void PhaseCCP::push_bool_matching_case1b(Unique_Node_List& worklist, const Node* cmpu) const {
3195   assert(cmpu->Opcode() == Op_CmpU, "must be");
3196   for (DUIterator_Fast imax, i = cmpu->fast_outs(imax); i < imax; i++) {
3197     Node* bol = cmpu->fast_out(i);
3198     if (!bol->is_Bool() || bol->as_Bool()->_test._test != BoolTest::lt) {
3199       // Not a Bool with "<u"
3200       continue;
3201     }
3202     Node* andI = cmpu->in(1);
3203     Node* addI = cmpu->in(2);
3204     if (andI->Opcode() != Op_AndI || addI->Opcode() != Op_AddI || addI->in(2)->find_int_con(0) != 1) {
3205       // Not "m & x" and "m + 1"
3206       continue;
3207     }
3208 
3209     Node* m = addI->in(1);
3210     if (m == andI->in(1) || m == andI->in(2)) {
3211       // Is "m" shared? Matched (1b) and thus we revisit Bool.
3212       push_if_not_bottom_type(worklist, bol);
3213     }
3214   }
3215 }
3216 
3217 // If n is used in a counted loop exit condition, then the type of the counted loop's Phi depends on the type of 'n'.
3218 // Seem PhiNode::Value().
3219 void PhaseCCP::push_counted_loop_phi(Unique_Node_List& worklist, Node* parent, const Node* use) {
3220   uint use_op = use->Opcode();
3221   if (use_op == Op_CmpI || use_op == Op_CmpL) {
3222     PhiNode* phi = countedloop_phi_from_cmp(use->as_Cmp(), parent);
3223     if (phi != nullptr) {
3224       worklist.push(phi);
3225     }
3226   }
3227 }
3228 
3229 // TODO 8350865 Still needed? Yes, I think this is from PhaseMacroExpand::expand_mh_intrinsic_return
3230 void PhaseCCP::push_cast(Unique_Node_List& worklist, const Node* use) {
3231   uint use_op = use->Opcode();
3232   if (use_op == Op_CastP2X) {
3233     for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
3234       Node* u = use->fast_out(i2);
3235       if (u->Opcode() == Op_AndX) {
3236         worklist.push(u);
3237       }
3238     }
3239   }
3240 }
3241 
3242 // Loading the java mirror from a Klass requires two loads and the type of the mirror load depends on the type of 'n'.
3243 // See LoadNode::Value().
3244 void PhaseCCP::push_loadp(Unique_Node_List& worklist, const Node* use) const {
3245   BarrierSetC2* barrier_set = BarrierSet::barrier_set()->barrier_set_c2();
3246   bool has_load_barrier_nodes = barrier_set->has_load_barrier_nodes();
3247 
3248   if (use->Opcode() == Op_LoadP && use->bottom_type()->isa_rawptr()) {
3249     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
3250       Node* loadp = use->fast_out(i);
3251       const Type* ut = loadp->bottom_type();
3252       if (loadp->Opcode() == Op_LoadP && ut->isa_instptr() && ut != type(loadp)) {
3253         if (has_load_barrier_nodes) {
3254           // Search for load barriers behind the load
3255           push_load_barrier(worklist, barrier_set, loadp);
3256         }
3257         worklist.push(loadp);
3258       }
3259     }
3260   }
3261 }
3262 
3263 void PhaseCCP::push_load_barrier(Unique_Node_List& worklist, const BarrierSetC2* barrier_set, const Node* use) {
3264   add_users_to_worklist_if(worklist, use, [&](Node* u) {
3265     return barrier_set->is_gc_barrier_node(u);
3266   });
3267 }
3268 
3269 // AndI/L::Value() optimizes patterns similar to (v << 2) & 3, or CON & 3 to zero if they are bitwise disjoint.
3270 // Add the AndI/L nodes back to the worklist to re-apply Value() in case the value is now a constant or shift
3271 // value changed.
3272 void PhaseCCP::push_and(Unique_Node_List& worklist, const Node* parent, const Node* use) const {
3273   const TypeInteger* parent_type = type(parent)->isa_integer(type(parent)->basic_type());
3274   uint use_op = use->Opcode();
3275   if (
3276     // Pattern: parent (now constant) -> (ConstraintCast | ConvI2L)* -> And
3277     (parent_type != nullptr && parent_type->is_con()) ||
3278     // Pattern: parent -> LShift (use) -> (ConstraintCast | ConvI2L)* -> And
3279     ((use_op == Op_LShiftI || use_op == Op_LShiftL) && use->in(2) == parent)) {
3280 
3281     auto push_and_uses_to_worklist = [&](Node* n) {
3282       uint opc = n->Opcode();
3283       if (opc == Op_AndI || opc == Op_AndL) {
3284         push_if_not_bottom_type(worklist, n);
3285       }
3286     };
3287     auto is_boundary = [](Node* n) {
3288       return !(n->is_ConstraintCast() || n->Opcode() == Op_ConvI2L);
3289     };
3290     use->visit_uses(push_and_uses_to_worklist, is_boundary);
3291   }
3292 }
3293 
3294 // CastII::Value() optimizes CmpI/If patterns if the right input of the CmpI has a constant type. If the CastII input is
3295 // the same node as the left input into the CmpI node, the type of the CastII node can be improved accordingly. Add the
3296 // CastII node back to the worklist to re-apply Value() to either not miss this optimization or to undo it because it
3297 // cannot be applied anymore. We could have optimized the type of the CastII before but now the type of the right input
3298 // of the CmpI (i.e. 'parent') is no longer constant. The type of the CastII must be widened in this case.
3299 void PhaseCCP::push_cast_ii(Unique_Node_List& worklist, const Node* parent, const Node* use) const {
3300   if (use->Opcode() == Op_CmpI && use->in(2) == parent) {
3301     Node* other_cmp_input = use->in(1);
3302     add_users_to_worklist_if(worklist, other_cmp_input, [&](Node* u) {
3303       return u->is_CastII() && not_bottom_type(u);
3304     });
3305   }
3306 }
3307 
3308 void PhaseCCP::push_opaque_zero_trip_guard(Unique_Node_List& worklist, const Node* use) const {
3309   if (use->Opcode() == Op_OpaqueZeroTripGuard) {
3310     push_if_not_bottom_type(worklist, use->unique_out());
3311   }
3312 }
3313 
3314 //------------------------------do_transform-----------------------------------
3315 // Top level driver for the recursive transformer
3316 void PhaseCCP::do_transform() {
3317   // Correct leaves of new-space Nodes; they point to old-space.
3318   C->set_root( transform(C->root())->as_Root() );
3319   assert( C->top(),  "missing TOP node" );
3320   assert( C->root(), "missing root" );
3321 }
3322 
3323 //------------------------------transform--------------------------------------
3324 // Given a Node in old-space, clone him into new-space.
3325 // Convert any of his old-space children into new-space children.
3326 Node *PhaseCCP::transform( Node *n ) {
3327   assert(n->is_Root(), "traversal must start at root");
3328   assert(_root_and_safepoints.member(n), "root (n) must be in list");
3329 
3330   ResourceMark rm;
3331   // Map: old node idx -> node after CCP (or nullptr if not yet transformed or useless).
3332   Node_List node_map;
3333   // Pre-allocate to avoid frequent realloc
3334   GrowableArray <Node *> transform_stack(C->live_nodes() >> 1);
3335   // track all visited nodes, so that we can remove the complement
3336   Unique_Node_List useful;
3337 
3338   if (KillPathsReachableByDeadTypeNode) {
3339     for (uint i = 0; i < _maybe_top_type_nodes.size(); ++i) {
3340       Node* type_node = _maybe_top_type_nodes.at(i);
3341       if (type(type_node) == Type::TOP) {
3342         ResourceMark rm;
3343         type_node->as_Type()->make_paths_from_here_dead(this, nullptr, "ccp");
3344       }
3345     }
3346   } else {
3347     assert(_maybe_top_type_nodes.size() == 0, "we don't need type nodes");
3348   }
3349 
3350   // Initialize the traversal.
3351   // This CCP pass may prove that no exit test for a loop ever succeeds (i.e. the loop is infinite). In that case,
3352   // the logic below doesn't follow any path from Root to the loop body: there's at least one such path but it's proven
3353   // never taken (its type is TOP). As a consequence the node on the exit path that's input to Root (let's call it n) is
3354   // replaced by the top node and the inputs of that node n are not enqueued for further processing. If CCP only works
3355   // through the graph from Root, this causes the loop body to never be processed here even when it's not dead (that
3356   // is reachable from Root following its uses). To prevent that issue, transform() starts walking the graph from Root
3357   // and all safepoints.
3358   for (uint i = 0; i < _root_and_safepoints.size(); ++i) {
3359     Node* nn = _root_and_safepoints.at(i);
3360     Node* new_node = node_map[nn->_idx];
3361     assert(new_node == nullptr, "");
3362     new_node = transform_once(nn);  // Check for constant
3363     node_map.map(nn->_idx, new_node); // Flag as having been cloned
3364     transform_stack.push(new_node); // Process children of cloned node
3365     useful.push(new_node);
3366   }
3367 
3368   while (transform_stack.is_nonempty()) {
3369     Node* clone = transform_stack.pop();
3370     uint cnt = clone->req();
3371     for( uint i = 0; i < cnt; i++ ) {          // For all inputs do
3372       Node *input = clone->in(i);
3373       if( input != nullptr ) {                 // Ignore nulls
3374         Node *new_input = node_map[input->_idx]; // Check for cloned input node
3375         if( new_input == nullptr ) {
3376           new_input = transform_once(input);   // Check for constant
3377           node_map.map( input->_idx, new_input );// Flag as having been cloned
3378           transform_stack.push(new_input);     // Process children of cloned node
3379           useful.push(new_input);
3380         }
3381         assert( new_input == clone->in(i), "insanity check");
3382       }
3383     }
3384   }
3385 
3386   // The above transformation might lead to subgraphs becoming unreachable from the
3387   // bottom while still being reachable from the top. As a result, nodes in that
3388   // subgraph are not transformed and their bottom types are not updated, leading to
3389   // an inconsistency between bottom_type() and type(). In rare cases, LoadNodes in
3390   // such a subgraph, might be re-enqueued for IGVN indefinitely by MemNode::Ideal_common
3391   // because their address type is inconsistent. Therefore, we aggressively remove
3392   // all useless nodes here even before PhaseIdealLoop::build_loop_late gets a chance
3393   // to remove them anyway.
3394   if (C->cached_top_node()) {
3395     useful.push(C->cached_top_node());
3396   }
3397   C->update_dead_node_list(useful);
3398   remove_useless_nodes(useful.member_set());
3399   _worklist.remove_useless_nodes(useful.member_set());
3400   C->disconnect_useless_nodes(useful, _worklist, &_root_and_safepoints);
3401 
3402   Node* new_root = node_map[n->_idx];
3403   assert(new_root->is_Root(), "transformed root node must be a root node");
3404   return new_root;
3405 }
3406 
3407 //------------------------------transform_once---------------------------------
3408 // For PhaseCCP, transformation is IDENTITY unless Node computed a constant.
3409 Node *PhaseCCP::transform_once( Node *n ) {
3410   const Type *t = type(n);
3411   // Constant?  Use constant Node instead
3412   if( t->singleton() ) {
3413     Node *nn = n;               // Default is to return the original constant
3414     if( t == Type::TOP ) {
3415       // cache my top node on the Compile instance
3416       if( C->cached_top_node() == nullptr || C->cached_top_node()->in(0) == nullptr ) {
3417         C->set_cached_top_node(ConNode::make(Type::TOP));
3418         set_type(C->top(), Type::TOP);
3419       }
3420       nn = C->top();
3421     }
3422     if( !n->is_Con() ) {
3423       if( t != Type::TOP ) {
3424         nn = makecon(t);        // ConNode::make(t);
3425         NOT_PRODUCT( inc_constants(); )
3426       } else if( n->is_Region() ) { // Unreachable region
3427         // Note: nn == C->top()
3428         n->set_req(0, nullptr);     // Cut selfreference
3429         bool progress = true;
3430         uint max = n->outcnt();
3431         DUIterator i;
3432         while (progress) {
3433           progress = false;
3434           // Eagerly remove dead phis to avoid phis copies creation.
3435           for (i = n->outs(); n->has_out(i); i++) {
3436             Node* m = n->out(i);
3437             if (m->is_Phi()) {
3438               assert(type(m) == Type::TOP, "Unreachable region should not have live phis.");
3439               replace_node(m, nn);
3440               if (max != n->outcnt()) {
3441                 progress = true;
3442                 i = n->refresh_out_pos(i);
3443                 max = n->outcnt();
3444               }
3445             }
3446           }
3447         }
3448       }
3449       replace_node(n,nn);       // Update DefUse edges for new constant
3450     }
3451     return nn;
3452   }
3453 
3454   // If x is a TypeNode, capture any more-precise type permanently into Node
3455   if (t != n->bottom_type()) {
3456     hash_delete(n);             // changing bottom type may force a rehash
3457     n->raise_bottom_type(t);
3458     _worklist.push(n);          // n re-enters the hash table via the worklist
3459     add_users_to_worklist(n);   // if ideal or identity optimizations depend on the input type, users need to be notified
3460   }
3461 
3462   // TEMPORARY fix to ensure that 2nd GVN pass eliminates null checks
3463   switch( n->Opcode() ) {
3464   case Op_CallStaticJava:  // Give post-parse call devirtualization a chance
3465   case Op_CallDynamicJava:
3466   case Op_FastLock:        // Revisit FastLocks for lock coarsening
3467   case Op_If:
3468   case Op_CountedLoopEnd:
3469   case Op_Region:
3470   case Op_Loop:
3471   case Op_CountedLoop:
3472   case Op_Conv2B:
3473   case Op_Opaque1:
3474     _worklist.push(n);
3475     break;
3476   default:
3477     break;
3478   }
3479 
3480   return  n;
3481 }
3482 
3483 //---------------------------------saturate------------------------------------
3484 const Type* PhaseCCP::saturate(const Type* new_type, const Type* old_type,
3485                                const Type* limit_type) const {
3486   const Type* wide_type = new_type->widen(old_type, limit_type);
3487   if (wide_type != new_type) {          // did we widen?
3488     // If so, we may have widened beyond the limit type.  Clip it back down.
3489     new_type = wide_type->filter(limit_type);
3490   }
3491   return new_type;
3492 }
3493 
3494 //------------------------------print_statistics-------------------------------
3495 #ifndef PRODUCT
3496 void PhaseCCP::print_statistics() {
3497   tty->print_cr("CCP: %d  constants found: %d", _total_invokes, _total_constants);
3498 }
3499 #endif
3500 
3501 
3502 //=============================================================================
3503 #ifndef PRODUCT
3504 uint PhasePeephole::_total_peepholes = 0;
3505 #endif
3506 //------------------------------PhasePeephole----------------------------------
3507 // Conditional Constant Propagation, ala Wegman & Zadeck
3508 PhasePeephole::PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg )
3509   : PhaseTransform(Peephole), _regalloc(regalloc), _cfg(cfg) {
3510   NOT_PRODUCT( clear_peepholes(); )
3511 }
3512 
3513 #ifndef PRODUCT
3514 //------------------------------~PhasePeephole---------------------------------
3515 PhasePeephole::~PhasePeephole() {
3516   _total_peepholes += count_peepholes();
3517 }
3518 #endif
3519 
3520 //------------------------------transform--------------------------------------
3521 Node *PhasePeephole::transform( Node *n ) {
3522   ShouldNotCallThis();
3523   return nullptr;
3524 }
3525 
3526 //------------------------------do_transform-----------------------------------
3527 void PhasePeephole::do_transform() {
3528   bool method_name_not_printed = true;
3529 
3530   // Examine each basic block
3531   for (uint block_number = 1; block_number < _cfg.number_of_blocks(); ++block_number) {
3532     Block* block = _cfg.get_block(block_number);
3533     bool block_not_printed = true;
3534 
3535     for (bool progress = true; progress;) {
3536       progress = false;
3537       // block->end_idx() not valid after PhaseRegAlloc
3538       uint end_index = block->number_of_nodes();
3539       for( uint instruction_index = end_index - 1; instruction_index > 0; --instruction_index ) {
3540         Node     *n = block->get_node(instruction_index);
3541         if( n->is_Mach() ) {
3542           MachNode *m = n->as_Mach();
3543           // check for peephole opportunities
3544           int result = m->peephole(block, instruction_index, &_cfg, _regalloc);
3545           if( result != -1 ) {
3546 #ifndef PRODUCT
3547             if( PrintOptoPeephole ) {
3548               // Print method, first time only
3549               if( C->method() && method_name_not_printed ) {
3550                 C->method()->print_short_name(); tty->cr();
3551                 method_name_not_printed = false;
3552               }
3553               // Print this block
3554               if( Verbose && block_not_printed) {
3555                 tty->print_cr("in block");
3556                 block->dump();
3557                 block_not_printed = false;
3558               }
3559               // Print the peephole number
3560               tty->print_cr("peephole number: %d", result);
3561             }
3562             inc_peepholes();
3563 #endif
3564             // Set progress, start again
3565             progress = true;
3566             break;
3567           }
3568         }
3569       }
3570     }
3571   }
3572 }
3573 
3574 //------------------------------print_statistics-------------------------------
3575 #ifndef PRODUCT
3576 void PhasePeephole::print_statistics() {
3577   tty->print_cr("Peephole: peephole rules applied: %d",  _total_peepholes);
3578 }
3579 #endif
3580 
3581 
3582 //=============================================================================
3583 //------------------------------set_req_X--------------------------------------
3584 void Node::set_req_X( uint i, Node *n, PhaseIterGVN *igvn ) {
3585   assert( is_not_dead(n), "can not use dead node");
3586 #ifdef ASSERT
3587   if (igvn->hash_find(this) == this) {
3588     tty->print_cr("Need to remove from hash before changing edges");
3589     this->dump(1);
3590     tty->print_cr("Set at i = %d", i);
3591     n->dump();
3592     assert(false, "Need to remove from hash before changing edges");
3593   }
3594 #endif
3595   Node *old = in(i);
3596   set_req(i, n);
3597 
3598   // old goes dead?
3599   if( old ) {
3600     switch (old->outcnt()) {
3601     case 0:
3602       // Put into the worklist to kill later. We do not kill it now because the
3603       // recursive kill will delete the current node (this) if dead-loop exists
3604       if (!old->is_top())
3605         igvn->_worklist.push( old );
3606       break;
3607     case 1:
3608       if( old->is_Store() || old->has_special_unique_user() )
3609         igvn->add_users_to_worklist( old );
3610       break;
3611     case 2:
3612       if( old->is_Store() )
3613         igvn->add_users_to_worklist( old );
3614       if( old->Opcode() == Op_Region )
3615         igvn->_worklist.push(old);
3616       break;
3617     case 3:
3618       if( old->Opcode() == Op_Region ) {
3619         igvn->_worklist.push(old);
3620         igvn->add_users_to_worklist( old );
3621       }
3622       break;
3623     default:
3624       break;
3625     }
3626 
3627     BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(igvn, old);
3628   }
3629 }
3630 
3631 void Node::set_req_X(uint i, Node *n, PhaseGVN *gvn) {
3632   PhaseIterGVN* igvn = gvn->is_IterGVN();
3633   if (igvn == nullptr) {
3634     set_req(i, n);
3635     return;
3636   }
3637   set_req_X(i, n, igvn);
3638 }
3639 
3640 //-------------------------------replace_by-----------------------------------
3641 // Using def-use info, replace one node for another.  Follow the def-use info
3642 // to all users of the OLD node.  Then make all uses point to the NEW node.
3643 void Node::replace_by(Node *new_node) {
3644   assert(!is_top(), "top node has no DU info");
3645   for (DUIterator_Last imin, i = last_outs(imin); i >= imin; ) {
3646     Node* use = last_out(i);
3647     uint uses_found = 0;
3648     for (uint j = 0; j < use->len(); j++) {
3649       if (use->in(j) == this) {
3650         if (j < use->req())
3651               use->set_req(j, new_node);
3652         else  use->set_prec(j, new_node);
3653         uses_found++;
3654       }
3655     }
3656     i -= uses_found;    // we deleted 1 or more copies of this edge
3657   }
3658 }
3659 
3660 //=============================================================================
3661 //-----------------------------------------------------------------------------
3662 void Type_Array::grow( uint i ) {
3663   assert(_a == Compile::current()->comp_arena(), "Should be allocated in comp_arena");
3664   if( !_max ) {
3665     _max = 1;
3666     _types = (const Type**)_a->Amalloc( _max * sizeof(Type*) );
3667     _types[0] = nullptr;
3668   }
3669   uint old = _max;
3670   _max = next_power_of_2(i);
3671   _types = (const Type**)_a->Arealloc( _types, old*sizeof(Type*),_max*sizeof(Type*));
3672   memset( &_types[old], 0, (_max-old)*sizeof(Type*) );
3673 }
3674 
3675 //------------------------------dump-------------------------------------------
3676 #ifndef PRODUCT
3677 void Type_Array::dump() const {
3678   uint max = Size();
3679   for( uint i = 0; i < max; i++ ) {
3680     if( _types[i] != nullptr ) {
3681       tty->print("  %d\t== ", i); _types[i]->dump(); tty->cr();
3682     }
3683   }
3684 }
3685 #endif