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 ---> %d/%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     NOT_PRODUCT(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     NOT_PRODUCT(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     NOT_PRODUCT(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() {
 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();
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 void PhaseIterGVN::optimize() {
1044   DEBUG_ONLY(uint num_processed  = 0;)
1045   NOT_PRODUCT(init_verifyPhaseIterGVN();)
1046   NOT_PRODUCT(C->reset_igv_phase_iter(PHASE_AFTER_ITER_GVN_STEP);)
1047   C->print_method(PHASE_BEFORE_ITER_GVN, 3);
1048   if (StressIGVN) {
1049     shuffle_worklist();
1050   }
1051 
1052   // The node count check in the loop below (check_node_count) assumes that we
1053   // increase the live node count with at most
1054   // max_live_nodes_increase_per_iteration in between checks. If this
1055   // assumption does not hold, there is a risk that we exceed the max node
1056   // limit in between checks and trigger an assert during node creation.
1057   const int max_live_nodes_increase_per_iteration = NodeLimitFudgeFactor * 3;
1058 
1059   uint loop_count = 0;
1060   // Pull from worklist and transform the node. If the node has changed,
1061   // update edge info and put uses on worklist.
1062   while (_worklist.size() > 0) {
1063     if (C->check_node_count(max_live_nodes_increase_per_iteration, "Out of nodes")) {
1064       C->print_method(PHASE_AFTER_ITER_GVN, 3);
1065       return;
1066     }
1067     Node* n  = _worklist.pop();
1068     if (loop_count >= K * C->live_nodes()) {
1069       DEBUG_ONLY(dump_infinite_loop_info(n, "PhaseIterGVN::optimize");)
1070       C->record_method_not_compilable("infinite loop in PhaseIterGVN::optimize");
1071       C->print_method(PHASE_AFTER_ITER_GVN, 3);
1072       return;
1073     }
1074     DEBUG_ONLY(trace_PhaseIterGVN_verbose(n, num_processed++);)
1075     if (n->outcnt() != 0) {
1076       NOT_PRODUCT(const Type* oldtype = type_or_null(n));
1077       // Do the transformation
1078       DEBUG_ONLY(int live_nodes_before = C->live_nodes();)
1079       Node* nn = transform_old(n);
1080       DEBUG_ONLY(int live_nodes_after = C->live_nodes();)
1081       // Ensure we did not increase the live node count with more than
1082       // max_live_nodes_increase_per_iteration during the call to transform_old
1083       DEBUG_ONLY(int increase = live_nodes_after - live_nodes_before;)
1084       assert(increase < max_live_nodes_increase_per_iteration,
1085              "excessive live node increase in single iteration of IGVN: %d "
1086              "(should be at most %d)",
1087              increase, max_live_nodes_increase_per_iteration);
1088       NOT_PRODUCT(trace_PhaseIterGVN(n, nn, oldtype);)
1089     } else if (!n->is_top()) {
1090       remove_dead_node(n);
1091     }
1092     loop_count++;
1093   }
1094   NOT_PRODUCT(verify_PhaseIterGVN();)
1095   C->print_method(PHASE_AFTER_ITER_GVN, 3);
1096 }
1097 
1098 #ifdef ASSERT
1099 void PhaseIterGVN::verify_optimize() {
1100   assert(_worklist.size() == 0, "igvn worklist must be empty before verify");
1101 
1102   if (is_verify_Value() ||
1103       is_verify_Ideal() ||
1104       is_verify_Identity() ||
1105       is_verify_invariants()) {
1106     ResourceMark rm;
1107     Unique_Node_List worklist;
1108     // BFS all nodes, starting at root
1109     worklist.push(C->root());
1110     for (uint j = 0; j < worklist.size(); ++j) {
1111       Node* n = worklist.at(j);
1112       // If we get an assert here, check why the reported node was not processed again in IGVN.
1113       // We should either make sure that this node is properly added back to the IGVN worklist
1114       // in PhaseIterGVN::add_users_to_worklist to update it again or add an exception
1115       // in the verification methods below if that is not possible for some reason (like Load nodes).
1116       if (is_verify_Value()) {
1117         verify_Value_for(n);
1118       }
1119       if (is_verify_Ideal()) {
1120         verify_Ideal_for(n, false);
1121         verify_Ideal_for(n, true);
1122       }
1123       if (is_verify_Identity()) {
1124         verify_Identity_for(n);
1125       }
1126       if (is_verify_invariants()) {
1127         verify_node_invariants_for(n);
1128       }
1129 
1130       // traverse all inputs and outputs
1131       for (uint i = 0; i < n->req(); i++) {
1132         if (n->in(i) != nullptr) {
1133           worklist.push(n->in(i));
1134         }
1135       }
1136       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1137         worklist.push(n->fast_out(i));
1138       }
1139     }
1140   }
1141 
1142   verify_empty_worklist(nullptr);
1143 }
1144 
1145 void PhaseIterGVN::verify_empty_worklist(Node* node) {
1146   // Verify that the igvn worklist is empty. If no optimization happened, then
1147   // nothing needs to be on the worklist.
1148   if (_worklist.size() == 0) { return; }
1149 
1150   stringStream ss; // Print as a block without tty lock.
1151   for (uint j = 0; j < _worklist.size(); j++) {
1152     Node* n = _worklist.at(j);
1153     ss.print("igvn.worklist[%d] ", j);
1154     n->dump("\n", false, &ss);
1155   }
1156   if (_worklist.size() != 0 && node != nullptr) {
1157     ss.print_cr("Previously optimized:");
1158     node->dump("\n", false, &ss);
1159   }
1160   tty->print_cr("%s", ss.as_string());
1161   assert(false, "igvn worklist must still be empty after verify");
1162 }
1163 
1164 // Check that type(n) == n->Value(), asserts if we have a failure.
1165 // We have a list of exceptions, see detailed comments in code.
1166 // (1) Integer "widen" changes, but the range is the same.
1167 // (2) LoadNode performs deep traversals. Load is not notified for changes far away.
1168 // (3) CmpPNode performs deep traversals if it compares oopptr. CmpP is not notified for changes far away.
1169 void PhaseIterGVN::verify_Value_for(const Node* n, bool strict) {
1170   // If we assert inside type(n), because the type is still a null, then maybe
1171   // the node never went through gvn.transform, which would be a bug.
1172   const Type* told = type(n);
1173   const Type* tnew = n->Value(this);
1174   if (told == tnew) {
1175     return;
1176   }
1177   // Exception (1)
1178   // Integer "widen" changes, but range is the same.
1179   if (told->isa_integer(tnew->basic_type()) != nullptr) { // both either int or long
1180     const TypeInteger* t0 = told->is_integer(tnew->basic_type());
1181     const TypeInteger* t1 = tnew->is_integer(tnew->basic_type());
1182     if (t0->lo_as_long() == t1->lo_as_long() &&
1183         t0->hi_as_long() == t1->hi_as_long()) {
1184       return; // ignore integer widen
1185     }
1186   }
1187   // Exception (2)
1188   // LoadNode performs deep traversals. Load is not notified for changes far away.
1189   if (!strict && n->is_Load() && !told->singleton()) {
1190     // MemNode::can_see_stored_value looks up through many memory nodes,
1191     // which means we would need to notify modifications from far up in
1192     // the inputs all the way down to the LoadNode. We don't do that.
1193     return;
1194   }
1195   // Exception (3)
1196   // CmpPNode performs deep traversals if it compares oopptr. CmpP is not notified for changes far away.
1197   if (!strict && n->Opcode() == Op_CmpP && type(n->in(1))->isa_oopptr() && type(n->in(2))->isa_oopptr()) {
1198     // SubNode::Value
1199     // CmpPNode::sub
1200     // MemNode::detect_ptr_independence
1201     // MemNode::all_controls_dominate
1202     // We find all controls of a pointer load, and see if they dominate the control of
1203     // an allocation. If they all dominate, we know the allocation is after (independent)
1204     // of the pointer load, and we can say the pointers are different. For this we call
1205     // n->dominates(sub, nlist) to check if controls n of the pointer load dominate the
1206     // control sub of the allocation. The problems is that sometimes dominates answers
1207     // false conservatively, and later it can determine that it is indeed true. Loops with
1208     // Region heads can lead to giving up, whereas LoopNodes can be skipped easier, and
1209     // so the traversal becomes more powerful. This is difficult to remedy, we would have
1210     // to notify the CmpP of CFG updates. Luckily, we recompute CmpP::Value during CCP
1211     // after loop-opts, so that should take care of many of these cases.
1212     return;
1213   }
1214 
1215   stringStream ss; // Print as a block without tty lock.
1216   ss.cr();
1217   ss.print_cr("Missed Value optimization:");
1218   n->dump_bfs(1, nullptr, "", &ss);
1219   ss.print_cr("Current type:");
1220   told->dump_on(&ss);
1221   ss.cr();
1222   ss.print_cr("Optimized type:");
1223   tnew->dump_on(&ss);
1224   ss.cr();
1225   tty->print_cr("%s", ss.as_string());
1226 
1227   switch (_phase) {
1228     case PhaseValuesType::iter_gvn:
1229       assert(false, "Missed Value optimization opportunity in PhaseIterGVN for %s",n->Name());
1230       break;
1231     case PhaseValuesType::ccp:
1232       assert(false, "PhaseCCP not at fixpoint: analysis result may be unsound for %s", n->Name());
1233       break;
1234     default:
1235       assert(false, "Unexpected phase");
1236       break;
1237   }
1238 }
1239 
1240 // Check that all Ideal optimizations that could be done were done.
1241 // Asserts if it found missed optimization opportunities or encountered unexpected changes, and
1242 //         returns normally otherwise (no missed optimization, or skipped verification).
1243 void PhaseIterGVN::verify_Ideal_for(Node* n, bool can_reshape) {
1244   // First, we check a list of exceptions, where we skip verification,
1245   // because there are known cases where Ideal can optimize after IGVN.
1246   // Some may be expected and cannot be fixed, and others should be fixed.
1247   switch (n->Opcode()) {
1248     // RangeCheckNode::Ideal looks up the chain for about 999 nodes
1249     // (see "Range-Check scan limit"). So, it is possible that something
1250     // is optimized in that input subgraph, and the RangeCheck was not
1251     // added to the worklist because it would be too expensive to walk
1252     // down the graph for 1000 nodes and put all on the worklist.
1253     //
1254     // Found with:
1255     //   java -XX:VerifyIterativeGVN=0100 -Xbatch --version
1256     case Op_RangeCheck:
1257       return;
1258 
1259     // IfNode::Ideal does:
1260     //   Node* prev_dom = search_identical(dist, igvn);
1261     // which means we seach up the CFG, traversing at most up to a distance.
1262     // If anything happens rather far away from the If, we may not put the If
1263     // back on the worklist.
1264     //
1265     // Found with:
1266     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1267     case Op_If:
1268       return;
1269 
1270     // IfNode::simple_subsuming
1271     // Looks for dominating test that subsumes the current test.
1272     // Notification could be difficult because of larger distance.
1273     //
1274     // Found with:
1275     //   runtime/exceptionMsgs/ArrayIndexOutOfBoundsException/ArrayIndexOutOfBoundsExceptionTest.java#id1
1276     //   -XX:VerifyIterativeGVN=1110
1277     case Op_CountedLoopEnd:
1278       return;
1279 
1280     // LongCountedLoopEndNode::Ideal
1281     // Probably same issue as above.
1282     //
1283     // Found with:
1284     //   compiler/predicates/assertion/TestAssertionPredicates.java#NoLoopPredicationXbatch
1285     //   -XX:StressLongCountedLoop=2000000 -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1286     case Op_LongCountedLoopEnd:
1287       return;
1288 
1289     // RegionNode::Ideal does "Skip around the useless IF diamond".
1290     //   245  IfTrue  === 244
1291     //   258  If  === 245 257
1292     //   259  IfTrue  === 258  [[ 263 ]]
1293     //   260  IfFalse  === 258  [[ 263 ]]
1294     //   263  Region  === 263 260 259  [[ 263 268 ]]
1295     // to
1296     //   245  IfTrue  === 244
1297     //   263  Region  === 263 245 _  [[ 263 268 ]]
1298     //
1299     // "Useless" means that there is no code in either branch of the If.
1300     // I found a case where this was not done yet during IGVN.
1301     // Why does the Region not get added to IGVN worklist when the If diamond becomes useless?
1302     //
1303     // Found with:
1304     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1305     case Op_Region:
1306       return;
1307 
1308     // In AddNode::Ideal, we call "commute", which swaps the inputs so
1309     // that smaller idx are first. Tracking it back, it led me to
1310     // PhaseIdealLoop::remix_address_expressions which swapped the edges.
1311     //
1312     // Example:
1313     //   Before PhaseIdealLoop::remix_address_expressions
1314     //     154  AddI  === _ 12 144
1315     //   After PhaseIdealLoop::remix_address_expressions
1316     //     154  AddI  === _ 144 12
1317     //   After AddNode::Ideal
1318     //     154  AddI  === _ 12 144
1319     //
1320     // I suspect that the node should be added to the IGVN worklist after
1321     // PhaseIdealLoop::remix_address_expressions
1322     //
1323     // This is the only case I looked at, there may be others. Found like this:
1324     //   java -XX:VerifyIterativeGVN=0100 -Xbatch --version
1325     //
1326     // The following hit the same logic in PhaseIdealLoop::remix_address_expressions.
1327     //
1328     // Note: currently all of these fail also for other reasons, for example
1329     // because of "commute" doing the reordering with the phi below. Once
1330     // that is resolved, we can come back to this issue here.
1331     //
1332     // case Op_AddD:
1333     // case Op_AddI:
1334     // case Op_AddL:
1335     // case Op_AddF:
1336     // case Op_MulI:
1337     // case Op_MulL:
1338     // case Op_MulF:
1339     // case Op_MulD:
1340     //   if (n->in(1)->_idx > n->in(2)->_idx) {
1341     //     // Expect "commute" to revert this case.
1342     //     return false;
1343     //   }
1344     //   break; // keep verifying
1345 
1346     // AddFNode::Ideal calls "commute", which can reorder the inputs for this:
1347     //   Check for tight loop increments: Loop-phi of Add of loop-phi
1348     // It wants to take the phi into in(1):
1349     //    471  Phi  === 435 38 390
1350     //    390  AddF  === _ 471 391
1351     //
1352     // Other Associative operators are also affected equally.
1353     //
1354     // Investigate why this does not happen earlier during IGVN.
1355     //
1356     // Found with:
1357     //   test/hotspot/jtreg/compiler/loopopts/superword/ReductionPerf.java
1358     //   -XX:VerifyIterativeGVN=1110
1359     case Op_AddD:
1360     //case Op_AddI: // Also affected for other reasons, see case further down.
1361     //case Op_AddL: // Also affected for other reasons, see case further down.
1362     case Op_AddF:
1363     case Op_MulI:
1364     case Op_MulL:
1365     case Op_MulF:
1366     case Op_MulD:
1367     case Op_MinF:
1368     case Op_MinD:
1369     case Op_MaxF:
1370     case Op_MaxD:
1371     // XorINode::Ideal
1372     // Found with:
1373     //   compiler/intrinsics/chacha/TestChaCha20.java
1374     //   -XX:VerifyIterativeGVN=1110
1375     case Op_XorI:
1376     case Op_XorL:
1377     // It seems we may have similar issues with the HF cases.
1378     // Found with aarch64:
1379     //   compiler/vectorization/TestFloat16VectorOperations.java
1380     //   -XX:VerifyIterativeGVN=1110
1381     case Op_AddHF:
1382     case Op_MulHF:
1383     case Op_MaxHF:
1384     case Op_MinHF:
1385       return;
1386 
1387     // In MulNode::Ideal the edges can be swapped to help value numbering:
1388     //
1389     //    // We are OK if right is a constant, or right is a load and
1390     //    // left is a non-constant.
1391     //    if( !(t2->singleton() ||
1392     //          (in(2)->is_Load() && !(t1->singleton() || in(1)->is_Load())) ) ) {
1393     //      if( t1->singleton() ||       // Left input is a constant?
1394     //          // Otherwise, sort inputs (commutativity) to help value numbering.
1395     //          (in(1)->_idx > in(2)->_idx) ) {
1396     //        swap_edges(1, 2);
1397     //
1398     // Why was this not done earlier during IGVN?
1399     //
1400     // Found with:
1401     //    test/hotspot/jtreg/gc/stress/gcbasher/TestGCBasherWithG1.java
1402     //    -XX:VerifyIterativeGVN=1110
1403     case Op_AndI:
1404     // Same for AndL.
1405     // Found with:
1406     //   compiler/intrinsics/bigInteger/MontgomeryMultiplyTest.java
1407     //    -XX:VerifyIterativeGVN=1110
1408     case Op_AndL:
1409       return;
1410 
1411     // SubLNode::Ideal does transform like:
1412     //   Convert "c1 - (y+c0)" into "(c1-c0) - y"
1413     //
1414     // In IGVN before verification:
1415     //   8423  ConvI2L  === _ 3519  [[ 8424 ]]  #long:-2
1416     //   8422  ConvI2L  === _ 8399  [[ 8424 ]]  #long:3..256:www
1417     //   8424  AddL  === _ 8422 8423  [[ 8383 ]]  !orig=[8382]
1418     //   8016  ConL  === 0  [[ 8383 ]]  #long:0
1419     //   8383  SubL  === _ 8016 8424  [[ 8156 ]]  !orig=[8154]
1420     //
1421     // And then in verification:
1422     //   8338  ConL  === 0  [[ 8339 8424 ]]  #long:-2     <----- Was constant folded.
1423     //   8422  ConvI2L  === _ 8399  [[ 8424 ]]  #long:3..256:www
1424     //   8424  AddL  === _ 8422 8338  [[ 8383 ]]  !orig=[8382]
1425     //   8016  ConL  === 0  [[ 8383 ]]  #long:0
1426     //   8383  SubL  === _ 8016 8424  [[ 8156 ]]  !orig=[8154]
1427     //
1428     // So the form changed from:
1429     //   c1 - (y + [8423  ConvI2L])
1430     // to
1431     //   c1 - (y + -2)
1432     // but the SubL was not added to the IGVN worklist. Investigate why.
1433     // There could be other issues too.
1434     //
1435     // There seems to be a related AddL IGVN optimization that triggers
1436     // the same SubL optimization, so investigate that too.
1437     //
1438     // Found with:
1439     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1440     case Op_SubL:
1441       return;
1442 
1443     // SubINode::Ideal does
1444     // Convert "x - (y+c0)" into "(x-y) - c0" AND
1445     // Convert "c1 - (y+c0)" into "(c1-c0) - y"
1446     //
1447     // Investigate why this does not yet happen during IGVN.
1448     //
1449     // Found with:
1450     //   test/hotspot/jtreg/compiler/c2/IVTest.java
1451     //   -XX:VerifyIterativeGVN=1110
1452     case Op_SubI:
1453       return;
1454 
1455     // AddNode::IdealIL does transform like:
1456     //   Convert x + (con - y) into "(x - y) + con"
1457     //
1458     // In IGVN before verification:
1459     //   8382  ConvI2L
1460     //   8381  ConvI2L  === _ 791  [[ 8383 ]]  #long:0
1461     //   8383  SubL  === _ 8381 8382
1462     //   8168  ConvI2L
1463     //   8156  AddL  === _ 8168 8383  [[ 8158 ]]
1464     //
1465     // And then in verification:
1466     //   8424  AddL
1467     //   8016  ConL  === 0  [[ 8383 ]]  #long:0  <--- Was constant folded.
1468     //   8383  SubL  === _ 8016 8424
1469     //   8168  ConvI2L
1470     //   8156  AddL  === _ 8168 8383  [[ 8158 ]]
1471     //
1472     // So the form changed from:
1473     //   x + (ConvI2L(0) - [8382  ConvI2L])
1474     // to
1475     //   x + (0 - [8424  AddL])
1476     // but the AddL was not added to the IGVN worklist. Investigate why.
1477     // There could be other issues, too. For example with "commute", see above.
1478     //
1479     // Found with:
1480     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1481     case Op_AddL:
1482       return;
1483 
1484     // SubTypeCheckNode::Ideal calls SubTypeCheckNode::verify_helper, which does
1485     //   Node* cmp = phase->transform(new CmpPNode(subklass, in(SuperKlass)));
1486     //   record_for_cleanup(cmp, phase);
1487     // This verification code in the Ideal code creates new nodes, and checks
1488     // if they fold in unexpected ways. This means some nodes are created and
1489     // added to the worklist, even if the SubTypeCheck is not optimized. This
1490     // goes agains the assumption of the verification here, which assumes that
1491     // if the node is not optimized, then no new nodes should be created, and
1492     // also no nodes should be added to the worklist.
1493     // I see two options:
1494     //  1) forbid what verify_helper does, because for each Ideal call it
1495     //     uses memory and that is suboptimal. But it is not clear how that
1496     //     verification can be done otherwise.
1497     //  2) Special case the verification here. Probably the new nodes that
1498     //     were just created are dead, i.e. they are not connected down to
1499     //     root. We could verify that, and remove those nodes from the graph
1500     //     by setting all their inputs to nullptr. And of course we would
1501     //     have to remove those nodes from the worklist.
1502     // Maybe there are other options too, I did not dig much deeper yet.
1503     //
1504     // Found with:
1505     //   java -XX:VerifyIterativeGVN=0100 -Xbatch --version
1506     case Op_SubTypeCheck:
1507       return;
1508 
1509     // LoopLimitNode::Ideal when stride is constant power-of-2, we can do a lowering
1510     // to other nodes: Conv, Add, Sub, Mul, And ...
1511     //
1512     //  107  ConI  === 0  [[ ... ]]  #int:2
1513     //   84  LoadRange  === _ 7 83
1514     //   50  ConI  === 0  [[ ... ]]  #int:0
1515     //  549  LoopLimit  === _ 50 84 107
1516     //
1517     // I stepped backward, to see how the node was generated, and I found that it was
1518     // created in PhaseIdealLoop::exact_limit and not changed since. It is added to the
1519     // IGVN worklist. I quickly checked when it goes into LoopLimitNode::Ideal after
1520     // that, and it seems we want to skip lowering it until after loop-opts, but never
1521     // add call record_for_post_loop_opts_igvn. This would be an easy fix, but there
1522     // could be other issues too.
1523     //
1524     // Fond with:
1525     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1526     case Op_LoopLimit:
1527       return;
1528 
1529     // PhiNode::Ideal calls split_flow_path, which tries to do this:
1530     // "This optimization tries to find two or more inputs of phi with the same constant
1531     // value. It then splits them into a separate Phi, and according Region."
1532     //
1533     // Example:
1534     //   130  DecodeN  === _ 129
1535     //    50  ConP  === 0  [[ 18 91 99 18 ]]  #null
1536     //    18  Phi  === 14 50 130 50  [[ 133 ]]  #java/lang/Object *  Oop:java/lang/Object *
1537     //
1538     //  turns into:
1539     //
1540     //    50  ConP  === 0  [[ 99 91 18 ]]  #null
1541     //   130  DecodeN  === _ 129  [[ 18 ]]
1542     //    18  Phi  === 14 130 50  [[ 133 ]]  #java/lang/Object *  Oop:java/lang/Object *
1543     //
1544     // We would have to investigate why this optimization does not happen during IGVN.
1545     // There could also be other issues - I did not investigate further yet.
1546     //
1547     // Found with:
1548     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1549     case Op_Phi:
1550       return;
1551 
1552     // MemBarNode::Ideal does "Eliminate volatile MemBars for scalar replaced objects".
1553     // For examle "The allocated object does not escape".
1554     //
1555     // It seems the difference to earlier calls to MemBarNode::Ideal, is that there
1556     // alloc->as_Allocate()->does_not_escape_thread() returned false, but in verification
1557     // it returned true. Why does the MemBarStoreStore not get added to the IGVN
1558     // worklist when this change happens?
1559     //
1560     // Found with:
1561     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1562     case Op_MemBarStoreStore:
1563       return;
1564 
1565     // ConvI2LNode::Ideal converts
1566     //   648  AddI  === _ 583 645  [[ 661 ]]
1567     //   661  ConvI2L  === _ 648  [[ 664 ]]  #long:0..maxint-1:www
1568     // into
1569     //   772  ConvI2L  === _ 645  [[ 773 ]]  #long:-120..maxint-61:www
1570     //   771  ConvI2L  === _ 583  [[ 773 ]]  #long:60..120:www
1571     //   773  AddL  === _ 771 772  [[ ]]
1572     //
1573     // We have to investigate why this does not happen during IGVN in this case.
1574     // There could also be other issues - I did not investigate further yet.
1575     //
1576     // Found with:
1577     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1578     case Op_ConvI2L:
1579       return;
1580 
1581     // AddNode::IdealIL can do this transform (and similar other ones):
1582     //   Convert "a*b+a*c into a*(b+c)
1583     // The example had AddI(MulI(a, b), MulI(a, c)). Why did this not happen
1584     // during IGVN? There was a mutation for one of the MulI, and only
1585     // after that the pattern was as needed for the optimization. The MulI
1586     // was added to the IGVN worklist, but not the AddI. This probably
1587     // can be fixed by adding the correct pattern in add_users_of_use_to_worklist.
1588     //
1589     // Found with:
1590     //   test/hotspot/jtreg/compiler/loopopts/superword/ReductionPerf.java
1591     //   -XX:VerifyIterativeGVN=1110
1592     case Op_AddI:
1593       return;
1594 
1595     // ArrayCopyNode::Ideal
1596     //    calls ArrayCopyNode::prepare_array_copy
1597     //    calls Compile::conv_I2X_index        -> is called with sizetype = intcon(0), I think that
1598     //                                            is not expected, and we create a range int:0..-1
1599     //    calls Compile::constrained_convI2L   -> creates ConvI2L(intcon(1), int:0..-1)
1600     //                                            note: the type is already empty!
1601     //    calls PhaseIterGVN::transform
1602     //    calls PhaseIterGVN::transform_old
1603     //    calls PhaseIterGVN::subsume_node     -> subsume ConvI2L with TOP
1604     //    calls Unique_Node_List::push         -> pushes TOP to worklist
1605     //
1606     // Once we get back to ArrayCopyNode::prepare_array_copy, we get back TOP, and
1607     // return false. This means we eventually return nullptr from ArrayCopyNode::Ideal.
1608     //
1609     // Question: is it ok to push anything to the worklist during ::Ideal, if we will
1610     //           return nullptr, indicating nothing happened?
1611     //           Is it smart to do transform in Compile::constrained_convI2L, and then
1612     //           check for TOP in calls ArrayCopyNode::prepare_array_copy?
1613     //           Should we just allow TOP to land on the worklist, as an exception?
1614     //
1615     // Found with:
1616     //   compiler/arraycopy/TestArrayCopyAsLoadsStores.java
1617     //   -XX:VerifyIterativeGVN=1110
1618     case Op_ArrayCopy:
1619       return;
1620 
1621     // CastLLNode::Ideal
1622     //    calls ConstraintCastNode::optimize_integer_cast -> pushes CastLL through SubL
1623     //
1624     // Could be a notification issue, where updates inputs of CastLL do not notify
1625     // down through SubL to CastLL.
1626     //
1627     // Found With:
1628     //   compiler/c2/TestMergeStoresMemorySegment.java#byte-array
1629     //   -XX:VerifyIterativeGVN=1110
1630     case Op_CastLL:
1631       return;
1632 
1633     // Similar case happens to CastII
1634     //
1635     // Found With:
1636     //   compiler/c2/TestScalarReplacementMaxLiveNodes.java
1637     //   -XX:VerifyIterativeGVN=1110
1638     case Op_CastII:
1639       return;
1640 
1641     // MaxLNode::Ideal
1642     //   calls AddNode::Ideal
1643     //   calls commute -> decides to swap edges
1644     //
1645     // Another notification issue, because we check inputs of inputs?
1646     // MaxL -> Phi -> Loop
1647     // MaxL -> Phi -> MaxL
1648     //
1649     // Found with:
1650     //   compiler/c2/irTests/TestIfMinMax.java
1651     //   -XX:VerifyIterativeGVN=1110
1652     case Op_MaxL:
1653     case Op_MinL:
1654       return;
1655 
1656     // OrINode::Ideal
1657     //   calls AddNode::Ideal
1658     //   calls commute -> left is Load, right not -> commute.
1659     //
1660     // Not sure why notification does not work here, seems like
1661     // the depth is only 1, so it should work. Needs investigation.
1662     //
1663     // Found with:
1664     //   compiler/codegen/TestCharVect2.java#id0
1665     //   -XX:VerifyIterativeGVN=1110
1666     case Op_OrI:
1667     case Op_OrL:
1668       return;
1669 
1670     // Bool -> constant folded to 1.
1671     // Issue with notification?
1672     //
1673     // Found with:
1674     //   compiler/c2/irTests/TestVectorizationMismatchedAccess.java
1675     //   -XX:VerifyIterativeGVN=1110
1676     case Op_Bool:
1677       return;
1678 
1679     // LShiftLNode::Ideal
1680     // Looks at pattern: "(x + x) << c0", converts it to "x << (c0 + 1)"
1681     // Probably a notification issue.
1682     //
1683     // Found with:
1684     //   compiler/conversions/TestMoveConvI2LOrCastIIThruAddIs.java
1685     //   -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1686     case Op_LShiftL:
1687       return;
1688 
1689     // LShiftINode::Ideal
1690     // pattern: ((x + con1) << con2) -> x << con2 + con1 << con2
1691     // Could be issue with notification of inputs of inputs
1692     //
1693     // Side-note: should cases like these not be shared between
1694     //            LShiftI and LShiftL?
1695     //
1696     // Found with:
1697     //   compiler/escapeAnalysis/Test6689060.java
1698     //   -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110 -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1699     case Op_LShiftI:
1700       return;
1701 
1702     // AddPNode::Ideal seems to do set_req without removing lock first.
1703     // Found with various vector tests tier1-tier3.
1704     case Op_AddP:
1705       return;
1706 
1707     // StrIndexOfNode::Ideal
1708     // Found in tier1-3.
1709     case Op_StrIndexOf:
1710     case Op_StrIndexOfChar:
1711       return;
1712 
1713     // StrEqualsNode::Identity
1714     //
1715     // Found (linux x64 only?) with:
1716     //   serviceability/sa/ClhsdbThreadContext.java
1717     //   -XX:+UnlockExperimentalVMOptions -XX:LockingMode=1 -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1718     //   Note: The -XX:LockingMode option is not available anymore.
1719     case Op_StrEquals:
1720       return;
1721 
1722     // AryEqNode::Ideal
1723     // Not investigated. Reshapes itself and adds lots of nodes to the worklist.
1724     //
1725     // Found with:
1726     //   vmTestbase/vm/mlvm/meth/stress/compiler/i2c_c2i/Test.java
1727     //   -XX:+UnlockDiagnosticVMOptions -XX:-TieredCompilation -XX:+StressUnstableIfTraps -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1728     case Op_AryEq:
1729       return;
1730 
1731     // MergeMemNode::Ideal
1732     // Found in tier1-3. Did not investigate further yet.
1733     case Op_MergeMem:
1734       return;
1735 
1736     // CMoveINode::Ideal
1737     // Found in tier1-3. Did not investigate further yet.
1738     case Op_CMoveI:
1739       return;
1740 
1741     // CmpPNode::Ideal calls isa_const_java_mirror
1742     // and generates new constant nodes, even if no progress is made.
1743     // We can probably rewrite this so that only types are generated.
1744     // It seems that object types are not hashed, we could investigate
1745     // if that is an option as well.
1746     //
1747     // Found with:
1748     //   java -XX:VerifyIterativeGVN=1110 -Xcomp --version
1749     case Op_CmpP:
1750       return;
1751 
1752     // MinINode::Ideal
1753     // Did not investigate, but there are some patterns that might
1754     // need more notification.
1755     case Op_MinI:
1756     case Op_MaxI: // preemptively removed it as well.
1757       return;
1758   }
1759 
1760   if (n->is_Load()) {
1761     // LoadNode::Ideal uses tries to find an earlier memory state, and
1762     // checks can_see_stored_value for it.
1763     //
1764     // Investigate why this was not already done during IGVN.
1765     // A similar issue happens with Identity.
1766     //
1767     // There seem to be other cases where loads go up some steps, like
1768     // LoadNode::Ideal going up 10x steps to find dominating load.
1769     //
1770     // Found with:
1771     //   test/hotspot/jtreg/compiler/arraycopy/TestCloneAccess.java
1772     //   -XX:VerifyIterativeGVN=1110
1773     return;
1774   }
1775 
1776   if (n->is_Store()) {
1777     // StoreNode::Ideal can do this:
1778     //  // Capture an unaliased, unconditional, simple store into an initializer.
1779     //  // Or, if it is independent of the allocation, hoist it above the allocation.
1780     // That replaces the Store with a MergeMem.
1781     //
1782     // We have to investigate why this does not happen during IGVN in this case.
1783     // There could also be other issues - I did not investigate further yet.
1784     //
1785     // Found with:
1786     //   java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1787     return;
1788   }
1789 
1790   if (n->is_Vector()) {
1791     // VectorNode::Ideal swaps edges, but only for ops
1792     // that are deemed commutable. But swap_edges
1793     // requires the hash to be invariant when the edges
1794     // are swapped, which is not implemented for these
1795     // vector nodes. This seems not to create any trouble
1796     // usually, but we can also get graphs where in the
1797     // end the nodes are not all commuted, so there is
1798     // definitively an issue here.
1799     //
1800     // Probably we have two options: kill the hash, or
1801     // properly make the hash commutation friendly.
1802     //
1803     // Found with:
1804     //   compiler/vectorapi/TestMaskedMacroLogicVector.java
1805     //   -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110 -XX:+UseParallelGC -XX:+UseNUMA
1806     return;
1807   }
1808 
1809   if (n->is_Region()) {
1810     // LoopNode::Ideal calls RegionNode::Ideal.
1811     // CountedLoopNode::Ideal calls RegionNode::Ideal too.
1812     // But I got an issue because RegionNode::optimize_trichotomy
1813     // then modifies another node, and pushes nodes to the worklist
1814     // Not sure if this is ok, modifying another node like that.
1815     // Maybe it is, then we need to look into what to do with
1816     // the nodes that are now on the worklist, maybe just clear
1817     // them out again. But maybe modifying other nodes like that
1818     // is also bad design. In the end, we return nullptr for
1819     // the current CountedLoop. But the extra nodes on the worklist
1820     // trip the asserts later on.
1821     //
1822     // Found with:
1823     //   compiler/eliminateAutobox/TestShortBoxing.java
1824     //   -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1825     return;
1826   }
1827 
1828   if (n->is_CallJava()) {
1829     // CallStaticJavaNode::Ideal
1830     // Led to a crash:
1831     //   assert((is_CallStaticJava() && cg->is_mh_late_inline()) || (is_CallDynamicJava() && cg->is_virtual_late_inline())) failed: mismatch
1832     //
1833     // Did not investigate yet, could be a bug.
1834     // Or maybe it does not expect to be called during verification.
1835     //
1836     // Found with:
1837     //   test/jdk/jdk/incubator/vector/VectorRuns.java
1838     //   -XX:VerifyIterativeGVN=1110
1839 
1840     // CallDynamicJavaNode::Ideal, and I think also for CallStaticJavaNode::Ideal
1841     //  and possibly their subclasses.
1842     // During late inlining it can call CallJavaNode::register_for_late_inline
1843     // That means we do more rounds of late inlining, but might fail.
1844     // Then we do IGVN again, and register the node again for late inlining.
1845     // This creates an endless cycle. Everytime we try late inlining, we
1846     // are also creating more nodes, especially SafePoint and MergeMem.
1847     // These nodes are immediately rejected when the inlining fails in the
1848     // do_late_inline_check, but they still grow the memory, until we hit
1849     // the MemLimit and crash.
1850     // The assumption here seems that CallDynamicJavaNode::Ideal does not get
1851     // called repeatedly, and eventually we terminate. I fear this is not
1852     // a great assumption to make. We should investigate more.
1853     //
1854     // Found with:
1855     //   compiler/loopopts/superword/TestDependencyOffsets.java#vanilla-U
1856     //   -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1857     return;
1858   }
1859 
1860   // The number of nodes shoud not increase.
1861   uint old_unique = C->unique();
1862   // The hash of a node should not change, this would indicate different inputs
1863   uint old_hash = n->hash();
1864   // Remove 'n' from hash table in case it gets modified. We want to avoid
1865   // hitting the "Need to remove from hash before changing edges" assert if
1866   // a change occurs. Instead, we would like to proceed with the optimization,
1867   // return and finally hit the assert in PhaseIterGVN::verify_optimize to get
1868   // a more meaningful message
1869   _table.hash_delete(n);
1870   Node* i = n->Ideal(this, can_reshape);
1871   // If there was no new Idealization, we are probably happy.
1872   if (i == nullptr) {
1873     if (old_unique < C->unique()) {
1874       stringStream ss; // Print as a block without tty lock.
1875       ss.cr();
1876       ss.print_cr("Ideal optimization did not make progress but created new unused nodes.");
1877       ss.print_cr("  old_unique = %d, unique = %d", old_unique, C->unique());
1878       n->dump_bfs(1, nullptr, "", &ss);
1879       tty->print_cr("%s", ss.as_string());
1880       assert(false, "Unexpected new unused nodes from applying Ideal optimization on %s", n->Name());
1881     }
1882 
1883     if (old_hash != n->hash()) {
1884       stringStream ss; // Print as a block without tty lock.
1885       ss.cr();
1886       ss.print_cr("Ideal optimization did not make progress but node hash changed.");
1887       ss.print_cr("  old_hash = %d, hash = %d", old_hash, n->hash());
1888       n->dump_bfs(1, nullptr, "", &ss);
1889       tty->print_cr("%s", ss.as_string());
1890       assert(false, "Unexpected hash change from applying Ideal optimization on %s", n->Name());
1891     }
1892 
1893     verify_empty_worklist(n);
1894 
1895     // Everything is good.
1896     hash_find_insert(n);
1897     return;
1898   }
1899 
1900   // We just saw a new Idealization which was not done during IGVN.
1901   stringStream ss; // Print as a block without tty lock.
1902   ss.cr();
1903   ss.print_cr("Missed Ideal optimization (can_reshape=%s):", can_reshape ? "true": "false");
1904   if (i == n) {
1905     ss.print_cr("The node was reshaped by Ideal.");
1906   } else {
1907     ss.print_cr("The node was replaced by Ideal.");
1908     ss.print_cr("Old node:");
1909     n->dump_bfs(1, nullptr, "", &ss);
1910   }
1911   ss.print_cr("The result after Ideal:");
1912   i->dump_bfs(1, nullptr, "", &ss);
1913   tty->print_cr("%s", ss.as_string());
1914 
1915   assert(false, "Missed Ideal optimization opportunity in PhaseIterGVN for %s", n->Name());
1916 }
1917 
1918 // Check that all Identity optimizations that could be done were done.
1919 // Asserts if it found missed optimization opportunities, and
1920 //         returns normally otherwise (no missed optimization, or skipped verification).
1921 void PhaseIterGVN::verify_Identity_for(Node* n) {
1922   // First, we check a list of exceptions, where we skip verification,
1923   // because there are known cases where Ideal can optimize after IGVN.
1924   // Some may be expected and cannot be fixed, and others should be fixed.
1925   switch (n->Opcode()) {
1926     // SafePointNode::Identity can remove SafePoints, but wants to wait until
1927     // after loopopts:
1928     //   // Transforming long counted loops requires a safepoint node. Do not
1929     //   // eliminate a safepoint until loop opts are over.
1930     //   if (in(0)->is_Proj() && !phase->C->major_progress()) {
1931     //
1932     // I think the check for major_progress does delay it until after loopopts
1933     // but it does not ensure that the node is on the IGVN worklist after
1934     // loopopts. I think we should try to instead check for
1935     // phase->C->post_loop_opts_phase() and call record_for_post_loop_opts_igvn.
1936     //
1937     // Found with:
1938     //   java -XX:VerifyIterativeGVN=1000 -Xcomp --version
1939     case Op_SafePoint:
1940       return;
1941 
1942     // MergeMemNode::Identity replaces the MergeMem with its base_memory if it
1943     // does not record any other memory splits.
1944     //
1945     // I did not deeply investigate, but it looks like MergeMemNode::Identity
1946     // never got called during IGVN for this node, investigate why.
1947     //
1948     // Found with:
1949     //   java -XX:VerifyIterativeGVN=1000 -Xcomp --version
1950     case Op_MergeMem:
1951       return;
1952 
1953     // ConstraintCastNode::Identity finds casts that are the same, except that
1954     // the control is "higher up", i.e. dominates. The call goes via
1955     // ConstraintCastNode::dominating_cast to PhaseGVN::is_dominator_helper,
1956     // which traverses up to 100 idom steps. If anything gets optimized somewhere
1957     // away from the cast, but within 100 idom steps, the cast may not be
1958     // put on the IGVN worklist any more.
1959     //
1960     // Found with:
1961     //   java -XX:VerifyIterativeGVN=1000 -Xcomp --version
1962     case Op_CastPP:
1963     case Op_CastII:
1964     case Op_CastLL:
1965       return;
1966 
1967     // Same issue for CheckCastPP, uses ConstraintCastNode::Identity and
1968     // checks dominator, which may be changed, but too far up for notification
1969     // to work.
1970     //
1971     // Found with:
1972     //   compiler/c2/irTests/TestSkeletonPredicates.java
1973     //   -XX:VerifyIterativeGVN=1110
1974     case Op_CheckCastPP:
1975       return;
1976 
1977     // In SubNode::Identity, we do:
1978     //   Convert "(X+Y) - Y" into X and "(X+Y) - X" into Y
1979     // In the example, the AddI had an input replaced, the AddI is
1980     // added to the IGVN worklist, but the SubI is one link further
1981     // down and is not added. I checked add_users_of_use_to_worklist
1982     // where I would expect the SubI would be added, and I cannot
1983     // find the pattern, only this one:
1984     //   If changed AddI/SubI inputs, check CmpU for range check optimization.
1985     //
1986     // Fix this "notification" issue and check if there are any other
1987     // issues.
1988     //
1989     // Found with:
1990     //   java -XX:VerifyIterativeGVN=1000 -Xcomp --version
1991     case Op_SubI:
1992     case Op_SubL:
1993       return;
1994 
1995     // PhiNode::Identity checks for patterns like:
1996     //   r = (x != con) ? x : con;
1997     // that can be constant folded to "x".
1998     //
1999     // Call goes through PhiNode::is_cmove_id and CMoveNode::is_cmove_id.
2000     // I suspect there was some earlier change to one of the inputs, but
2001     // not all relevant outputs were put on the IGVN worklist.
2002     //
2003     // Found with:
2004     //   test/hotspot/jtreg/gc/stress/gcbasher/TestGCBasherWithG1.java
2005     //   -XX:VerifyIterativeGVN=1110
2006     case Op_Phi:
2007       return;
2008 
2009     // ConvI2LNode::Identity does
2010     // convert I2L(L2I(x)) => x
2011     //
2012     // Investigate why this did not already happen during IGVN.
2013     //
2014     // Found with:
2015     //   compiler/loopopts/superword/TestDependencyOffsets.java#vanilla-A
2016     //   -XX:VerifyIterativeGVN=1110
2017     case Op_ConvI2L:
2018       return;
2019 
2020     // AbsINode::Identity
2021     // Not investigated yet.
2022     case Op_AbsI:
2023       return;
2024   }
2025 
2026   if (n->is_Load()) {
2027     // LoadNode::Identity tries to look for an earlier store value via
2028     // can_see_stored_value. I found an example where this led to
2029     // an Allocation, where we could assume the value was still zero.
2030     // So the LoadN can be replaced with a zerocon.
2031     //
2032     // Investigate why this was not already done during IGVN.
2033     // A similar issue happens with Ideal.
2034     //
2035     // Found with:
2036     //   java -XX:VerifyIterativeGVN=1000 -Xcomp --version
2037     return;
2038   }
2039 
2040   if (n->is_Store()) {
2041     // StoreNode::Identity
2042     // Not investigated, but found missing optimization for StoreI.
2043     // Looks like a StoreI is replaced with an InitializeNode.
2044     //
2045     // Found with:
2046     //   applications/ctw/modules/java_base_2.java
2047     //   -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -Djava.awt.headless=true -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
2048     return;
2049   }
2050 
2051   if (n->is_Vector()) {
2052     // Found with tier1-3. Not investigated yet.
2053     // The observed issue was with AndVNode::Identity
2054     return;
2055   }
2056 
2057   Node* i = n->Identity(this);
2058   // If we cannot find any other Identity, we are happy.
2059   if (i == n) {
2060     verify_empty_worklist(n);
2061     return;
2062   }
2063 
2064   // The verification just found a new Identity that was not found during IGVN.
2065   stringStream ss; // Print as a block without tty lock.
2066   ss.cr();
2067   ss.print_cr("Missed Identity optimization:");
2068   ss.print_cr("Old node:");
2069   n->dump_bfs(1, nullptr, "", &ss);
2070   ss.print_cr("New node:");
2071   i->dump_bfs(1, nullptr, "", &ss);
2072   tty->print_cr("%s", ss.as_string());
2073 
2074   assert(false, "Missed Identity optimization opportunity in PhaseIterGVN for %s", n->Name());
2075 }
2076 
2077 // Some other verifications that are not specific to a particular transformation.
2078 void PhaseIterGVN::verify_node_invariants_for(const Node* n) {
2079   if (n->is_AddP()) {
2080     if (!n->as_AddP()->address_input_has_same_base()) {
2081       stringStream ss; // Print as a block without tty lock.
2082       ss.cr();
2083       ss.print_cr("Base pointers must match for AddP chain:");
2084       n->dump_bfs(2, nullptr, "", &ss);
2085       tty->print_cr("%s", ss.as_string());
2086 
2087       assert(false, "Broken node invariant for %s", n->Name());
2088     }
2089   }
2090 }
2091 #endif
2092 
2093 /**
2094  * Register a new node with the optimizer.  Update the types array, the def-use
2095  * info.  Put on worklist.
2096  */
2097 Node* PhaseIterGVN::register_new_node_with_optimizer(Node* n, Node* orig) {
2098   set_type_bottom(n);
2099   _worklist.push(n);
2100   if (orig != nullptr)  C->copy_node_notes_to(n, orig);
2101   return n;
2102 }
2103 
2104 //------------------------------transform--------------------------------------
2105 // Non-recursive: idealize Node 'n' with respect to its inputs and its value
2106 Node *PhaseIterGVN::transform( Node *n ) {
2107   if (_delay_transform) {
2108     // Register the node but don't optimize for now
2109     register_new_node_with_optimizer(n);
2110     return n;
2111   }
2112 
2113   // If brand new node, make space in type array, and give it a type.
2114   ensure_type_or_null(n);
2115   if (type_or_null(n) == nullptr) {
2116     set_type_bottom(n);
2117   }
2118 






2119   return transform_old(n);
2120 }
2121 
2122 Node *PhaseIterGVN::transform_old(Node* n) {
2123   NOT_PRODUCT(set_transforms());
2124   // Remove 'n' from hash table in case it gets modified
2125   _table.hash_delete(n);
2126 #ifdef ASSERT
2127   if (is_verify_def_use()) {
2128     assert(!_table.find_index(n->_idx), "found duplicate entry in table");
2129   }
2130 #endif
2131 
2132   // Allow Bool -> Cmp idealisation in late inlining intrinsics that return a bool
2133   if (n->is_Cmp()) {
2134     add_users_to_worklist(n);
2135   }
2136 
2137   // Apply the Ideal call in a loop until it no longer applies
2138   Node* k = n;
2139   DEBUG_ONLY(dead_loop_check(k);)
2140   DEBUG_ONLY(bool is_new = (k->outcnt() == 0);)
2141   C->remove_modified_node(k);
2142 #ifndef PRODUCT
2143   uint hash_before = is_verify_Ideal_return() ? k->hash() : 0;
2144 #endif
2145   Node* i = apply_ideal(k, /*can_reshape=*/true);
2146   assert(i != k || is_new || i->outcnt() > 0, "don't return dead nodes");
2147 #ifndef PRODUCT
2148   if (is_verify_Ideal_return()) {
2149     assert(k->outcnt() == 0 || i != nullptr || hash_before == k->hash(), "hash changed after Ideal returned nullptr for %s", k->Name());
2150   }
2151   verify_step(k);
2152 #endif
2153 
2154   DEBUG_ONLY(uint loop_count = 1;)
2155   while (i != nullptr) {
2156 #ifdef ASSERT
2157     if (loop_count >= K + C->live_nodes()) {
2158       dump_infinite_loop_info(i, "PhaseIterGVN::transform_old");
2159     }
2160 #endif
2161     assert((i->_idx >= k->_idx) || i->is_top(), "Idealize should return new nodes, use Identity to return old nodes");
2162     // Made a change; put users of original Node on worklist
2163     add_users_to_worklist(k);
2164     // Replacing root of transform tree?
2165     if (k != i) {
2166       // Make users of old Node now use new.
2167       subsume_node(k, i);
2168       k = i;
2169     }
2170     DEBUG_ONLY(dead_loop_check(k);)
2171     // Try idealizing again
2172     DEBUG_ONLY(is_new = (k->outcnt() == 0);)
2173     C->remove_modified_node(k);
2174 #ifndef PRODUCT
2175     uint hash_before = is_verify_Ideal_return() ? k->hash() : 0;
2176 #endif
2177     i = apply_ideal(k, /*can_reshape=*/true);
2178     assert(i != k || is_new || (i->outcnt() > 0), "don't return dead nodes");
2179 #ifndef PRODUCT
2180     if (is_verify_Ideal_return()) {
2181       assert(k->outcnt() == 0 || i != nullptr || hash_before == k->hash(), "hash changed after Ideal returned nullptr for %s", k->Name());
2182     }
2183     verify_step(k);
2184 #endif
2185     DEBUG_ONLY(loop_count++;)
2186   }
2187 
2188   // If brand new node, make space in type array.
2189   ensure_type_or_null(k);
2190 
2191   // See what kind of values 'k' takes on at runtime
2192   const Type* t = k->Value(this);
2193   assert(t != nullptr, "value sanity");
2194 
2195   // Since I just called 'Value' to compute the set of run-time values
2196   // for this Node, and 'Value' is non-local (and therefore expensive) I'll
2197   // cache Value.  Later requests for the local phase->type of this Node can
2198   // use the cached Value instead of suffering with 'bottom_type'.
2199   if (type_or_null(k) != t) {
2200 #ifndef PRODUCT
2201     inc_new_values();
2202     set_progress();
2203 #endif
2204     set_type(k, t);
2205     // If k is a TypeNode, capture any more-precise type permanently into Node
2206     k->raise_bottom_type(t);
2207     // Move users of node to worklist
2208     add_users_to_worklist(k);
2209   }
2210   // If 'k' computes a constant, replace it with a constant
2211   if (t->singleton() && !k->is_Con()) {
2212     NOT_PRODUCT(set_progress();)
2213     Node* con = makecon(t);     // Make a constant
2214     add_users_to_worklist(k);
2215     subsume_node(k, con);       // Everybody using k now uses con
2216     return con;
2217   }
2218 
2219   // Now check for Identities
2220   i = k->Identity(this);      // Look for a nearby replacement
2221   if (i != k) {                // Found? Return replacement!
2222     NOT_PRODUCT(set_progress();)
2223     add_users_to_worklist(k);
2224     subsume_node(k, i);       // Everybody using k now uses i
2225     return i;
2226   }
2227 
2228   // Global Value Numbering
2229   i = hash_find_insert(k);      // Check for pre-existing node
2230   if (i && (i != k)) {
2231     // Return the pre-existing node if it isn't dead
2232     NOT_PRODUCT(set_progress();)
2233     add_users_to_worklist(k);
2234     subsume_node(k, i);       // Everybody using k now uses i
2235     return i;
2236   }
2237 
2238   // Return Idealized original
2239   return k;
2240 }
2241 
2242 //---------------------------------saturate------------------------------------
2243 const Type* PhaseIterGVN::saturate(const Type* new_type, const Type* old_type,
2244                                    const Type* limit_type) const {
2245   return new_type->narrow(old_type);
2246 }
2247 
2248 //------------------------------remove_globally_dead_node----------------------
2249 // Kill a globally dead Node.  All uses are also globally dead and are
2250 // aggressively trimmed.
2251 void PhaseIterGVN::remove_globally_dead_node( Node *dead ) {
2252   enum DeleteProgress {
2253     PROCESS_INPUTS,
2254     PROCESS_OUTPUTS
2255   };
2256   ResourceMark rm;
2257   Node_Stack stack(32);
2258   stack.push(dead, PROCESS_INPUTS);
2259 
2260   while (stack.is_nonempty()) {
2261     dead = stack.node();
2262     if (dead->Opcode() == Op_SafePoint) {
2263       dead->as_SafePoint()->disconnect_from_root(this);
2264     }
2265     uint progress_state = stack.index();
2266     assert(dead != C->root(), "killing root, eh?");
2267     assert(!dead->is_top(), "add check for top when pushing");
2268     NOT_PRODUCT( set_progress(); )
2269     if (progress_state == PROCESS_INPUTS) {
2270       // After following inputs, continue to outputs
2271       stack.set_index(PROCESS_OUTPUTS);
2272       if (!dead->is_Con()) { // Don't kill cons but uses
2273         bool recurse = false;
2274         // Remove from hash table
2275         _table.hash_delete( dead );
2276         // Smash all inputs to 'dead', isolating him completely
2277         for (uint i = 0; i < dead->req(); i++) {
2278           Node *in = dead->in(i);
2279           if (in != nullptr && in != C->top()) {  // Points to something?
2280             int nrep = dead->replace_edge(in, nullptr, this);  // Kill edges
2281             assert((nrep > 0), "sanity");
2282             if (in->outcnt() == 0) { // Made input go dead?
2283               stack.push(in, PROCESS_INPUTS); // Recursively remove
2284               recurse = true;
2285             } else if (in->outcnt() == 1 &&
2286                        in->has_special_unique_user()) {
2287               _worklist.push(in->unique_out());
2288             } else if (in->outcnt() <= 2 && dead->is_Phi()) {
2289               if (in->Opcode() == Op_Region) {
2290                 _worklist.push(in);
2291               } else if (in->is_Store()) {
2292                 DUIterator_Fast imax, i = in->fast_outs(imax);
2293                 _worklist.push(in->fast_out(i));
2294                 i++;
2295                 if (in->outcnt() == 2) {
2296                   _worklist.push(in->fast_out(i));
2297                   i++;
2298                 }
2299                 assert(!(i < imax), "sanity");
2300               }
2301             } else if (dead->is_data_proj_of_pure_function(in)) {
2302               _worklist.push(in);
2303             } else {
2304               BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(this, in);
2305             }
2306             if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory &&
2307                 in->is_Proj() && in->in(0) != nullptr && in->in(0)->is_Initialize()) {
2308               // A Load that directly follows an InitializeNode is
2309               // going away. The Stores that follow are candidates
2310               // again to be captured by the InitializeNode.
2311               add_users_to_worklist_if(_worklist, in, [](Node* n) { return n->is_Store(); });
2312             }
2313           } // if (in != nullptr && in != C->top())
2314         } // for (uint i = 0; i < dead->req(); i++)
2315         if (recurse) {
2316           continue;
2317         }
2318       } // if (!dead->is_Con())
2319     } // if (progress_state == PROCESS_INPUTS)
2320 
2321     // Aggressively kill globally dead uses
2322     // (Rather than pushing all the outs at once, we push one at a time,
2323     // plus the parent to resume later, because of the indefinite number
2324     // of edge deletions per loop trip.)
2325     if (dead->outcnt() > 0) {
2326       // Recursively remove output edges
2327       stack.push(dead->raw_out(0), PROCESS_INPUTS);
2328     } else {
2329       // Finished disconnecting all input and output edges.
2330       stack.pop();
2331       // Remove dead node from iterative worklist
2332       _worklist.remove(dead);
2333       C->remove_useless_node(dead);
2334     }
2335   } // while (stack.is_nonempty())
2336 }
2337 
2338 //------------------------------subsume_node-----------------------------------
2339 // Remove users from node 'old' and add them to node 'nn'.
2340 void PhaseIterGVN::subsume_node( Node *old, Node *nn ) {
2341   if (old->Opcode() == Op_SafePoint) {
2342     old->as_SafePoint()->disconnect_from_root(this);
2343   }
2344   assert( old != hash_find(old), "should already been removed" );
2345   assert( old != C->top(), "cannot subsume top node");
2346   // Copy debug or profile information to the new version:
2347   C->copy_node_notes_to(nn, old);
2348   // Move users of node 'old' to node 'nn'
2349   for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
2350     Node* use = old->last_out(i);  // for each use...
2351     // use might need re-hashing (but it won't if it's a new node)
2352     rehash_node_delayed(use);
2353     // Update use-def info as well
2354     // We remove all occurrences of old within use->in,
2355     // so as to avoid rehashing any node more than once.
2356     // The hash table probe swamps any outer loop overhead.
2357     uint num_edges = 0;
2358     for (uint jmax = use->len(), j = 0; j < jmax; j++) {
2359       if (use->in(j) == old) {
2360         use->set_req(j, nn);
2361         ++num_edges;
2362       }
2363     }
2364     i -= num_edges;    // we deleted 1 or more copies of this edge
2365   }
2366 
2367   // Search for instance field data PhiNodes in the same region pointing to the old
2368   // memory PhiNode and update their instance memory ids to point to the new node.
2369   if (old->is_Phi() && old->as_Phi()->type()->has_memory() && old->in(0) != nullptr) {
2370     Node* region = old->in(0);
2371     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2372       PhiNode* phi = region->fast_out(i)->isa_Phi();
2373       if (phi != nullptr && phi->inst_mem_id() == (int)old->_idx) {
2374         phi->set_inst_mem_id((int)nn->_idx);
2375       }
2376     }
2377   }
2378 
2379   // Smash all inputs to 'old', isolating him completely
2380   Node *temp = new Node(1);
2381   temp->init_req(0,nn);     // Add a use to nn to prevent him from dying
2382   remove_dead_node( old );
2383   temp->del_req(0);         // Yank bogus edge
2384   if (nn != nullptr && nn->outcnt() == 0) {
2385     _worklist.push(nn);
2386   }
2387 #ifndef PRODUCT
2388   if (is_verify_def_use()) {
2389     for ( int i = 0; i < _verify_window_size; i++ ) {
2390       if ( _verify_window[i] == old )
2391         _verify_window[i] = nn;
2392     }
2393   }
2394 #endif
2395   temp->destruct(this);     // reuse the _idx of this little guy
2396 }
2397 













2398 //------------------------------add_users_to_worklist--------------------------
2399 void PhaseIterGVN::add_users_to_worklist0(Node* n, Unique_Node_List& worklist) {
2400   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2401     worklist.push(n->fast_out(i));  // Push on worklist
2402   }
2403 }
2404 
2405 // Return counted loop Phi if as a counted loop exit condition, cmp
2406 // compares the induction variable with n
2407 static PhiNode* countedloop_phi_from_cmp(CmpNode* cmp, Node* n) {
2408   for (DUIterator_Fast imax, i = cmp->fast_outs(imax); i < imax; i++) {
2409     Node* bol = cmp->fast_out(i);
2410     for (DUIterator_Fast i2max, i2 = bol->fast_outs(i2max); i2 < i2max; i2++) {
2411       Node* iff = bol->fast_out(i2);
2412       if (iff->is_BaseCountedLoopEnd()) {
2413         BaseCountedLoopEndNode* cle = iff->as_BaseCountedLoopEnd();
2414         if (cle->limit() == n) {
2415           PhiNode* phi = cle->phi();
2416           if (phi != nullptr) {
2417             return phi;
2418           }
2419         }
2420       }
2421     }
2422   }
2423   return nullptr;
2424 }
2425 
2426 void PhaseIterGVN::add_users_to_worklist(Node *n) {
2427   add_users_to_worklist0(n, _worklist);
2428 
2429   Unique_Node_List& worklist = _worklist;
2430   // Move users of node to worklist
2431   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2432     Node* use = n->fast_out(i); // Get use
2433     add_users_of_use_to_worklist(n, use, worklist);
2434   }
2435 }
2436 
2437 void PhaseIterGVN::add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_List& worklist) {
2438   if(use->is_Multi() ||      // Multi-definer?  Push projs on worklist
2439       use->is_Store() )       // Enable store/load same address
2440     add_users_to_worklist0(use, worklist);
2441 
2442   // If we changed the receiver type to a call, we need to revisit
2443   // the Catch following the call.  It's looking for a non-null
2444   // receiver to know when to enable the regular fall-through path
2445   // in addition to the NullPtrException path.
2446   if (use->is_CallDynamicJava() && n == use->in(TypeFunc::Parms)) {
2447     Node* p = use->as_CallDynamicJava()->proj_out_or_null(TypeFunc::Control);
2448     if (p != nullptr) {
2449       add_users_to_worklist0(p, worklist);
2450     }
2451   }
2452 










2453   uint use_op = use->Opcode();
2454   if(use->is_Cmp()) {       // Enable CMP/BOOL optimization
2455     add_users_to_worklist0(use, worklist); // Put Bool on worklist
2456     if (use->outcnt() > 0) {
2457       Node* bol = use->raw_out(0);
2458       if (bol->outcnt() > 0) {
2459         Node* iff = bol->raw_out(0);
2460         if (iff->outcnt() == 2) {
2461           // Look for the 'is_x2logic' pattern: "x ? : 0 : 1" and put the
2462           // phi merging either 0 or 1 onto the worklist
2463           Node* ifproj0 = iff->raw_out(0);
2464           Node* ifproj1 = iff->raw_out(1);
2465           if (ifproj0->outcnt() > 0 && ifproj1->outcnt() > 0) {
2466             Node* region0 = ifproj0->raw_out(0);
2467             Node* region1 = ifproj1->raw_out(0);
2468             if( region0 == region1 )
2469               add_users_to_worklist0(region0, worklist);
2470           }
2471         }
2472       }
2473     }
2474     if (use_op == Op_CmpI || use_op == Op_CmpL) {
2475       Node* phi = countedloop_phi_from_cmp(use->as_Cmp(), n);
2476       if (phi != nullptr) {
2477         // Input to the cmp of a loop exit check has changed, thus
2478         // the loop limit may have changed, which can then change the
2479         // range values of the trip-count Phi.
2480         worklist.push(phi);
2481       }
2482     }
2483     if (use_op == Op_CmpI) {
2484       Node* cmp = use;
2485       Node* in1 = cmp->in(1);
2486       Node* in2 = cmp->in(2);
2487       // Notify CmpI / If pattern from CastIINode::Value (left pattern).
2488       // Must also notify if in1 is modified and possibly turns into X (right pattern).
2489       //
2490       // in1  in2                   in1  in2
2491       //  |    |                     |    |
2492       //  +--- | --+                 |    |
2493       //  |    |   |                 |    |
2494       // CmpINode  |                CmpINode
2495       //    |      |                   |
2496       // BoolNode  |                BoolNode
2497       //    |      |        OR         |
2498       //  IfNode   |                 IfNode
2499       //    |      |                   |
2500       //  IfProj   |                 IfProj   X
2501       //    |      |                   |      |
2502       //   CastIINode                 CastIINode
2503       //
2504       if (in1 != in2) { // if they are equal, the CmpI can fold them away
2505         if (in1 == n) {
2506           // in1 modified -> could turn into X -> do traversal based on right pattern.
2507           for (DUIterator_Fast i2max, i2 = cmp->fast_outs(i2max); i2 < i2max; i2++) {
2508             Node* bol = cmp->fast_out(i2); // For each Bool
2509             if (bol->is_Bool()) {
2510               for (DUIterator_Fast i3max, i3 = bol->fast_outs(i3max); i3 < i3max; i3++) {
2511                 Node* iff = bol->fast_out(i3); // For each If
2512                 if (iff->is_If()) {
2513                   for (DUIterator_Fast i4max, i4 = iff->fast_outs(i4max); i4 < i4max; i4++) {
2514                     Node* if_proj = iff->fast_out(i4); // For each IfProj
2515                     assert(if_proj->is_IfProj(), "If only has IfTrue and IfFalse as outputs");
2516                     for (DUIterator_Fast i5max, i5 = if_proj->fast_outs(i5max); i5 < i5max; i5++) {
2517                       Node* castii = if_proj->fast_out(i5); // For each CastII
2518                       if (castii->is_CastII() &&
2519                           castii->as_CastII()->carry_dependency()) {
2520                         worklist.push(castii);
2521                       }
2522                     }
2523                   }
2524                 }
2525               }
2526             }
2527           }
2528         } else {
2529           // Only in2 modified -> can assume X == in2 (left pattern).
2530           assert(n == in2, "only in2 modified");
2531           // Find all CastII with input in1.
2532           for (DUIterator_Fast jmax, j = in1->fast_outs(jmax); j < jmax; j++) {
2533             Node* castii = in1->fast_out(j);
2534             if (castii->is_CastII() && castii->as_CastII()->carry_dependency()) {
2535               // Find If.
2536               if (castii->in(0) != nullptr && castii->in(0)->in(0) != nullptr && castii->in(0)->in(0)->is_If()) {
2537                 Node* ifnode = castii->in(0)->in(0);
2538                 // Check that if connects to the cmp
2539                 if (ifnode->in(1) != nullptr && ifnode->in(1)->is_Bool() && ifnode->in(1)->in(1) == cmp) {
2540                   worklist.push(castii);
2541                 }
2542               }
2543             }
2544           }
2545         }
2546       }
2547     }
2548   }
2549 











2550   // If changed Cast input, notify down for Phi, Sub, and Xor - all do "uncast"
2551   // Patterns:
2552   // ConstraintCast+ -> Sub
2553   // ConstraintCast+ -> Phi
2554   // ConstraintCast+ -> Xor
2555   if (use->is_ConstraintCast()) {
2556     auto push_the_uses_to_worklist = [&](Node* n){
2557       if (n->is_Phi() || n->is_Sub() || n->Opcode() == Op_XorI || n->Opcode() == Op_XorL) {
2558         worklist.push(n);
2559       }
2560     };
2561     auto is_boundary = [](Node* n){ return !n->is_ConstraintCast(); };
2562     use->visit_uses(push_the_uses_to_worklist, is_boundary);
2563   }
2564   // If changed LShift inputs, check RShift/URShift users for
2565   // "(X << C) >> C" sign-ext and "(X << C) >>> C" zero-ext optimizations.
2566   if (use_op == Op_LShiftI || use_op == Op_LShiftL) {
2567     add_users_to_worklist_if(worklist, use, [](Node* u) {
2568       return u->Opcode() == Op_RShiftI || u->Opcode() == Op_RShiftL ||
2569              u->Opcode() == Op_URShiftI || u->Opcode() == Op_URShiftL;
2570     });
2571   }
2572   // If changed LShift inputs, check And users for shift and mask (And) operation
2573   if (use_op == Op_LShiftI || use_op == Op_LShiftL) {
2574     add_users_to_worklist_if(worklist, use, [](Node* u) {
2575       return u->Opcode() == Op_AndI || u->Opcode() == Op_AndL;
2576     });
2577   }
2578   // If changed AddI/SubI inputs, check CmpU for range check optimization.
2579   if (use_op == Op_AddI || use_op == Op_SubI) {
2580     add_users_to_worklist_if(worklist, use, [](Node* u) {
2581       return u->Opcode() == Op_CmpU;
2582     });
2583   }
2584   // If changed AndI/AndL inputs, check RShift/URShift users for "(x & mask) >> shift" optimization opportunity
2585   if (use_op == Op_AndI || use_op == Op_AndL) {
2586     add_users_to_worklist_if(worklist, use, [](Node* u) {
2587       return u->Opcode() == Op_RShiftI || u->Opcode() == Op_RShiftL ||
2588              u->Opcode() == Op_URShiftI || u->Opcode() == Op_URShiftL;
2589     });
2590   }
2591   // Check for redundant conversion patterns:
2592   // ConvD2L->ConvL2D->ConvD2L
2593   // ConvF2I->ConvI2F->ConvF2I
2594   // ConvF2L->ConvL2F->ConvF2L
2595   // ConvI2F->ConvF2I->ConvI2F
2596   // Note: there may be other 3-nodes conversion chains that would require to be added here, but these
2597   // are the only ones that are known to trigger missed optimizations otherwise
2598   if (use_op == Op_ConvL2D ||
2599       use_op == Op_ConvI2F ||
2600       use_op == Op_ConvL2F ||
2601       use_op == Op_ConvF2I) {
2602     add_users_to_worklist_if(worklist, use, [=](Node* u) {
2603       return (use_op == Op_ConvL2D && u->Opcode() == Op_ConvD2L) ||
2604              (use_op == Op_ConvI2F && u->Opcode() == Op_ConvF2I) ||
2605              (use_op == Op_ConvL2F && u->Opcode() == Op_ConvF2L) ||
2606              (use_op == Op_ConvF2I && u->Opcode() == Op_ConvI2F);
2607     });
2608   }
2609   // ConvD2F::Ideal matches ConvD2F(SqrtD(ConvF2D(x))) => SqrtF(x).
2610   // Notify ConvD2F users of SqrtD when any input of the SqrtD changes.
2611   if (use_op == Op_SqrtD) {
2612     add_users_to_worklist_if(worklist, use, [](Node* u) { return u->Opcode() == Op_ConvD2F; });
2613   }
2614   // ConvF2HF::Ideal matches ConvF2HF(binopF(ConvHF2F(...))) => FP16BinOp(...).
2615   // Notify ConvF2HF users of float binary ops when any input changes.
2616   if (Float16NodeFactory::is_float32_binary_oper(use_op)) {
2617     add_users_to_worklist_if(worklist, use, [](Node* u) { return u->Opcode() == Op_ConvF2HF; });
2618   }
2619   // If changed AddP inputs:
2620   // - check Stores for loop invariant, and
2621   // - if the changed input is the offset, check constant-offset AddP users for
2622   //   address expression flattening.
2623   if (use_op == Op_AddP) {
2624     bool offset_changed = n == use->in(AddPNode::Offset);
2625     add_users_to_worklist_if(worklist, use, [=](Node* u) {
2626       return u->is_Mem() ||
2627              (offset_changed && u->is_AddP() && u->in(AddPNode::Offset)->is_Con());
2628     });
2629   }
2630   // Check for "abs(0-x)" into "abs(x)" conversion
2631   if (use->is_Sub()) {
2632     add_users_to_worklist_if(worklist, use, [](Node* u) {
2633       return u->Opcode() == Op_AbsD || u->Opcode() == Op_AbsF ||
2634              u->Opcode() == Op_AbsL || u->Opcode() == Op_AbsI;
2635     });
2636   }
2637   // Check for Max/Min(A, Max/Min(B, C)) where A == B or A == C
2638   if (use->is_MinMax()) {
2639     add_users_to_worklist_if(worklist, use, [](Node* u) { return u->is_MinMax(); });
2640   }
2641   auto enqueue_init_mem_projs = [&](ProjNode* proj) {
2642     add_users_to_worklist0(proj, worklist);
2643   };
2644   // If changed initialization activity, check dependent Stores
2645   if (use_op == Op_Allocate || use_op == Op_AllocateArray) {
2646     InitializeNode* init = use->as_Allocate()->initialization();
2647     if (init != nullptr) {
2648       init->for_each_proj(enqueue_init_mem_projs, TypeFunc::Memory);
2649     }
2650   }
2651   // If the ValidLengthTest input changes then the fallthrough path out of the AllocateArray may have become dead.
2652   // CatchNode::Value() is responsible for killing that path. The CatchNode has to be explicitly enqueued for igvn
2653   // to guarantee the change is not missed.
2654   if (use_op == Op_AllocateArray && n == use->in(AllocateNode::ValidLengthTest)) {
2655     Node* p = use->as_AllocateArray()->proj_out_or_null(TypeFunc::Control);
2656     if (p != nullptr) {
2657       add_users_to_worklist0(p, worklist);
2658     }
2659   }
2660 
2661   if (use_op == Op_Initialize) {
2662     InitializeNode* init = use->as_Initialize();
2663     init->for_each_proj(enqueue_init_mem_projs, TypeFunc::Memory);
2664   }
2665   // Loading the java mirror from a Klass requires two loads and the type
2666   // of the mirror load depends on the type of 'n'. See LoadNode::Value().
2667   //   LoadBarrier?(LoadP(LoadP(AddP(foo:Klass, #java_mirror))))
2668   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2669   bool has_load_barrier_nodes = bs->has_load_barrier_nodes();
2670 


















2671   if (use_op == Op_LoadP && use->bottom_type()->isa_rawptr()) {
2672     for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2673       Node* u = use->fast_out(i2);
2674       const Type* ut = u->bottom_type();
2675       if (u->Opcode() == Op_LoadP && ut->isa_instptr()) {
2676         if (has_load_barrier_nodes) {
2677           // Search for load barriers behind the load
2678           add_users_to_worklist_if(worklist, u, [&](Node* b) {
2679             return bs->is_gc_barrier_node(b);
2680           });
2681         }
2682         worklist.push(u);
2683       }
2684     }
2685   }










2686   if (use->Opcode() == Op_OpaqueZeroTripGuard) {
2687     assert(use->outcnt() <= 1, "OpaqueZeroTripGuard can't be shared");
2688     if (use->outcnt() == 1) {
2689       Node* cmp = use->unique_out();
2690       worklist.push(cmp);
2691     }
2692   }
2693   // VectorMaskToLongNode::Ideal_MaskAll looks through VectorStoreMask
2694   // to fold constant masks.
2695   if (use_op == Op_VectorStoreMask) {
2696     add_users_to_worklist_if(worklist, use, [](Node* u) { return u->Opcode() == Op_VectorMaskToLong; });
2697   }
2698 
2699   // From CastX2PNode::Ideal
2700   // CastX2P(AddX(x, y))
2701   // CastX2P(SubX(x, y))
2702   if (use->Opcode() == Op_AddX || use->Opcode() == Op_SubX) {
2703     add_users_to_worklist_if(worklist, use, [](Node* u) { return u->Opcode() == Op_CastX2P; });
2704   }
2705 
2706   /* AndNode has a special handling when one of the operands is a LShiftNode:
2707    * (LHS << s) & RHS
2708    * if RHS fits in less than s bits, the value of this expression is 0.
2709    * The difficulty is that there might be a conversion node (ConvI2L) between
2710    * the LShiftINode and the AndLNode, like so:
2711    * AndLNode(ConvI2L(LShiftI(LHS, s)), RHS)
2712    * This case is handled by And[IL]Node::Value(PhaseGVN*)
2713    * (see `AndIL_min_trailing_zeros`).
2714    *
2715    * But, when the shift is updated during IGVN, pushing the user (ConvI2L)
2716    * is not enough: there might be no update happening there. We need to
2717    * directly push the And[IL]Node on the worklist, jumping over ConvI2L.
2718    *
2719    * Moreover we can have ConstraintCasts in between. It may look like
2720    * ConstraintCast+ -> ConvI2L -> ConstraintCast+ -> And
2721    * and And[IL]Node::Value(PhaseGVN*) still handles that by looking through casts.
2722    * So we must deal with that as well.
2723    */
2724   if (use->is_ConstraintCast() || use_op == Op_ConvI2L) {
2725     auto is_boundary = [](Node* n){ return !n->is_ConstraintCast() && n->Opcode() != Op_ConvI2L; };
2726     auto push_and_to_worklist = [&worklist](Node* n){
2727       if (n->Opcode() == Op_AndL || n->Opcode() == Op_AndI) {
2728         worklist.push(n);
2729       }
2730     };
2731     use->visit_uses(push_and_to_worklist, is_boundary);
2732   }
2733 
2734   // If changed Sub inputs, check Add for identity.
2735   // e.g., (x - y) + y -> x; x + (y - x) -> y.
2736   if (use_op == Op_SubI || use_op == Op_SubL) {
2737     const int add_op = (use_op == Op_SubI) ? Op_AddI : Op_AddL;
2738     add_users_to_worklist_if(worklist, use, [=](Node* u) { return u->Opcode() == add_op; });
2739   }
2740 }
2741 
2742 /**
2743  * Remove the speculative part of all types that we know of
2744  */
2745 void PhaseIterGVN::remove_speculative_types()  {
2746   assert(UseTypeSpeculation, "speculation is off");
2747   for (uint i = 0; i < _types.Size(); i++)  {
2748     const Type* t = _types.fast_lookup(i);
2749     if (t != nullptr) {
2750       _types.map(i, t->remove_speculative());
2751     }
2752   }
2753   _table.check_no_speculative_types();
2754 }
2755 
2756 //=============================================================================
2757 #ifndef PRODUCT
2758 uint PhaseCCP::_total_invokes   = 0;
2759 uint PhaseCCP::_total_constants = 0;
2760 #endif
2761 //------------------------------PhaseCCP---------------------------------------
2762 // Conditional Constant Propagation, ala Wegman & Zadeck
2763 PhaseCCP::PhaseCCP( PhaseIterGVN *igvn ) : PhaseIterGVN(igvn) {
2764   NOT_PRODUCT( clear_constants(); )
2765   assert( _worklist.size() == 0, "" );
2766   _phase = PhaseValuesType::ccp;
2767   analyze();
2768 }
2769 
2770 #ifndef PRODUCT
2771 //------------------------------~PhaseCCP--------------------------------------
2772 PhaseCCP::~PhaseCCP() {
2773   inc_invokes();
2774   _total_constants += count_constants();
2775 }
2776 #endif
2777 
2778 
2779 #ifdef ASSERT
2780 void PhaseCCP::verify_type(Node* n, const Type* tnew, const Type* told) {
2781   if (tnew->meet(told) != tnew->remove_speculative()) {
2782     n->dump(1);
2783     tty->print("told = "); told->dump(); tty->cr();
2784     tty->print("tnew = "); tnew->dump(); tty->cr();
2785     fatal("Not monotonic");
2786   }
2787   assert(!told->isa_int() || !tnew->isa_int() || told->is_int()->_widen <= tnew->is_int()->_widen, "widen increases");
2788   assert(!told->isa_long() || !tnew->isa_long() || told->is_long()->_widen <= tnew->is_long()->_widen, "widen increases");
2789 }
2790 #endif //ASSERT
2791 
2792 // In this analysis, all types are initially set to TOP. We iteratively call Value() on all nodes of the graph until
2793 // we reach a fixed-point (i.e. no types change anymore). We start with a list that only contains the root node. Each time
2794 // a new type is set, we push all uses of that node back to the worklist (in some cases, we also push grandchildren
2795 // or nodes even further down back to the worklist because their type could change as a result of the current type
2796 // change).
2797 void PhaseCCP::analyze() {
2798   // Initialize all types to TOP, optimistic analysis
2799   for (uint i = 0; i < C->unique(); i++)  {
2800     _types.map(i, Type::TOP);
2801   }
2802 
2803   // CCP worklist is placed on a local arena, so that we can allow ResourceMarks on "Compile::current()->resource_arena()".
2804   // We also do not want to put the worklist on "Compile::current()->comp_arena()", as that one only gets de-allocated after
2805   // Compile is over. The local arena gets de-allocated at the end of its scope.
2806   ResourceArea local_arena(mtCompiler);
2807   Unique_Node_List worklist(&local_arena);
2808   Unique_Node_List worklist_revisit(&local_arena);
2809   DEBUG_ONLY(Unique_Node_List worklist_verify(&local_arena);)
2810 
2811   // Push root onto worklist
2812   worklist.push(C->root());
2813 
2814   assert(_root_and_safepoints.size() == 0, "must be empty (unused)");
2815   _root_and_safepoints.push(C->root());
2816 
2817   // This is the meat of CCP: pull from worklist; compute new value; push changes out.
2818 
2819   // Do the first round. Since all initial types are TOP, this will visit all alive nodes.
2820   while (worklist.size() != 0) {
2821     Node* n = fetch_next_node(worklist);
2822     DEBUG_ONLY(worklist_verify.push(n);)
2823     if (needs_revisit(n)) {
2824       worklist_revisit.push(n);
2825     }
2826     if (n->is_SafePoint()) {
2827       // Make sure safepoints are processed by PhaseCCP::transform even if they are
2828       // not reachable from the bottom. Otherwise, infinite loops would be removed.
2829       _root_and_safepoints.push(n);
2830     }
2831     analyze_step(worklist, n);
2832   }
2833 
2834   // More rounds to catch updates far in the graph.
2835   // Revisit nodes that might be able to refine their types at the end of the round.
2836   // If so, process these nodes. If there is remaining work, start another round.
2837   do {
2838     while (worklist.size() != 0) {
2839       Node* n = fetch_next_node(worklist);
2840       analyze_step(worklist, n);
2841     }
2842     for (uint t = 0; t < worklist_revisit.size(); t++) {
2843       Node* n = worklist_revisit.at(t);
2844       analyze_step(worklist, n);
2845     }
2846   } while (worklist.size() != 0);
2847 
2848   DEBUG_ONLY(verify_analyze(worklist_verify);)
2849 }
2850 
2851 void PhaseCCP::analyze_step(Unique_Node_List& worklist, Node* n) {
2852   const Type* new_type = n->Value(this);
2853   if (new_type != type(n)) {
2854     DEBUG_ONLY(verify_type(n, new_type, type(n));)
2855     dump_type_and_node(n, new_type);
2856     set_type(n, new_type);
2857     push_child_nodes_to_worklist(worklist, n);
2858   }
2859   if (KillPathsReachableByDeadTypeNode && n->is_Type() && new_type == Type::TOP) {
2860     // Keep track of Type nodes to kill CFG paths that use Type
2861     // nodes that become dead.
2862     _maybe_top_type_nodes.push(n);
2863   }
2864 }
2865 
2866 // Some nodes can refine their types due to type change somewhere deep
2867 // in the graph. We will need to revisit them before claiming convergence.
2868 // Add nodes here if particular *Node::Value is doing deep graph traversals
2869 // not handled by PhaseCCP::push_more_uses().
2870 bool PhaseCCP::needs_revisit(Node* n) const {
2871   // LoadNode performs deep traversals. Load is not notified for changes far away.
2872   if (n->is_Load()) {
2873     return true;
2874   }
2875   // CmpPNode performs deep traversals if it compares oopptr. CmpP is not notified for changes far away.
2876   if (n->Opcode() == Op_CmpP && type(n->in(1))->isa_oopptr() && type(n->in(2))->isa_oopptr()) {
2877     return true;
2878   }
2879   return false;
2880 }
2881 
2882 #ifdef ASSERT
2883 // For every node n on verify list, check if type(n) == n->Value()
2884 // Note for CCP the non-convergence can lead to unsound analysis and mis-compilation.
2885 // Therefore, we are verifying Value convergence strictly.
2886 void PhaseCCP::verify_analyze(Unique_Node_List& worklist_verify) {
2887   while (worklist_verify.size()) {
2888     Node* n = worklist_verify.pop();
2889 
2890     // An assert in verify_Value_for means that PhaseCCP is not at fixpoint
2891     // and that the analysis result may be unsound.
2892     // If this happens, check why the reported nodes were not processed again in CCP.
2893     // We should either make sure that these nodes are properly added back to the CCP worklist
2894     // in PhaseCCP::push_child_nodes_to_worklist() to update their type in the same round,
2895     // or that they are added in PhaseCCP::needs_revisit() so that analysis revisits
2896     // them at the end of the round.
2897     verify_Value_for(n, true);
2898   }
2899 }
2900 #endif
2901 
2902 // Fetch next node from worklist to be examined in this iteration.
2903 Node* PhaseCCP::fetch_next_node(Unique_Node_List& worklist) {
2904   if (StressCCP) {
2905     return worklist.remove(C->random() % worklist.size());
2906   } else {
2907     return worklist.pop();
2908   }
2909 }
2910 
2911 #ifndef PRODUCT
2912 void PhaseCCP::dump_type_and_node(const Node* n, const Type* t) {
2913   if (TracePhaseCCP) {
2914     t->dump();
2915     do {
2916       tty->print("\t");
2917     } while (tty->position() < 16);
2918     n->dump();
2919   }
2920 }
2921 #endif
2922 
2923 bool PhaseCCP::not_bottom_type(Node* n) const {
2924   return n->bottom_type() != type(n);
2925 }
2926 
2927 // We need to propagate the type change of 'n' to all its uses. Depending on the kind of node, additional nodes
2928 // (grandchildren or even further down) need to be revisited as their types could also be improved as a result
2929 // of the new type of 'n'. Push these nodes to the worklist.
2930 void PhaseCCP::push_child_nodes_to_worklist(Unique_Node_List& worklist, Node* n) const {
2931   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2932     Node* use = n->fast_out(i);
2933     push_if_not_bottom_type(worklist, use);
2934     push_more_uses(worklist, n, use);
2935   }
2936 }
2937 
2938 void PhaseCCP::push_if_not_bottom_type(Unique_Node_List& worklist, Node* n) const {
2939   if (not_bottom_type(n)) {
2940     worklist.push(n);
2941   }
2942 }
2943 
2944 // For some nodes, we need to propagate the type change to grandchildren or even further down.
2945 // Add them back to the worklist.
2946 void PhaseCCP::push_more_uses(Unique_Node_List& worklist, Node* parent, const Node* use) const {
2947   push_phis(worklist, use);
2948   push_catch(worklist, use);
2949   push_cmpu(worklist, use);
2950   push_counted_loop_phi(worklist, parent, use);

2951   push_loadp(worklist, use);
2952   push_and(worklist, parent, use);
2953   push_cast_ii(worklist, parent, use);
2954   push_opaque_zero_trip_guard(worklist, use);
2955   push_bool_with_cmpu_and_mask(worklist, use);
2956 }
2957 
2958 
2959 // We must recheck Phis too if use is a Region.
2960 void PhaseCCP::push_phis(Unique_Node_List& worklist, const Node* use) const {
2961   if (use->is_Region()) {
2962     add_users_to_worklist_if(worklist, use, [&](Node* u) {
2963       return not_bottom_type(u);
2964     });
2965   }
2966 }
2967 
2968 // If we changed the receiver type to a call, we need to revisit the Catch node following the call. It's looking for a
2969 // non-null receiver to know when to enable the regular fall-through path in addition to the NullPtrException path.
2970 // Same is true if the type of a ValidLengthTest input to an AllocateArrayNode changes.
2971 void PhaseCCP::push_catch(Unique_Node_List& worklist, const Node* use) {
2972   if (use->is_Call()) {
2973     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
2974       Node* proj = use->fast_out(i);
2975       if (proj->is_Proj() && proj->as_Proj()->_con == TypeFunc::Control) {
2976         Node* catch_node = proj->find_out_with(Op_Catch);
2977         if (catch_node != nullptr) {
2978           worklist.push(catch_node);
2979         }
2980       }
2981     }
2982   }
2983 }
2984 
2985 // CmpU nodes can get their type information from two nodes up in the graph (instead of from the nodes immediately
2986 // above). Make sure they are added to the worklist if nodes they depend on are updated since they could be missed
2987 // and get wrong types otherwise.
2988 void PhaseCCP::push_cmpu(Unique_Node_List& worklist, const Node* use) const {
2989   uint use_op = use->Opcode();
2990   if (use_op == Op_AddI || use_op == Op_SubI) {
2991     // Got a CmpU or CmpU3 which might need the new type information from node n.
2992     add_users_to_worklist_if(worklist, use, [&](Node* u) {
2993       uint op = u->Opcode();
2994       return (op == Op_CmpU || op == Op_CmpU3) && not_bottom_type(u);
2995     });
2996   }
2997 }
2998 
2999 // Look for the following shape, which can be optimized by BoolNode::Value_cmpu_and_mask() (i.e. corresponds to case
3000 // (1b): "(m & x) <u (m + 1))".
3001 // If any of the inputs on the level (%%) change, we need to revisit Bool because we could have prematurely found that
3002 // the Bool is constant (i.e. case (1b) can be applied) which could become invalid with new type information during CCP.
3003 //
3004 //  m    x  m    1  (%%)
3005 //   \  /    \  /
3006 //   AndI    AddI
3007 //      \    /
3008 //       CmpU
3009 //        |
3010 //       Bool
3011 //
3012 void PhaseCCP::push_bool_with_cmpu_and_mask(Unique_Node_List& worklist, const Node* use) const {
3013   uint use_op = use->Opcode();
3014   if (use_op != Op_AndI && (use_op != Op_AddI || use->in(2)->find_int_con(0) != 1)) {
3015     // Not "m & x" or "m + 1"
3016     return;
3017   }
3018   for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
3019     Node* cmpu = use->fast_out(i);
3020     if (cmpu->Opcode() == Op_CmpU) {
3021       push_bool_matching_case1b(worklist, cmpu);
3022     }
3023   }
3024 }
3025 
3026 // Push any Bool below 'cmpu' that matches case (1b) of BoolNode::Value_cmpu_and_mask().
3027 void PhaseCCP::push_bool_matching_case1b(Unique_Node_List& worklist, const Node* cmpu) const {
3028   assert(cmpu->Opcode() == Op_CmpU, "must be");
3029   for (DUIterator_Fast imax, i = cmpu->fast_outs(imax); i < imax; i++) {
3030     Node* bol = cmpu->fast_out(i);
3031     if (!bol->is_Bool() || bol->as_Bool()->_test._test != BoolTest::lt) {
3032       // Not a Bool with "<u"
3033       continue;
3034     }
3035     Node* andI = cmpu->in(1);
3036     Node* addI = cmpu->in(2);
3037     if (andI->Opcode() != Op_AndI || addI->Opcode() != Op_AddI || addI->in(2)->find_int_con(0) != 1) {
3038       // Not "m & x" and "m + 1"
3039       continue;
3040     }
3041 
3042     Node* m = addI->in(1);
3043     if (m == andI->in(1) || m == andI->in(2)) {
3044       // Is "m" shared? Matched (1b) and thus we revisit Bool.
3045       push_if_not_bottom_type(worklist, bol);
3046     }
3047   }
3048 }
3049 
3050 // 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'.
3051 // Seem PhiNode::Value().
3052 void PhaseCCP::push_counted_loop_phi(Unique_Node_List& worklist, Node* parent, const Node* use) {
3053   uint use_op = use->Opcode();
3054   if (use_op == Op_CmpI || use_op == Op_CmpL) {
3055     PhiNode* phi = countedloop_phi_from_cmp(use->as_Cmp(), parent);
3056     if (phi != nullptr) {
3057       worklist.push(phi);
3058     }
3059   }
3060 }
3061 













3062 // Loading the java mirror from a Klass requires two loads and the type of the mirror load depends on the type of 'n'.
3063 // See LoadNode::Value().
3064 void PhaseCCP::push_loadp(Unique_Node_List& worklist, const Node* use) const {
3065   BarrierSetC2* barrier_set = BarrierSet::barrier_set()->barrier_set_c2();
3066   bool has_load_barrier_nodes = barrier_set->has_load_barrier_nodes();
3067 
3068   if (use->Opcode() == Op_LoadP && use->bottom_type()->isa_rawptr()) {
3069     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
3070       Node* loadp = use->fast_out(i);
3071       const Type* ut = loadp->bottom_type();
3072       if (loadp->Opcode() == Op_LoadP && ut->isa_instptr() && ut != type(loadp)) {
3073         if (has_load_barrier_nodes) {
3074           // Search for load barriers behind the load
3075           push_load_barrier(worklist, barrier_set, loadp);
3076         }
3077         worklist.push(loadp);
3078       }
3079     }
3080   }
3081 }
3082 
3083 void PhaseCCP::push_load_barrier(Unique_Node_List& worklist, const BarrierSetC2* barrier_set, const Node* use) {
3084   add_users_to_worklist_if(worklist, use, [&](Node* u) {
3085     return barrier_set->is_gc_barrier_node(u);
3086   });
3087 }
3088 
3089 // AndI/L::Value() optimizes patterns similar to (v << 2) & 3, or CON & 3 to zero if they are bitwise disjoint.
3090 // Add the AndI/L nodes back to the worklist to re-apply Value() in case the value is now a constant or shift
3091 // value changed.
3092 void PhaseCCP::push_and(Unique_Node_List& worklist, const Node* parent, const Node* use) const {
3093   const TypeInteger* parent_type = type(parent)->isa_integer(type(parent)->basic_type());
3094   uint use_op = use->Opcode();
3095   if (
3096     // Pattern: parent (now constant) -> (ConstraintCast | ConvI2L)* -> And
3097     (parent_type != nullptr && parent_type->is_con()) ||
3098     // Pattern: parent -> LShift (use) -> (ConstraintCast | ConvI2L)* -> And
3099     ((use_op == Op_LShiftI || use_op == Op_LShiftL) && use->in(2) == parent)) {
3100 
3101     auto push_and_uses_to_worklist = [&](Node* n) {
3102       uint opc = n->Opcode();
3103       if (opc == Op_AndI || opc == Op_AndL) {
3104         push_if_not_bottom_type(worklist, n);
3105       }
3106     };
3107     auto is_boundary = [](Node* n) {
3108       return !(n->is_ConstraintCast() || n->Opcode() == Op_ConvI2L);
3109     };
3110     use->visit_uses(push_and_uses_to_worklist, is_boundary);
3111   }
3112 }
3113 
3114 // CastII::Value() optimizes CmpI/If patterns if the right input of the CmpI has a constant type. If the CastII input is
3115 // the same node as the left input into the CmpI node, the type of the CastII node can be improved accordingly. Add the
3116 // CastII node back to the worklist to re-apply Value() to either not miss this optimization or to undo it because it
3117 // cannot be applied anymore. We could have optimized the type of the CastII before but now the type of the right input
3118 // of the CmpI (i.e. 'parent') is no longer constant. The type of the CastII must be widened in this case.
3119 void PhaseCCP::push_cast_ii(Unique_Node_List& worklist, const Node* parent, const Node* use) const {
3120   if (use->Opcode() == Op_CmpI && use->in(2) == parent) {
3121     Node* other_cmp_input = use->in(1);
3122     add_users_to_worklist_if(worklist, other_cmp_input, [&](Node* u) {
3123       return u->is_CastII() && not_bottom_type(u);
3124     });
3125   }
3126 }
3127 
3128 void PhaseCCP::push_opaque_zero_trip_guard(Unique_Node_List& worklist, const Node* use) const {
3129   if (use->Opcode() == Op_OpaqueZeroTripGuard) {
3130     push_if_not_bottom_type(worklist, use->unique_out());
3131   }
3132 }
3133 
3134 //------------------------------do_transform-----------------------------------
3135 // Top level driver for the recursive transformer
3136 void PhaseCCP::do_transform() {
3137   // Correct leaves of new-space Nodes; they point to old-space.
3138   C->set_root( transform(C->root())->as_Root() );
3139   assert( C->top(),  "missing TOP node" );
3140   assert( C->root(), "missing root" );
3141 }
3142 
3143 //------------------------------transform--------------------------------------
3144 // Given a Node in old-space, clone him into new-space.
3145 // Convert any of his old-space children into new-space children.
3146 Node *PhaseCCP::transform( Node *n ) {
3147   assert(n->is_Root(), "traversal must start at root");
3148   assert(_root_and_safepoints.member(n), "root (n) must be in list");
3149 
3150   ResourceMark rm;
3151   // Map: old node idx -> node after CCP (or nullptr if not yet transformed or useless).
3152   Node_List node_map;
3153   // Pre-allocate to avoid frequent realloc
3154   GrowableArray <Node *> transform_stack(C->live_nodes() >> 1);
3155   // track all visited nodes, so that we can remove the complement
3156   Unique_Node_List useful;
3157 
3158   if (KillPathsReachableByDeadTypeNode) {
3159     for (uint i = 0; i < _maybe_top_type_nodes.size(); ++i) {
3160       Node* type_node = _maybe_top_type_nodes.at(i);
3161       if (type(type_node) == Type::TOP) {
3162         ResourceMark rm;
3163         type_node->as_Type()->make_paths_from_here_dead(this, nullptr, "ccp");
3164       }
3165     }
3166   } else {
3167     assert(_maybe_top_type_nodes.size() == 0, "we don't need type nodes");
3168   }
3169 
3170   // Initialize the traversal.
3171   // This CCP pass may prove that no exit test for a loop ever succeeds (i.e. the loop is infinite). In that case,
3172   // 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
3173   // 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
3174   // replaced by the top node and the inputs of that node n are not enqueued for further processing. If CCP only works
3175   // through the graph from Root, this causes the loop body to never be processed here even when it's not dead (that
3176   // is reachable from Root following its uses). To prevent that issue, transform() starts walking the graph from Root
3177   // and all safepoints.
3178   for (uint i = 0; i < _root_and_safepoints.size(); ++i) {
3179     Node* nn = _root_and_safepoints.at(i);
3180     Node* new_node = node_map[nn->_idx];
3181     assert(new_node == nullptr, "");
3182     new_node = transform_once(nn);  // Check for constant
3183     node_map.map(nn->_idx, new_node); // Flag as having been cloned
3184     transform_stack.push(new_node); // Process children of cloned node
3185     useful.push(new_node);
3186   }
3187 
3188   while (transform_stack.is_nonempty()) {
3189     Node* clone = transform_stack.pop();
3190     uint cnt = clone->req();
3191     for( uint i = 0; i < cnt; i++ ) {          // For all inputs do
3192       Node *input = clone->in(i);
3193       if( input != nullptr ) {                 // Ignore nulls
3194         Node *new_input = node_map[input->_idx]; // Check for cloned input node
3195         if( new_input == nullptr ) {
3196           new_input = transform_once(input);   // Check for constant
3197           node_map.map( input->_idx, new_input );// Flag as having been cloned
3198           transform_stack.push(new_input);     // Process children of cloned node
3199           useful.push(new_input);
3200         }
3201         assert( new_input == clone->in(i), "insanity check");
3202       }
3203     }
3204   }
3205 
3206   // The above transformation might lead to subgraphs becoming unreachable from the
3207   // bottom while still being reachable from the top. As a result, nodes in that
3208   // subgraph are not transformed and their bottom types are not updated, leading to
3209   // an inconsistency between bottom_type() and type(). In rare cases, LoadNodes in
3210   // such a subgraph, might be re-enqueued for IGVN indefinitely by MemNode::Ideal_common
3211   // because their address type is inconsistent. Therefore, we aggressively remove
3212   // all useless nodes here even before PhaseIdealLoop::build_loop_late gets a chance
3213   // to remove them anyway.
3214   if (C->cached_top_node()) {
3215     useful.push(C->cached_top_node());
3216   }
3217   C->update_dead_node_list(useful);
3218   remove_useless_nodes(useful.member_set());
3219   _worklist.remove_useless_nodes(useful.member_set());
3220   C->disconnect_useless_nodes(useful, _worklist, &_root_and_safepoints);
3221 
3222   Node* new_root = node_map[n->_idx];
3223   assert(new_root->is_Root(), "transformed root node must be a root node");
3224   return new_root;
3225 }
3226 
3227 //------------------------------transform_once---------------------------------
3228 // For PhaseCCP, transformation is IDENTITY unless Node computed a constant.
3229 Node *PhaseCCP::transform_once( Node *n ) {
3230   const Type *t = type(n);
3231   // Constant?  Use constant Node instead
3232   if( t->singleton() ) {
3233     Node *nn = n;               // Default is to return the original constant
3234     if( t == Type::TOP ) {
3235       // cache my top node on the Compile instance
3236       if( C->cached_top_node() == nullptr || C->cached_top_node()->in(0) == nullptr ) {
3237         C->set_cached_top_node(ConNode::make(Type::TOP));
3238         set_type(C->top(), Type::TOP);
3239       }
3240       nn = C->top();
3241     }
3242     if( !n->is_Con() ) {
3243       if( t != Type::TOP ) {
3244         nn = makecon(t);        // ConNode::make(t);
3245         NOT_PRODUCT( inc_constants(); )
3246       } else if( n->is_Region() ) { // Unreachable region
3247         // Note: nn == C->top()
3248         n->set_req(0, nullptr);     // Cut selfreference
3249         bool progress = true;
3250         uint max = n->outcnt();
3251         DUIterator i;
3252         while (progress) {
3253           progress = false;
3254           // Eagerly remove dead phis to avoid phis copies creation.
3255           for (i = n->outs(); n->has_out(i); i++) {
3256             Node* m = n->out(i);
3257             if (m->is_Phi()) {
3258               assert(type(m) == Type::TOP, "Unreachable region should not have live phis.");
3259               replace_node(m, nn);
3260               if (max != n->outcnt()) {
3261                 progress = true;
3262                 i = n->refresh_out_pos(i);
3263                 max = n->outcnt();
3264               }
3265             }
3266           }
3267         }
3268       }
3269       replace_node(n,nn);       // Update DefUse edges for new constant
3270     }
3271     return nn;
3272   }
3273 
3274   // If x is a TypeNode, capture any more-precise type permanently into Node
3275   if (t != n->bottom_type()) {
3276     hash_delete(n);             // changing bottom type may force a rehash
3277     n->raise_bottom_type(t);
3278     _worklist.push(n);          // n re-enters the hash table via the worklist
3279     add_users_to_worklist(n);   // if ideal or identity optimizations depend on the input type, users need to be notified
3280   }
3281 
3282   // TEMPORARY fix to ensure that 2nd GVN pass eliminates null checks
3283   switch( n->Opcode() ) {
3284   case Op_CallStaticJava:  // Give post-parse call devirtualization a chance
3285   case Op_CallDynamicJava:
3286   case Op_FastLock:        // Revisit FastLocks for lock coarsening
3287   case Op_If:
3288   case Op_CountedLoopEnd:
3289   case Op_Region:
3290   case Op_Loop:
3291   case Op_CountedLoop:
3292   case Op_Conv2B:
3293   case Op_Opaque1:
3294     _worklist.push(n);
3295     break;
3296   default:
3297     break;
3298   }
3299 
3300   return  n;
3301 }
3302 
3303 //---------------------------------saturate------------------------------------
3304 const Type* PhaseCCP::saturate(const Type* new_type, const Type* old_type,
3305                                const Type* limit_type) const {
3306   const Type* wide_type = new_type->widen(old_type, limit_type);
3307   if (wide_type != new_type) {          // did we widen?
3308     // If so, we may have widened beyond the limit type.  Clip it back down.
3309     new_type = wide_type->filter(limit_type);
3310   }
3311   return new_type;
3312 }
3313 
3314 //------------------------------print_statistics-------------------------------
3315 #ifndef PRODUCT
3316 void PhaseCCP::print_statistics() {
3317   tty->print_cr("CCP: %d  constants found: %d", _total_invokes, _total_constants);
3318 }
3319 #endif
3320 
3321 
3322 //=============================================================================
3323 #ifndef PRODUCT
3324 uint PhasePeephole::_total_peepholes = 0;
3325 #endif
3326 //------------------------------PhasePeephole----------------------------------
3327 // Conditional Constant Propagation, ala Wegman & Zadeck
3328 PhasePeephole::PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg )
3329   : PhaseTransform(Peephole), _regalloc(regalloc), _cfg(cfg) {
3330   NOT_PRODUCT( clear_peepholes(); )
3331 }
3332 
3333 #ifndef PRODUCT
3334 //------------------------------~PhasePeephole---------------------------------
3335 PhasePeephole::~PhasePeephole() {
3336   _total_peepholes += count_peepholes();
3337 }
3338 #endif
3339 
3340 //------------------------------transform--------------------------------------
3341 Node *PhasePeephole::transform( Node *n ) {
3342   ShouldNotCallThis();
3343   return nullptr;
3344 }
3345 
3346 //------------------------------do_transform-----------------------------------
3347 void PhasePeephole::do_transform() {
3348   bool method_name_not_printed = true;
3349 
3350   // Examine each basic block
3351   for (uint block_number = 1; block_number < _cfg.number_of_blocks(); ++block_number) {
3352     Block* block = _cfg.get_block(block_number);
3353     bool block_not_printed = true;
3354 
3355     for (bool progress = true; progress;) {
3356       progress = false;
3357       // block->end_idx() not valid after PhaseRegAlloc
3358       uint end_index = block->number_of_nodes();
3359       for( uint instruction_index = end_index - 1; instruction_index > 0; --instruction_index ) {
3360         Node     *n = block->get_node(instruction_index);
3361         if( n->is_Mach() ) {
3362           MachNode *m = n->as_Mach();
3363           // check for peephole opportunities
3364           int result = m->peephole(block, instruction_index, &_cfg, _regalloc);
3365           if( result != -1 ) {
3366 #ifndef PRODUCT
3367             if( PrintOptoPeephole ) {
3368               // Print method, first time only
3369               if( C->method() && method_name_not_printed ) {
3370                 C->method()->print_short_name(); tty->cr();
3371                 method_name_not_printed = false;
3372               }
3373               // Print this block
3374               if( Verbose && block_not_printed) {
3375                 tty->print_cr("in block");
3376                 block->dump();
3377                 block_not_printed = false;
3378               }
3379               // Print the peephole number
3380               tty->print_cr("peephole number: %d", result);
3381             }
3382             inc_peepholes();
3383 #endif
3384             // Set progress, start again
3385             progress = true;
3386             break;
3387           }
3388         }
3389       }
3390     }
3391   }
3392 }
3393 
3394 //------------------------------print_statistics-------------------------------
3395 #ifndef PRODUCT
3396 void PhasePeephole::print_statistics() {
3397   tty->print_cr("Peephole: peephole rules applied: %d",  _total_peepholes);
3398 }
3399 #endif
3400 
3401 
3402 //=============================================================================
3403 //------------------------------set_req_X--------------------------------------
3404 void Node::set_req_X( uint i, Node *n, PhaseIterGVN *igvn ) {
3405   assert( is_not_dead(n), "can not use dead node");
3406 #ifdef ASSERT
3407   if (igvn->hash_find(this) == this) {
3408     tty->print_cr("Need to remove from hash before changing edges");
3409     this->dump(1);
3410     tty->print_cr("Set at i = %d", i);
3411     n->dump();
3412     assert(false, "Need to remove from hash before changing edges");
3413   }
3414 #endif
3415   Node *old = in(i);
3416   set_req(i, n);
3417 
3418   // old goes dead?
3419   if( old ) {
3420     switch (old->outcnt()) {
3421     case 0:
3422       // Put into the worklist to kill later. We do not kill it now because the
3423       // recursive kill will delete the current node (this) if dead-loop exists
3424       if (!old->is_top())
3425         igvn->_worklist.push( old );
3426       break;
3427     case 1:
3428       if( old->is_Store() || old->has_special_unique_user() )
3429         igvn->add_users_to_worklist( old );
3430       break;
3431     case 2:
3432       if( old->is_Store() )
3433         igvn->add_users_to_worklist( old );
3434       if( old->Opcode() == Op_Region )
3435         igvn->_worklist.push(old);
3436       break;
3437     case 3:
3438       if( old->Opcode() == Op_Region ) {
3439         igvn->_worklist.push(old);
3440         igvn->add_users_to_worklist( old );
3441       }
3442       break;
3443     default:
3444       break;
3445     }
3446 
3447     BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(igvn, old);
3448   }
3449 }
3450 
3451 void Node::set_req_X(uint i, Node *n, PhaseGVN *gvn) {
3452   PhaseIterGVN* igvn = gvn->is_IterGVN();
3453   if (igvn == nullptr) {
3454     set_req(i, n);
3455     return;
3456   }
3457   set_req_X(i, n, igvn);
3458 }
3459 
3460 //-------------------------------replace_by-----------------------------------
3461 // Using def-use info, replace one node for another.  Follow the def-use info
3462 // to all users of the OLD node.  Then make all uses point to the NEW node.
3463 void Node::replace_by(Node *new_node) {
3464   assert(!is_top(), "top node has no DU info");
3465   for (DUIterator_Last imin, i = last_outs(imin); i >= imin; ) {
3466     Node* use = last_out(i);
3467     uint uses_found = 0;
3468     for (uint j = 0; j < use->len(); j++) {
3469       if (use->in(j) == this) {
3470         if (j < use->req())
3471               use->set_req(j, new_node);
3472         else  use->set_prec(j, new_node);
3473         uses_found++;
3474       }
3475     }
3476     i -= uses_found;    // we deleted 1 or more copies of this edge
3477   }
3478 }
3479 
3480 //=============================================================================
3481 //-----------------------------------------------------------------------------
3482 void Type_Array::grow( uint i ) {
3483   assert(_a == Compile::current()->comp_arena(), "Should be allocated in comp_arena");
3484   if( !_max ) {
3485     _max = 1;
3486     _types = (const Type**)_a->Amalloc( _max * sizeof(Type*) );
3487     _types[0] = nullptr;
3488   }
3489   uint old = _max;
3490   _max = next_power_of_2(i);
3491   _types = (const Type**)_a->Arealloc( _types, old*sizeof(Type*),_max*sizeof(Type*));
3492   memset( &_types[old], 0, (_max-old)*sizeof(Type*) );
3493 }
3494 
3495 //------------------------------dump-------------------------------------------
3496 #ifndef PRODUCT
3497 void Type_Array::dump() const {
3498   uint max = Size();
3499   for( uint i = 0; i < max; i++ ) {
3500     if( _types[i] != nullptr ) {
3501       tty->print("  %d\t== ", i); _types[i]->dump(); tty->cr();
3502     }
3503   }
3504 }
3505 #endif
--- EOF ---