1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "gc/shared/barrierSet.hpp"
  27 #include "gc/shared/c2/barrierSetC2.hpp"
  28 #include "memory/allocation.inline.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "opto/block.hpp"
  31 #include "opto/callnode.hpp"
  32 #include "opto/castnode.hpp"
  33 #include "opto/cfgnode.hpp"
  34 #include "opto/idealGraphPrinter.hpp"
  35 #include "opto/loopnode.hpp"
  36 #include "opto/machnode.hpp"
  37 #include "opto/opcodes.hpp"
  38 #include "opto/phaseX.hpp"
  39 #include "opto/regalloc.hpp"
  40 #include "opto/rootnode.hpp"
  41 #include "utilities/macros.hpp"
  42 #if INCLUDE_SHENANDOAHGC
  43 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  44 #endif
  45 
  46 //=============================================================================
  47 #define NODE_HASH_MINIMUM_SIZE    255
  48 //------------------------------NodeHash---------------------------------------
  49 NodeHash::NodeHash(uint est_max_size) :
  50   _max( round_up(est_max_size < NODE_HASH_MINIMUM_SIZE ? NODE_HASH_MINIMUM_SIZE : est_max_size) ),
  51   _a(Thread::current()->resource_area()),
  52   _table( NEW_ARENA_ARRAY( _a , Node* , _max ) ), // (Node**)_a->Amalloc(_max * sizeof(Node*)) ),
  53   _inserts(0), _insert_limit( insert_limit() )
  54 #ifndef PRODUCT
  55   ,_look_probes(0), _lookup_hits(0), _lookup_misses(0),
  56   _delete_probes(0), _delete_hits(0), _delete_misses(0),
  57   _total_insert_probes(0), _total_inserts(0),
  58   _insert_probes(0), _grows(0)
  59 #endif
  60 {
  61   // _sentinel must be in the current node space
  62   _sentinel = new ProjNode(NULL, TypeFunc::Control);
  63   memset(_table,0,sizeof(Node*)*_max);
  64 }
  65 
  66 //------------------------------NodeHash---------------------------------------
  67 NodeHash::NodeHash(Arena *arena, uint est_max_size) :
  68   _max( round_up(est_max_size < NODE_HASH_MINIMUM_SIZE ? NODE_HASH_MINIMUM_SIZE : est_max_size) ),
  69   _a(arena),
  70   _table( NEW_ARENA_ARRAY( _a , Node* , _max ) ),
  71   _inserts(0), _insert_limit( insert_limit() )
  72 #ifndef PRODUCT
  73   ,_look_probes(0), _lookup_hits(0), _lookup_misses(0),
  74   _delete_probes(0), _delete_hits(0), _delete_misses(0),
  75   _total_insert_probes(0), _total_inserts(0),
  76   _insert_probes(0), _grows(0)
  77 #endif
  78 {
  79   // _sentinel must be in the current node space
  80   _sentinel = new ProjNode(NULL, TypeFunc::Control);
  81   memset(_table,0,sizeof(Node*)*_max);
  82 }
  83 
  84 //------------------------------NodeHash---------------------------------------
  85 NodeHash::NodeHash(NodeHash *nh) {
  86   debug_only(_table = (Node**)badAddress);   // interact correctly w/ operator=
  87   // just copy in all the fields
  88   *this = *nh;
  89   // nh->_sentinel must be in the current node space
  90 }
  91 
  92 void NodeHash::replace_with(NodeHash *nh) {
  93   debug_only(_table = (Node**)badAddress);   // interact correctly w/ operator=
  94   // just copy in all the fields
  95   *this = *nh;
  96   // nh->_sentinel must be in the current node space
  97 }
  98 
  99 //------------------------------hash_find--------------------------------------
 100 // Find in hash table
 101 Node *NodeHash::hash_find( const Node *n ) {
 102   // ((Node*)n)->set_hash( n->hash() );
 103   uint hash = n->hash();
 104   if (hash == Node::NO_HASH) {
 105     NOT_PRODUCT( _lookup_misses++ );
 106     return NULL;
 107   }
 108   uint key = hash & (_max-1);
 109   uint stride = key | 0x01;
 110   NOT_PRODUCT( _look_probes++ );
 111   Node *k = _table[key];        // Get hashed value
 112   if( !k ) {                    // ?Miss?
 113     NOT_PRODUCT( _lookup_misses++ );
 114     return NULL;                // Miss!
 115   }
 116 
 117   int op = n->Opcode();
 118   uint req = n->req();
 119   while( 1 ) {                  // While probing hash table
 120     if( k->req() == req &&      // Same count of inputs
 121         k->Opcode() == op ) {   // Same Opcode
 122       for( uint i=0; i<req; i++ )
 123         if( n->in(i)!=k->in(i)) // Different inputs?
 124           goto collision;       // "goto" is a speed hack...
 125       if( n->cmp(*k) ) {        // Check for any special bits
 126         NOT_PRODUCT( _lookup_hits++ );
 127         return k;               // Hit!
 128       }
 129     }
 130   collision:
 131     NOT_PRODUCT( _look_probes++ );
 132     key = (key + stride/*7*/) & (_max-1); // Stride through table with relative prime
 133     k = _table[key];            // Get hashed value
 134     if( !k ) {                  // ?Miss?
 135       NOT_PRODUCT( _lookup_misses++ );
 136       return NULL;              // Miss!
 137     }
 138   }
 139   ShouldNotReachHere();
 140   return NULL;
 141 }
 142 
 143 //------------------------------hash_find_insert-------------------------------
 144 // Find in hash table, insert if not already present
 145 // Used to preserve unique entries in hash table
 146 Node *NodeHash::hash_find_insert( Node *n ) {
 147   // n->set_hash( );
 148   uint hash = n->hash();
 149   if (hash == Node::NO_HASH) {
 150     NOT_PRODUCT( _lookup_misses++ );
 151     return NULL;
 152   }
 153   uint key = hash & (_max-1);
 154   uint stride = key | 0x01;     // stride must be relatively prime to table siz
 155   uint first_sentinel = 0;      // replace a sentinel if seen.
 156   NOT_PRODUCT( _look_probes++ );
 157   Node *k = _table[key];        // Get hashed value
 158   if( !k ) {                    // ?Miss?
 159     NOT_PRODUCT( _lookup_misses++ );
 160     _table[key] = n;            // Insert into table!
 161     debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
 162     check_grow();               // Grow table if insert hit limit
 163     return NULL;                // Miss!
 164   }
 165   else if( k == _sentinel ) {
 166     first_sentinel = key;      // Can insert here
 167   }
 168 
 169   int op = n->Opcode();
 170   uint req = n->req();
 171   while( 1 ) {                  // While probing hash table
 172     if( k->req() == req &&      // Same count of inputs
 173         k->Opcode() == op ) {   // Same Opcode
 174       for( uint i=0; i<req; i++ )
 175         if( n->in(i)!=k->in(i)) // Different inputs?
 176           goto collision;       // "goto" is a speed hack...
 177       if( n->cmp(*k) ) {        // Check for any special bits
 178         NOT_PRODUCT( _lookup_hits++ );
 179         return k;               // Hit!
 180       }
 181     }
 182   collision:
 183     NOT_PRODUCT( _look_probes++ );
 184     key = (key + stride) & (_max-1); // Stride through table w/ relative prime
 185     k = _table[key];            // Get hashed value
 186     if( !k ) {                  // ?Miss?
 187       NOT_PRODUCT( _lookup_misses++ );
 188       key = (first_sentinel == 0) ? key : first_sentinel; // ?saw sentinel?
 189       _table[key] = n;          // Insert into table!
 190       debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
 191       check_grow();             // Grow table if insert hit limit
 192       return NULL;              // Miss!
 193     }
 194     else if( first_sentinel == 0 && k == _sentinel ) {
 195       first_sentinel = key;    // Can insert here
 196     }
 197 
 198   }
 199   ShouldNotReachHere();
 200   return NULL;
 201 }
 202 
 203 //------------------------------hash_insert------------------------------------
 204 // Insert into hash table
 205 void NodeHash::hash_insert( Node *n ) {
 206   // // "conflict" comments -- print nodes that conflict
 207   // bool conflict = false;
 208   // n->set_hash();
 209   uint hash = n->hash();
 210   if (hash == Node::NO_HASH) {
 211     return;
 212   }
 213   check_grow();
 214   uint key = hash & (_max-1);
 215   uint stride = key | 0x01;
 216 
 217   while( 1 ) {                  // While probing hash table
 218     NOT_PRODUCT( _insert_probes++ );
 219     Node *k = _table[key];      // Get hashed value
 220     if( !k || (k == _sentinel) ) break;       // Found a slot
 221     assert( k != n, "already inserted" );
 222     // if( PrintCompilation && PrintOptoStatistics && Verbose ) { tty->print("  conflict: "); k->dump(); conflict = true; }
 223     key = (key + stride) & (_max-1); // Stride through table w/ relative prime
 224   }
 225   _table[key] = n;              // Insert into table!
 226   debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
 227   // if( conflict ) { n->dump(); }
 228 }
 229 
 230 //------------------------------hash_delete------------------------------------
 231 // Replace in hash table with sentinel
 232 bool NodeHash::hash_delete( const Node *n ) {
 233   Node *k;
 234   uint hash = n->hash();
 235   if (hash == Node::NO_HASH) {
 236     NOT_PRODUCT( _delete_misses++ );
 237     return false;
 238   }
 239   uint key = hash & (_max-1);
 240   uint stride = key | 0x01;
 241   debug_only( uint counter = 0; );
 242   for( ; /* (k != NULL) && (k != _sentinel) */; ) {
 243     debug_only( counter++ );
 244     NOT_PRODUCT( _delete_probes++ );
 245     k = _table[key];            // Get hashed value
 246     if( !k ) {                  // Miss?
 247       NOT_PRODUCT( _delete_misses++ );
 248 #ifdef ASSERT
 249       if( VerifyOpto ) {
 250         for( uint i=0; i < _max; i++ )
 251           assert( _table[i] != n, "changed edges with rehashing" );
 252       }
 253 #endif
 254       return false;             // Miss! Not in chain
 255     }
 256     else if( n == k ) {
 257       NOT_PRODUCT( _delete_hits++ );
 258       _table[key] = _sentinel;  // Hit! Label as deleted entry
 259       debug_only(((Node*)n)->exit_hash_lock()); // Unlock the node upon removal from table.
 260       return true;
 261     }
 262     else {
 263       // collision: move through table with prime offset
 264       key = (key + stride/*7*/) & (_max-1);
 265       assert( counter <= _insert_limit, "Cycle in hash-table");
 266     }
 267   }
 268   ShouldNotReachHere();
 269   return false;
 270 }
 271 
 272 //------------------------------round_up---------------------------------------
 273 // Round up to nearest power of 2
 274 uint NodeHash::round_up( uint x ) {
 275   x += (x>>2);                  // Add 25% slop
 276   if( x <16 ) return 16;        // Small stuff
 277   uint i=16;
 278   while( i < x ) i <<= 1;       // Double to fit
 279   return i;                     // Return hash table size
 280 }
 281 
 282 //------------------------------grow-------------------------------------------
 283 // Grow _table to next power of 2 and insert old entries
 284 void  NodeHash::grow() {
 285   // Record old state
 286   uint   old_max   = _max;
 287   Node **old_table = _table;
 288   // Construct new table with twice the space
 289 #ifndef PRODUCT
 290   _grows++;
 291   _total_inserts       += _inserts;
 292   _total_insert_probes += _insert_probes;
 293   _insert_probes   = 0;
 294 #endif
 295   _inserts         = 0;
 296   _max     = _max << 1;
 297   _table   = NEW_ARENA_ARRAY( _a , Node* , _max ); // (Node**)_a->Amalloc( _max * sizeof(Node*) );
 298   memset(_table,0,sizeof(Node*)*_max);
 299   _insert_limit = insert_limit();
 300   // Insert old entries into the new table
 301   for( uint i = 0; i < old_max; i++ ) {
 302     Node *m = *old_table++;
 303     if( !m || m == _sentinel ) continue;
 304     debug_only(m->exit_hash_lock()); // Unlock the node upon removal from old table.
 305     hash_insert(m);
 306   }
 307 }
 308 
 309 //------------------------------clear------------------------------------------
 310 // Clear all entries in _table to NULL but keep storage
 311 void  NodeHash::clear() {
 312 #ifdef ASSERT
 313   // Unlock all nodes upon removal from table.
 314   for (uint i = 0; i < _max; i++) {
 315     Node* n = _table[i];
 316     if (!n || n == _sentinel)  continue;
 317     n->exit_hash_lock();
 318   }
 319 #endif
 320 
 321   memset( _table, 0, _max * sizeof(Node*) );
 322 }
 323 
 324 //-----------------------remove_useless_nodes----------------------------------
 325 // Remove useless nodes from value table,
 326 // implementation does not depend on hash function
 327 void NodeHash::remove_useless_nodes(VectorSet &useful) {
 328 
 329   // Dead nodes in the hash table inherited from GVN should not replace
 330   // existing nodes, remove dead nodes.
 331   uint max = size();
 332   Node *sentinel_node = sentinel();
 333   for( uint i = 0; i < max; ++i ) {
 334     Node *n = at(i);
 335     if(n != NULL && n != sentinel_node && !useful.test(n->_idx)) {
 336       debug_only(n->exit_hash_lock()); // Unlock the node when removed
 337       _table[i] = sentinel_node;       // Replace with placeholder
 338     }
 339   }
 340 }
 341 
 342 
 343 void NodeHash::check_no_speculative_types() {
 344 #ifdef ASSERT
 345   uint max = size();
 346   Node *sentinel_node = sentinel();
 347   for (uint i = 0; i < max; ++i) {
 348     Node *n = at(i);
 349     if(n != NULL && n != sentinel_node && n->is_Type() && n->outcnt() > 0) {
 350       TypeNode* tn = n->as_Type();
 351       const Type* t = tn->type();
 352       const Type* t_no_spec = t->remove_speculative();
 353       assert(t == t_no_spec, "dead node in hash table or missed node during speculative cleanup");
 354     }
 355   }
 356 #endif
 357 }
 358 
 359 #ifndef PRODUCT
 360 //------------------------------dump-------------------------------------------
 361 // Dump statistics for the hash table
 362 void NodeHash::dump() {
 363   _total_inserts       += _inserts;
 364   _total_insert_probes += _insert_probes;
 365   if (PrintCompilation && PrintOptoStatistics && Verbose && (_inserts > 0)) {
 366     if (WizardMode) {
 367       for (uint i=0; i<_max; i++) {
 368         if (_table[i])
 369           tty->print("%d/%d/%d ",i,_table[i]->hash()&(_max-1),_table[i]->_idx);
 370       }
 371     }
 372     tty->print("\nGVN Hash stats:  %d grows to %d max_size\n", _grows, _max);
 373     tty->print("  %d/%d (%8.1f%% full)\n", _inserts, _max, (double)_inserts/_max*100.0);
 374     tty->print("  %dp/(%dh+%dm) (%8.2f probes/lookup)\n", _look_probes, _lookup_hits, _lookup_misses, (double)_look_probes/(_lookup_hits+_lookup_misses));
 375     tty->print("  %dp/%di (%8.2f probes/insert)\n", _total_insert_probes, _total_inserts, (double)_total_insert_probes/_total_inserts);
 376     // sentinels increase lookup cost, but not insert cost
 377     assert((_lookup_misses+_lookup_hits)*4+100 >= _look_probes, "bad hash function");
 378     assert( _inserts+(_inserts>>3) < _max, "table too full" );
 379     assert( _inserts*3+100 >= _insert_probes, "bad hash function" );
 380   }
 381 }
 382 
 383 Node *NodeHash::find_index(uint idx) { // For debugging
 384   // Find an entry by its index value
 385   for( uint i = 0; i < _max; i++ ) {
 386     Node *m = _table[i];
 387     if( !m || m == _sentinel ) continue;
 388     if( m->_idx == (uint)idx ) return m;
 389   }
 390   return NULL;
 391 }
 392 #endif
 393 
 394 #ifdef ASSERT
 395 NodeHash::~NodeHash() {
 396   // Unlock all nodes upon destruction of table.
 397   if (_table != (Node**)badAddress)  clear();
 398 }
 399 
 400 void NodeHash::operator=(const NodeHash& nh) {
 401   // Unlock all nodes upon replacement of table.
 402   if (&nh == this)  return;
 403   if (_table != (Node**)badAddress)  clear();
 404   memcpy((void*)this, (void*)&nh, sizeof(*this));
 405   // Do not increment hash_lock counts again.
 406   // Instead, be sure we never again use the source table.
 407   ((NodeHash*)&nh)->_table = (Node**)badAddress;
 408 }
 409 
 410 
 411 #endif
 412 
 413 
 414 //=============================================================================
 415 //------------------------------PhaseRemoveUseless-----------------------------
 416 // 1) Use a breadthfirst walk to collect useful nodes reachable from root.
 417 PhaseRemoveUseless::PhaseRemoveUseless(PhaseGVN *gvn, Unique_Node_List *worklist, PhaseNumber phase_num) : Phase(phase_num),
 418   _useful(Thread::current()->resource_area()) {
 419 
 420   // Implementation requires 'UseLoopSafepoints == true' and an edge from root
 421   // to each SafePointNode at a backward branch.  Inserted in add_safepoint().
 422   if( !UseLoopSafepoints || !OptoRemoveUseless ) return;
 423 
 424   // Identify nodes that are reachable from below, useful.
 425   C->identify_useful_nodes(_useful);
 426   // Update dead node list
 427   C->update_dead_node_list(_useful);
 428 
 429   // Remove all useless nodes from PhaseValues' recorded types
 430   // Must be done before disconnecting nodes to preserve hash-table-invariant
 431   gvn->remove_useless_nodes(_useful.member_set());
 432 
 433   // Remove all useless nodes from future worklist
 434   worklist->remove_useless_nodes(_useful.member_set());
 435 
 436   // Disconnect 'useless' nodes that are adjacent to useful nodes
 437   C->remove_useless_nodes(_useful);
 438 
 439   // Remove edges from "root" to each SafePoint at a backward branch.
 440   // They were inserted during parsing (see add_safepoint()) to make infinite
 441   // loops without calls or exceptions visible to root, i.e., useful.
 442   Node *root = C->root();
 443   if( root != NULL ) {
 444     for( uint i = root->req(); i < root->len(); ++i ) {
 445       Node *n = root->in(i);
 446       if( n != NULL && n->is_SafePoint() ) {
 447         root->rm_prec(i);
 448         --i;
 449       }
 450     }
 451   }
 452 }
 453 
 454 //=============================================================================
 455 //------------------------------PhaseRenumberLive------------------------------
 456 // First, remove useless nodes (equivalent to identifying live nodes).
 457 // Then, renumber live nodes.
 458 //
 459 // The set of live nodes is returned by PhaseRemoveUseless in the _useful structure.
 460 // If the number of live nodes is 'x' (where 'x' == _useful.size()), then the
 461 // PhaseRenumberLive updates the node ID of each node (the _idx field) with a unique
 462 // value in the range [0, x).
 463 //
 464 // At the end of the PhaseRenumberLive phase, the compiler's count of unique nodes is
 465 // updated to 'x' and the list of dead nodes is reset (as there are no dead nodes).
 466 //
 467 // The PhaseRenumberLive phase updates two data structures with the new node IDs.
 468 // (1) The worklist is used by the PhaseIterGVN phase to identify nodes that must be
 469 // processed. A new worklist (with the updated node IDs) is returned in 'new_worklist'.
 470 // (2) Type information (the field PhaseGVN::_types) maps type information to each
 471 // node ID. The mapping is updated to use the new node IDs as well. Updated type
 472 // information is returned in PhaseGVN::_types.
 473 //
 474 // The PhaseRenumberLive phase does not preserve the order of elements in the worklist.
 475 //
 476 // Other data structures used by the compiler are not updated. The hash table for value
 477 // numbering (the field PhaseGVN::_table) is not updated because computing the hash
 478 // values is not based on node IDs. The field PhaseGVN::_nodes is not updated either
 479 // because it is empty wherever PhaseRenumberLive is used.
 480 PhaseRenumberLive::PhaseRenumberLive(PhaseGVN* gvn,
 481                                      Unique_Node_List* worklist, Unique_Node_List* new_worklist,
 482                                      PhaseNumber phase_num) :
 483   PhaseRemoveUseless(gvn, worklist, Remove_Useless_And_Renumber_Live) {
 484 
 485   assert(RenumberLiveNodes, "RenumberLiveNodes must be set to true for node renumbering to take place");
 486   assert(C->live_nodes() == _useful.size(), "the number of live nodes must match the number of useful nodes");
 487   assert(gvn->nodes_size() == 0, "GVN must not contain any nodes at this point");
 488 
 489   uint old_unique_count = C->unique();
 490   uint live_node_count = C->live_nodes();
 491   uint worklist_size = worklist->size();
 492 
 493   // Storage for the updated type information.
 494   Type_Array new_type_array(C->comp_arena());
 495 
 496   // Iterate over the set of live nodes.
 497   uint current_idx = 0; // The current new node ID. Incremented after every assignment.
 498   for (uint i = 0; i < _useful.size(); i++) {
 499     Node* n = _useful.at(i);
 500     // Sanity check that fails if we ever decide to execute this phase after EA
 501     assert(!n->is_Phi() || n->as_Phi()->inst_mem_id() == -1, "should not be linked to data Phi");
 502     const Type* type = gvn->type_or_null(n);
 503     new_type_array.map(current_idx, type);
 504 
 505     bool in_worklist = false;
 506     if (worklist->member(n)) {
 507       in_worklist = true;
 508     }
 509 
 510     n->set_idx(current_idx); // Update node ID.
 511 
 512     if (in_worklist) {
 513       new_worklist->push(n);
 514     }
 515 
 516     current_idx++;
 517   }
 518 
 519   assert(worklist_size == new_worklist->size(), "the new worklist must have the same size as the original worklist");
 520   assert(live_node_count == current_idx, "all live nodes must be processed");
 521 
 522   // Replace the compiler's type information with the updated type information.
 523   gvn->replace_types(new_type_array);
 524 
 525   // Update the unique node count of the compilation to the number of currently live nodes.
 526   C->set_unique(live_node_count);
 527 
 528   // Set the dead node count to 0 and reset dead node list.
 529   C->reset_dead_node_list();
 530 }
 531 
 532 
 533 //=============================================================================
 534 //------------------------------PhaseTransform---------------------------------
 535 PhaseTransform::PhaseTransform( PhaseNumber pnum ) : Phase(pnum),
 536   _arena(Thread::current()->resource_area()),
 537   _nodes(_arena),
 538   _types(_arena)
 539 {
 540   init_con_caches();
 541 #ifndef PRODUCT
 542   clear_progress();
 543   clear_transforms();
 544   set_allow_progress(true);
 545 #endif
 546   // Force allocation for currently existing nodes
 547   _types.map(C->unique(), NULL);
 548 }
 549 
 550 //------------------------------PhaseTransform---------------------------------
 551 PhaseTransform::PhaseTransform( Arena *arena, PhaseNumber pnum ) : Phase(pnum),
 552   _arena(arena),
 553   _nodes(arena),
 554   _types(arena)
 555 {
 556   init_con_caches();
 557 #ifndef PRODUCT
 558   clear_progress();
 559   clear_transforms();
 560   set_allow_progress(true);
 561 #endif
 562   // Force allocation for currently existing nodes
 563   _types.map(C->unique(), NULL);
 564 }
 565 
 566 //------------------------------PhaseTransform---------------------------------
 567 // Initialize with previously generated type information
 568 PhaseTransform::PhaseTransform( PhaseTransform *pt, PhaseNumber pnum ) : Phase(pnum),
 569   _arena(pt->_arena),
 570   _nodes(pt->_nodes),
 571   _types(pt->_types)
 572 {
 573   init_con_caches();
 574 #ifndef PRODUCT
 575   clear_progress();
 576   clear_transforms();
 577   set_allow_progress(true);
 578 #endif
 579 }
 580 
 581 void PhaseTransform::init_con_caches() {
 582   memset(_icons,0,sizeof(_icons));
 583   memset(_lcons,0,sizeof(_lcons));
 584   memset(_zcons,0,sizeof(_zcons));
 585 }
 586 
 587 
 588 //--------------------------------find_int_type--------------------------------
 589 const TypeInt* PhaseTransform::find_int_type(Node* n) {
 590   if (n == NULL)  return NULL;
 591   // Call type_or_null(n) to determine node's type since we might be in
 592   // parse phase and call n->Value() may return wrong type.
 593   // (For example, a phi node at the beginning of loop parsing is not ready.)
 594   const Type* t = type_or_null(n);
 595   if (t == NULL)  return NULL;
 596   return t->isa_int();
 597 }
 598 
 599 
 600 //-------------------------------find_long_type--------------------------------
 601 const TypeLong* PhaseTransform::find_long_type(Node* n) {
 602   if (n == NULL)  return NULL;
 603   // (See comment above on type_or_null.)
 604   const Type* t = type_or_null(n);
 605   if (t == NULL)  return NULL;
 606   return t->isa_long();
 607 }
 608 
 609 
 610 #ifndef PRODUCT
 611 void PhaseTransform::dump_old2new_map() const {
 612   _nodes.dump();
 613 }
 614 
 615 void PhaseTransform::dump_new( uint nidx ) const {
 616   for( uint i=0; i<_nodes.Size(); i++ )
 617     if( _nodes[i] && _nodes[i]->_idx == nidx ) {
 618       _nodes[i]->dump();
 619       tty->cr();
 620       tty->print_cr("Old index= %d",i);
 621       return;
 622     }
 623   tty->print_cr("Node %d not found in the new indices", nidx);
 624 }
 625 
 626 //------------------------------dump_types-------------------------------------
 627 void PhaseTransform::dump_types( ) const {
 628   _types.dump();
 629 }
 630 
 631 //------------------------------dump_nodes_and_types---------------------------
 632 void PhaseTransform::dump_nodes_and_types(const Node *root, uint depth, bool only_ctrl) {
 633   VectorSet visited(Thread::current()->resource_area());
 634   dump_nodes_and_types_recur( root, depth, only_ctrl, visited );
 635 }
 636 
 637 //------------------------------dump_nodes_and_types_recur---------------------
 638 void PhaseTransform::dump_nodes_and_types_recur( const Node *n, uint depth, bool only_ctrl, VectorSet &visited) {
 639   if( !n ) return;
 640   if( depth == 0 ) return;
 641   if( visited.test_set(n->_idx) ) return;
 642   for( uint i=0; i<n->len(); i++ ) {
 643     if( only_ctrl && !(n->is_Region()) && i != TypeFunc::Control ) continue;
 644     dump_nodes_and_types_recur( n->in(i), depth-1, only_ctrl, visited );
 645   }
 646   n->dump();
 647   if (type_or_null(n) != NULL) {
 648     tty->print("      "); type(n)->dump(); tty->cr();
 649   }
 650 }
 651 
 652 #endif
 653 
 654 
 655 //=============================================================================
 656 //------------------------------PhaseValues------------------------------------
 657 // Set minimum table size to "255"
 658 PhaseValues::PhaseValues( Arena *arena, uint est_max_size ) : PhaseTransform(arena, GVN), _table(arena, est_max_size) {
 659   NOT_PRODUCT( clear_new_values(); )
 660 }
 661 
 662 //------------------------------PhaseValues------------------------------------
 663 // Set minimum table size to "255"
 664 PhaseValues::PhaseValues( PhaseValues *ptv ) : PhaseTransform( ptv, GVN ),
 665   _table(&ptv->_table) {
 666   NOT_PRODUCT( clear_new_values(); )
 667 }
 668 
 669 //------------------------------PhaseValues------------------------------------
 670 // Used by +VerifyOpto.  Clear out hash table but copy _types array.
 671 PhaseValues::PhaseValues( PhaseValues *ptv, const char *dummy ) : PhaseTransform( ptv, GVN ),
 672   _table(ptv->arena(),ptv->_table.size()) {
 673   NOT_PRODUCT( clear_new_values(); )
 674 }
 675 
 676 //------------------------------~PhaseValues-----------------------------------
 677 #ifndef PRODUCT
 678 PhaseValues::~PhaseValues() {
 679   _table.dump();
 680 
 681   // Statistics for value progress and efficiency
 682   if( PrintCompilation && Verbose && WizardMode ) {
 683     tty->print("\n%sValues: %d nodes ---> %d/%d (%d)",
 684       is_IterGVN() ? "Iter" : "    ", C->unique(), made_progress(), made_transforms(), made_new_values());
 685     if( made_transforms() != 0 ) {
 686       tty->print_cr("  ratio %f", made_progress()/(float)made_transforms() );
 687     } else {
 688       tty->cr();
 689     }
 690   }
 691 }
 692 #endif
 693 
 694 //------------------------------makecon----------------------------------------
 695 ConNode* PhaseTransform::makecon(const Type *t) {
 696   assert(t->singleton(), "must be a constant");
 697   assert(!t->empty() || t == Type::TOP, "must not be vacuous range");
 698   switch (t->base()) {  // fast paths
 699   case Type::Half:
 700   case Type::Top:  return (ConNode*) C->top();
 701   case Type::Int:  return intcon( t->is_int()->get_con() );
 702   case Type::Long: return longcon( t->is_long()->get_con() );
 703   default:         break;
 704   }
 705   if (t->is_zero_type())
 706     return zerocon(t->basic_type());
 707   return uncached_makecon(t);
 708 }
 709 
 710 //--------------------------uncached_makecon-----------------------------------
 711 // Make an idealized constant - one of ConINode, ConPNode, etc.
 712 ConNode* PhaseValues::uncached_makecon(const Type *t) {
 713   assert(t->singleton(), "must be a constant");
 714   ConNode* x = ConNode::make(t);
 715   ConNode* k = (ConNode*)hash_find_insert(x); // Value numbering
 716   if (k == NULL) {
 717     set_type(x, t);             // Missed, provide type mapping
 718     GrowableArray<Node_Notes*>* nna = C->node_note_array();
 719     if (nna != NULL) {
 720       Node_Notes* loc = C->locate_node_notes(nna, x->_idx, true);
 721       loc->clear(); // do not put debug info on constants
 722     }
 723   } else {
 724     x->destruct();              // Hit, destroy duplicate constant
 725     x = k;                      // use existing constant
 726   }
 727   return x;
 728 }
 729 
 730 //------------------------------intcon-----------------------------------------
 731 // Fast integer constant.  Same as "transform(new ConINode(TypeInt::make(i)))"
 732 ConINode* PhaseTransform::intcon(jint i) {
 733   // Small integer?  Check cache! Check that cached node is not dead
 734   if (i >= _icon_min && i <= _icon_max) {
 735     ConINode* icon = _icons[i-_icon_min];
 736     if (icon != NULL && icon->in(TypeFunc::Control) != NULL)
 737       return icon;
 738   }
 739   ConINode* icon = (ConINode*) uncached_makecon(TypeInt::make(i));
 740   assert(icon->is_Con(), "");
 741   if (i >= _icon_min && i <= _icon_max)
 742     _icons[i-_icon_min] = icon;   // Cache small integers
 743   return icon;
 744 }
 745 
 746 //------------------------------longcon----------------------------------------
 747 // Fast long constant.
 748 ConLNode* PhaseTransform::longcon(jlong l) {
 749   // Small integer?  Check cache! Check that cached node is not dead
 750   if (l >= _lcon_min && l <= _lcon_max) {
 751     ConLNode* lcon = _lcons[l-_lcon_min];
 752     if (lcon != NULL && lcon->in(TypeFunc::Control) != NULL)
 753       return lcon;
 754   }
 755   ConLNode* lcon = (ConLNode*) uncached_makecon(TypeLong::make(l));
 756   assert(lcon->is_Con(), "");
 757   if (l >= _lcon_min && l <= _lcon_max)
 758     _lcons[l-_lcon_min] = lcon;      // Cache small integers
 759   return lcon;
 760 }
 761 
 762 //------------------------------zerocon-----------------------------------------
 763 // Fast zero or null constant. Same as "transform(ConNode::make(Type::get_zero_type(bt)))"
 764 ConNode* PhaseTransform::zerocon(BasicType bt) {
 765   assert((uint)bt <= _zcon_max, "domain check");
 766   ConNode* zcon = _zcons[bt];
 767   if (zcon != NULL && zcon->in(TypeFunc::Control) != NULL)
 768     return zcon;
 769   zcon = (ConNode*) uncached_makecon(Type::get_zero_type(bt));
 770   _zcons[bt] = zcon;
 771   return zcon;
 772 }
 773 
 774 
 775 
 776 //=============================================================================
 777 //------------------------------transform--------------------------------------
 778 // Return a node which computes the same function as this node, but in a
 779 // faster or cheaper fashion.
 780 Node *PhaseGVN::transform( Node *n ) {
 781   return transform_no_reclaim(n);
 782 }
 783 
 784 //------------------------------transform--------------------------------------
 785 // Return a node which computes the same function as this node, but
 786 // in a faster or cheaper fashion.
 787 Node *PhaseGVN::transform_no_reclaim( Node *n ) {
 788   NOT_PRODUCT( set_transforms(); )
 789 
 790   // Apply the Ideal call in a loop until it no longer applies
 791   Node *k = n;
 792   NOT_PRODUCT( uint loop_count = 0; )
 793   while( 1 ) {
 794     Node *i = k->Ideal(this, /*can_reshape=*/false);
 795     if( !i ) break;
 796     assert( i->_idx >= k->_idx, "Idealize should return new nodes, use Identity to return old nodes" );
 797     k = i;
 798     assert(loop_count++ < K, "infinite loop in PhaseGVN::transform");
 799   }
 800   NOT_PRODUCT( if( loop_count != 0 ) { set_progress(); } )
 801 
 802 
 803   // If brand new node, make space in type array.
 804   ensure_type_or_null(k);
 805 
 806   // Since I just called 'Value' to compute the set of run-time values
 807   // for this Node, and 'Value' is non-local (and therefore expensive) I'll
 808   // cache Value.  Later requests for the local phase->type of this Node can
 809   // use the cached Value instead of suffering with 'bottom_type'.
 810   const Type *t = k->Value(this); // Get runtime Value set
 811   assert(t != NULL, "value sanity");
 812   if (type_or_null(k) != t) {
 813 #ifndef PRODUCT
 814     // Do not count initial visit to node as a transformation
 815     if (type_or_null(k) == NULL) {
 816       inc_new_values();
 817       set_progress();
 818     }
 819 #endif
 820     set_type(k, t);
 821     // If k is a TypeNode, capture any more-precise type permanently into Node
 822     k->raise_bottom_type(t);
 823   }
 824 
 825   if( t->singleton() && !k->is_Con() ) {
 826     NOT_PRODUCT( set_progress(); )
 827     return makecon(t);          // Turn into a constant
 828   }
 829 
 830   // Now check for Identities
 831   Node *i = k->Identity(this);  // Look for a nearby replacement
 832   if( i != k ) {                // Found? Return replacement!
 833     NOT_PRODUCT( set_progress(); )
 834     return i;
 835   }
 836 
 837   // Global Value Numbering
 838   i = hash_find_insert(k);      // Insert if new
 839   if( i && (i != k) ) {
 840     // Return the pre-existing node
 841     NOT_PRODUCT( set_progress(); )
 842     return i;
 843   }
 844 
 845   // Return Idealized original
 846   return k;
 847 }
 848 
 849 bool PhaseGVN::is_dominator_helper(Node *d, Node *n, bool linear_only) {
 850   if (d->is_top() || n->is_top()) {
 851     return false;
 852   }
 853   assert(d->is_CFG() && n->is_CFG(), "must have CFG nodes");
 854   int i = 0;
 855   while (d != n) {
 856     n = IfNode::up_one_dom(n, linear_only);
 857     i++;
 858     if (n == NULL || i >= 10) {
 859       return false;
 860     }
 861   }
 862   return true;
 863 }
 864 
 865 #ifdef ASSERT
 866 //------------------------------dead_loop_check--------------------------------
 867 // Check for a simple dead loop when a data node references itself directly
 868 // or through an other data node excluding cons and phis.
 869 void PhaseGVN::dead_loop_check( Node *n ) {
 870   // Phi may reference itself in a loop
 871   if (n != NULL && !n->is_dead_loop_safe() && !n->is_CFG()) {
 872     // Do 2 levels check and only data inputs.
 873     bool no_dead_loop = true;
 874     uint cnt = n->req();
 875     for (uint i = 1; i < cnt && no_dead_loop; i++) {
 876       Node *in = n->in(i);
 877       if (in == n) {
 878         no_dead_loop = false;
 879       } else if (in != NULL && !in->is_dead_loop_safe()) {
 880         uint icnt = in->req();
 881         for (uint j = 1; j < icnt && no_dead_loop; j++) {
 882           if (in->in(j) == n || in->in(j) == in)
 883             no_dead_loop = false;
 884         }
 885       }
 886     }
 887     if (!no_dead_loop) n->dump(3);
 888     assert(no_dead_loop, "dead loop detected");
 889   }
 890 }
 891 #endif
 892 
 893 //=============================================================================
 894 //------------------------------PhaseIterGVN-----------------------------------
 895 // Initialize hash table to fresh and clean for +VerifyOpto
 896 PhaseIterGVN::PhaseIterGVN( PhaseIterGVN *igvn, const char *dummy ) : PhaseGVN(igvn,dummy), _worklist( ),
 897                                                                       _stack(C->live_nodes() >> 1),
 898                                                                       _delay_transform(false) {
 899 }
 900 
 901 //------------------------------PhaseIterGVN-----------------------------------
 902 // Initialize with previous PhaseIterGVN info; used by PhaseCCP
 903 PhaseIterGVN::PhaseIterGVN( PhaseIterGVN *igvn ) : PhaseGVN(igvn),
 904                                                    _worklist( igvn->_worklist ),
 905                                                    _stack( igvn->_stack ),
 906                                                    _delay_transform(igvn->_delay_transform)
 907 {
 908 }
 909 
 910 //------------------------------PhaseIterGVN-----------------------------------
 911 // Initialize with previous PhaseGVN info from Parser
 912 PhaseIterGVN::PhaseIterGVN( PhaseGVN *gvn ) : PhaseGVN(gvn),
 913                                               _worklist(*C->for_igvn()),
 914 // TODO: Before incremental inlining it was allocated only once and it was fine. Now that
 915 //       the constructor is used in incremental inlining, this consumes too much memory:
 916 //                                            _stack(C->live_nodes() >> 1),
 917 //       So, as a band-aid, we replace this by:
 918                                               _stack(C->comp_arena(), 32),
 919                                               _delay_transform(false)
 920 {
 921   uint max;
 922 
 923   // Dead nodes in the hash table inherited from GVN were not treated as
 924   // roots during def-use info creation; hence they represent an invisible
 925   // use.  Clear them out.
 926   max = _table.size();
 927   for( uint i = 0; i < max; ++i ) {
 928     Node *n = _table.at(i);
 929     if(n != NULL && n != _table.sentinel() && n->outcnt() == 0) {
 930       if( n->is_top() ) continue;
 931       assert( false, "Parse::remove_useless_nodes missed this node");
 932       hash_delete(n);
 933     }
 934   }
 935 
 936   // Any Phis or Regions on the worklist probably had uses that could not
 937   // make more progress because the uses were made while the Phis and Regions
 938   // were in half-built states.  Put all uses of Phis and Regions on worklist.
 939   max = _worklist.size();
 940   for( uint j = 0; j < max; j++ ) {
 941     Node *n = _worklist.at(j);
 942     uint uop = n->Opcode();
 943     if( uop == Op_Phi || uop == Op_Region ||
 944         n->is_Type() ||
 945         n->is_Mem() )
 946       add_users_to_worklist(n);
 947   }
 948 
 949   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 950   bs->add_users_to_worklist(&_worklist);
 951 }
 952 
 953 /**
 954  * Initialize worklist for each node.
 955  */
 956 void PhaseIterGVN::init_worklist(Node* first) {
 957   Unique_Node_List to_process;
 958   to_process.push(first);
 959 
 960   while (to_process.size() > 0) {
 961     Node* n = to_process.pop();
 962     if (!_worklist.member(n)) {
 963       _worklist.push(n);
 964 
 965       uint cnt = n->req();
 966       for(uint i = 0; i < cnt; i++) {
 967         Node* m = n->in(i);
 968         if (m != NULL) {
 969           to_process.push(m);
 970         }
 971       }
 972     }
 973   }
 974 }
 975 
 976 #ifndef PRODUCT
 977 void PhaseIterGVN::verify_step(Node* n) {
 978   if (VerifyIterativeGVN) {
 979     _verify_window[_verify_counter % _verify_window_size] = n;
 980     ++_verify_counter;
 981     ResourceMark rm;
 982     ResourceArea* area = Thread::current()->resource_area();
 983     VectorSet old_space(area), new_space(area);
 984     if (C->unique() < 1000 ||
 985         0 == _verify_counter % (C->unique() < 10000 ? 10 : 100)) {
 986       ++_verify_full_passes;
 987       Node::verify_recur(C->root(), -1, old_space, new_space);
 988     }
 989     const int verify_depth = 4;
 990     for ( int i = 0; i < _verify_window_size; i++ ) {
 991       Node* n = _verify_window[i];
 992       if ( n == NULL )  continue;
 993       if( n->in(0) == NodeSentinel ) {  // xform_idom
 994         _verify_window[i] = n->in(1);
 995         --i; continue;
 996       }
 997       // Typical fanout is 1-2, so this call visits about 6 nodes.
 998       Node::verify_recur(n, verify_depth, old_space, new_space);
 999     }
1000   }
1001 }
1002 
1003 void PhaseIterGVN::trace_PhaseIterGVN(Node* n, Node* nn, const Type* oldtype) {
1004   if (TraceIterativeGVN) {
1005     uint wlsize = _worklist.size();
1006     const Type* newtype = type_or_null(n);
1007     if (nn != n) {
1008       // print old node
1009       tty->print("< ");
1010       if (oldtype != newtype && oldtype != NULL) {
1011         oldtype->dump();
1012       }
1013       do { tty->print("\t"); } while (tty->position() < 16);
1014       tty->print("<");
1015       n->dump();
1016     }
1017     if (oldtype != newtype || nn != n) {
1018       // print new node and/or new type
1019       if (oldtype == NULL) {
1020         tty->print("* ");
1021       } else if (nn != n) {
1022         tty->print("> ");
1023       } else {
1024         tty->print("= ");
1025       }
1026       if (newtype == NULL) {
1027         tty->print("null");
1028       } else {
1029         newtype->dump();
1030       }
1031       do { tty->print("\t"); } while (tty->position() < 16);
1032       nn->dump();
1033     }
1034     if (Verbose && wlsize < _worklist.size()) {
1035       tty->print("  Push {");
1036       while (wlsize != _worklist.size()) {
1037         Node* pushed = _worklist.at(wlsize++);
1038         tty->print(" %d", pushed->_idx);
1039       }
1040       tty->print_cr(" }");
1041     }
1042     if (nn != n) {
1043       // ignore n, it might be subsumed
1044       verify_step((Node*) NULL);
1045     }
1046   }
1047 }
1048 
1049 void PhaseIterGVN::init_verifyPhaseIterGVN() {
1050   _verify_counter = 0;
1051   _verify_full_passes = 0;
1052   for (int i = 0; i < _verify_window_size; i++) {
1053     _verify_window[i] = NULL;
1054   }
1055 #ifdef ASSERT
1056   // Verify that all modified nodes are on _worklist
1057   Unique_Node_List* modified_list = C->modified_nodes();
1058   while (modified_list != NULL && modified_list->size()) {
1059     Node* n = modified_list->pop();
1060     if (n->outcnt() != 0 && !n->is_Con() && !_worklist.member(n)) {
1061       n->dump();
1062       assert(false, "modified node is not on IGVN._worklist");
1063     }
1064   }
1065 #endif
1066 }
1067 
1068 void PhaseIterGVN::verify_PhaseIterGVN() {
1069 #ifdef ASSERT
1070   // Verify nodes with changed inputs.
1071   Unique_Node_List* modified_list = C->modified_nodes();
1072   while (modified_list != NULL && modified_list->size()) {
1073     Node* n = modified_list->pop();
1074     if (n->outcnt() != 0 && !n->is_Con()) { // skip dead and Con nodes
1075       n->dump();
1076       assert(false, "modified node was not processed by IGVN.transform_old()");
1077     }
1078   }
1079 #endif
1080 
1081   C->verify_graph_edges();
1082   if( VerifyOpto && allow_progress() ) {
1083     // Must turn off allow_progress to enable assert and break recursion
1084     C->root()->verify();
1085     { // Check if any progress was missed using IterGVN
1086       // Def-Use info enables transformations not attempted in wash-pass
1087       // e.g. Region/Phi cleanup, ...
1088       // Null-check elision -- may not have reached fixpoint
1089       //                       do not propagate to dominated nodes
1090       ResourceMark rm;
1091       PhaseIterGVN igvn2(this,"Verify"); // Fresh and clean!
1092       // Fill worklist completely
1093       igvn2.init_worklist(C->root());
1094 
1095       igvn2.set_allow_progress(false);
1096       igvn2.optimize();
1097       igvn2.set_allow_progress(true);
1098     }
1099   }
1100   if (VerifyIterativeGVN && PrintOpto) {
1101     if (_verify_counter == _verify_full_passes) {
1102       tty->print_cr("VerifyIterativeGVN: %d transforms and verify passes",
1103                     (int) _verify_full_passes);
1104     } else {
1105       tty->print_cr("VerifyIterativeGVN: %d transforms, %d full verify passes",
1106                   (int) _verify_counter, (int) _verify_full_passes);
1107     }
1108   }
1109 
1110 #ifdef ASSERT
1111   while (modified_list->size()) {
1112     Node* n = modified_list->pop();
1113     n->dump();
1114     assert(false, "VerifyIterativeGVN: new modified node was added");
1115   }
1116 #endif
1117 }
1118 #endif /* PRODUCT */
1119 
1120 #ifdef ASSERT
1121 /**
1122  * Dumps information that can help to debug the problem. A debug
1123  * build fails with an assert.
1124  */
1125 void PhaseIterGVN::dump_infinite_loop_info(Node* n) {
1126   n->dump(4);
1127   _worklist.dump();
1128   assert(false, "infinite loop in PhaseIterGVN::optimize");
1129 }
1130 
1131 /**
1132  * Prints out information about IGVN if the 'verbose' option is used.
1133  */
1134 void PhaseIterGVN::trace_PhaseIterGVN_verbose(Node* n, int num_processed) {
1135   if (TraceIterativeGVN && Verbose) {
1136     tty->print("  Pop ");
1137     n->dump();
1138     if ((num_processed % 100) == 0) {
1139       _worklist.print_set();
1140     }
1141   }
1142 }
1143 #endif /* ASSERT */
1144 
1145 void PhaseIterGVN::optimize() {
1146   DEBUG_ONLY(uint num_processed  = 0;)
1147   NOT_PRODUCT(init_verifyPhaseIterGVN();)
1148 
1149   uint loop_count = 0;
1150   // Pull from worklist and transform the node. If the node has changed,
1151   // update edge info and put uses on worklist.
1152   while(_worklist.size()) {
1153     if (C->check_node_count(NodeLimitFudgeFactor * 2, "Out of nodes")) {
1154       return;
1155     }
1156     Node* n  = _worklist.pop();
1157     if (++loop_count >= K * C->live_nodes()) {
1158       DEBUG_ONLY(dump_infinite_loop_info(n);)
1159       C->record_method_not_compilable("infinite loop in PhaseIterGVN::optimize");
1160       return;
1161     }
1162     DEBUG_ONLY(trace_PhaseIterGVN_verbose(n, num_processed++);)
1163     if (n->outcnt() != 0) {
1164       NOT_PRODUCT(const Type* oldtype = type_or_null(n));
1165       // Do the transformation
1166       Node* nn = transform_old(n);
1167       NOT_PRODUCT(trace_PhaseIterGVN(n, nn, oldtype);)
1168     } else if (!n->is_top()) {
1169       remove_dead_node(n);
1170     }
1171   }
1172   NOT_PRODUCT(verify_PhaseIterGVN();)
1173 }
1174 
1175 
1176 /**
1177  * Register a new node with the optimizer.  Update the types array, the def-use
1178  * info.  Put on worklist.
1179  */
1180 Node* PhaseIterGVN::register_new_node_with_optimizer(Node* n, Node* orig) {
1181   set_type_bottom(n);
1182   _worklist.push(n);
1183   if (orig != NULL)  C->copy_node_notes_to(n, orig);
1184   return n;
1185 }
1186 
1187 //------------------------------transform--------------------------------------
1188 // Non-recursive: idealize Node 'n' with respect to its inputs and its value
1189 Node *PhaseIterGVN::transform( Node *n ) {
1190   if (_delay_transform) {
1191     // Register the node but don't optimize for now
1192     register_new_node_with_optimizer(n);
1193     return n;
1194   }
1195 
1196   // If brand new node, make space in type array, and give it a type.
1197   ensure_type_or_null(n);
1198   if (type_or_null(n) == NULL) {
1199     set_type_bottom(n);
1200   }
1201 
1202   return transform_old(n);
1203 }
1204 
1205 Node *PhaseIterGVN::transform_old(Node* n) {
1206   DEBUG_ONLY(uint loop_count = 0;);
1207   NOT_PRODUCT(set_transforms());
1208 
1209   // Remove 'n' from hash table in case it gets modified
1210   _table.hash_delete(n);
1211   if (VerifyIterativeGVN) {
1212    assert(!_table.find_index(n->_idx), "found duplicate entry in table");
1213   }
1214 
1215   // Apply the Ideal call in a loop until it no longer applies
1216   Node* k = n;
1217   DEBUG_ONLY(dead_loop_check(k);)
1218   DEBUG_ONLY(bool is_new = (k->outcnt() == 0);)
1219   C->remove_modified_node(k);
1220   Node* i = k->Ideal(this, /*can_reshape=*/true);
1221   assert(i != k || is_new || i->outcnt() > 0, "don't return dead nodes");
1222 #ifndef PRODUCT
1223   verify_step(k);
1224   if (i && VerifyOpto ) {
1225     if (!allow_progress()) {
1226       if (i->is_Add() && (i->outcnt() == 1)) {
1227         // Switched input to left side because this is the only use
1228       } else if (i->is_If() && (i->in(0) == NULL)) {
1229         // This IF is dead because it is dominated by an equivalent IF When
1230         // dominating if changed, info is not propagated sparsely to 'this'
1231         // Propagating this info further will spuriously identify other
1232         // progress.
1233         return i;
1234       } else
1235         set_progress();
1236     } else {
1237       set_progress();
1238     }
1239   }
1240 #endif
1241 
1242   while (i != NULL) {
1243 #ifdef ASSERT
1244     if (loop_count >= K) {
1245       dump_infinite_loop_info(i);
1246     }
1247     loop_count++;
1248 #endif
1249     assert((i->_idx >= k->_idx) || i->is_top(), "Idealize should return new nodes, use Identity to return old nodes");
1250     // Made a change; put users of original Node on worklist
1251     add_users_to_worklist(k);
1252     // Replacing root of transform tree?
1253     if (k != i) {
1254       // Make users of old Node now use new.
1255       subsume_node(k, i);
1256       k = i;
1257     }
1258     DEBUG_ONLY(dead_loop_check(k);)
1259     // Try idealizing again
1260     DEBUG_ONLY(is_new = (k->outcnt() == 0);)
1261     C->remove_modified_node(k);
1262     i = k->Ideal(this, /*can_reshape=*/true);
1263     assert(i != k || is_new || (i->outcnt() > 0), "don't return dead nodes");
1264 #ifndef PRODUCT
1265     verify_step(k);
1266     if (i && VerifyOpto) {
1267       set_progress();
1268     }
1269 #endif
1270   }
1271 
1272   // If brand new node, make space in type array.
1273   ensure_type_or_null(k);
1274 
1275   // See what kind of values 'k' takes on at runtime
1276   const Type* t = k->Value(this);
1277   assert(t != NULL, "value sanity");
1278 
1279   // Since I just called 'Value' to compute the set of run-time values
1280   // for this Node, and 'Value' is non-local (and therefore expensive) I'll
1281   // cache Value.  Later requests for the local phase->type of this Node can
1282   // use the cached Value instead of suffering with 'bottom_type'.
1283   if (type_or_null(k) != t) {
1284 #ifndef PRODUCT
1285     inc_new_values();
1286     set_progress();
1287 #endif
1288     set_type(k, t);
1289     // If k is a TypeNode, capture any more-precise type permanently into Node
1290     k->raise_bottom_type(t);
1291     // Move users of node to worklist
1292     add_users_to_worklist(k);
1293   }
1294   // If 'k' computes a constant, replace it with a constant
1295   if (t->singleton() && !k->is_Con()) {
1296     NOT_PRODUCT(set_progress();)
1297     Node* con = makecon(t);     // Make a constant
1298     add_users_to_worklist(k);
1299     subsume_node(k, con);       // Everybody using k now uses con
1300     return con;
1301   }
1302 
1303   // Now check for Identities
1304   i = k->Identity(this);      // Look for a nearby replacement
1305   if (i != k) {                // Found? Return replacement!
1306     NOT_PRODUCT(set_progress();)
1307     add_users_to_worklist(k);
1308     subsume_node(k, i);       // Everybody using k now uses i
1309     return i;
1310   }
1311 
1312   // Global Value Numbering
1313   i = hash_find_insert(k);      // Check for pre-existing node
1314   if (i && (i != k)) {
1315     // Return the pre-existing node if it isn't dead
1316     NOT_PRODUCT(set_progress();)
1317     add_users_to_worklist(k);
1318     subsume_node(k, i);       // Everybody using k now uses i
1319     return i;
1320   }
1321 
1322   // Return Idealized original
1323   return k;
1324 }
1325 
1326 //---------------------------------saturate------------------------------------
1327 const Type* PhaseIterGVN::saturate(const Type* new_type, const Type* old_type,
1328                                    const Type* limit_type) const {
1329   return new_type->narrow(old_type);
1330 }
1331 
1332 //------------------------------remove_globally_dead_node----------------------
1333 // Kill a globally dead Node.  All uses are also globally dead and are
1334 // aggressively trimmed.
1335 void PhaseIterGVN::remove_globally_dead_node( Node *dead ) {
1336   enum DeleteProgress {
1337     PROCESS_INPUTS,
1338     PROCESS_OUTPUTS
1339   };
1340   assert(_stack.is_empty(), "not empty");
1341   _stack.push(dead, PROCESS_INPUTS);
1342 
1343   while (_stack.is_nonempty()) {
1344     dead = _stack.node();
1345     uint progress_state = _stack.index();
1346     assert(dead != C->root(), "killing root, eh?");
1347     assert(!dead->is_top(), "add check for top when pushing");
1348     NOT_PRODUCT( set_progress(); )
1349     if (progress_state == PROCESS_INPUTS) {
1350       // After following inputs, continue to outputs
1351       _stack.set_index(PROCESS_OUTPUTS);
1352       if (!dead->is_Con()) { // Don't kill cons but uses
1353         bool recurse = false;
1354         // Remove from hash table
1355         _table.hash_delete( dead );
1356         // Smash all inputs to 'dead', isolating him completely
1357         for (uint i = 0; i < dead->req(); i++) {
1358           Node *in = dead->in(i);
1359           if (in != NULL && in != C->top()) {  // Points to something?
1360             int nrep = dead->replace_edge(in, NULL);  // Kill edges
1361             assert((nrep > 0), "sanity");
1362             if (in->outcnt() == 0) { // Made input go dead?
1363               _stack.push(in, PROCESS_INPUTS); // Recursively remove
1364               recurse = true;
1365             } else if (in->outcnt() == 1 &&
1366                        in->has_special_unique_user()) {
1367               _worklist.push(in->unique_out());
1368             } else if (in->outcnt() <= 2 && dead->is_Phi()) {
1369               if (in->Opcode() == Op_Region) {
1370                 _worklist.push(in);
1371               } else if (in->is_Store()) {
1372                 DUIterator_Fast imax, i = in->fast_outs(imax);
1373                 _worklist.push(in->fast_out(i));
1374                 i++;
1375                 if (in->outcnt() == 2) {
1376                   _worklist.push(in->fast_out(i));
1377                   i++;
1378                 }
1379                 assert(!(i < imax), "sanity");
1380               }
1381             } else if (dead->Opcode() == Op_ShenandoahWBMemProj) {
1382               assert(i == 1 && in->Opcode() == Op_ShenandoahWriteBarrier, "broken graph");
1383               _worklist.push(in);
1384 #if INCLUDE_SHENANDOAHGC
1385             // TODO: Move into below call to enqueue_useful_gc_barrier()
1386             } else if (in->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(in)) {
1387               add_users_to_worklist(in);
1388 #endif
1389             } else {
1390               BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(_worklist, in);
1391             }
1392             if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory &&
1393                 in->is_Proj() && in->in(0) != NULL && in->in(0)->is_Initialize()) {
1394               // A Load that directly follows an InitializeNode is
1395               // going away. The Stores that follow are candidates
1396               // again to be captured by the InitializeNode.
1397               for (DUIterator_Fast jmax, j = in->fast_outs(jmax); j < jmax; j++) {
1398                 Node *n = in->fast_out(j);
1399                 if (n->is_Store()) {
1400                   _worklist.push(n);
1401                 }
1402               }
1403             }
1404           } // if (in != NULL && in != C->top())
1405         } // for (uint i = 0; i < dead->req(); i++)
1406         if (recurse) {
1407           continue;
1408         }
1409       } // if (!dead->is_Con())
1410     } // if (progress_state == PROCESS_INPUTS)
1411 
1412     // Aggressively kill globally dead uses
1413     // (Rather than pushing all the outs at once, we push one at a time,
1414     // plus the parent to resume later, because of the indefinite number
1415     // of edge deletions per loop trip.)
1416     if (dead->outcnt() > 0) {
1417       // Recursively remove output edges
1418       _stack.push(dead->raw_out(0), PROCESS_INPUTS);
1419     } else {
1420       // Finished disconnecting all input and output edges.
1421       _stack.pop();
1422       // Remove dead node from iterative worklist
1423       _worklist.remove(dead);
1424       C->remove_modified_node(dead);
1425       // Constant node that has no out-edges and has only one in-edge from
1426       // root is usually dead. However, sometimes reshaping walk makes
1427       // it reachable by adding use edges. So, we will NOT count Con nodes
1428       // as dead to be conservative about the dead node count at any
1429       // given time.
1430       if (!dead->is_Con()) {
1431         C->record_dead_node(dead->_idx);
1432       }
1433       if (dead->is_macro()) {
1434         C->remove_macro_node(dead);
1435       }
1436       if (dead->is_expensive()) {
1437         C->remove_expensive_node(dead);
1438       }
1439       CastIINode* cast = dead->isa_CastII();
1440       if (cast != NULL && cast->has_range_check()) {
1441         C->remove_range_check_cast(cast);
1442       }
1443       if (dead->Opcode() == Op_Opaque4) {
1444         C->remove_opaque4_node(dead);
1445       }
1446       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1447       bs->unregister_potential_barrier_node(dead);
1448     }
1449   } // while (_stack.is_nonempty())
1450 }
1451 
1452 //------------------------------subsume_node-----------------------------------
1453 // Remove users from node 'old' and add them to node 'nn'.
1454 void PhaseIterGVN::subsume_node( Node *old, Node *nn ) {
1455   assert( old != hash_find(old), "should already been removed" );
1456   assert( old != C->top(), "cannot subsume top node");
1457   // Copy debug or profile information to the new version:
1458   C->copy_node_notes_to(nn, old);
1459   // Move users of node 'old' to node 'nn'
1460   for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
1461     Node* use = old->last_out(i);  // for each use...
1462     // use might need re-hashing (but it won't if it's a new node)
1463     rehash_node_delayed(use);
1464     // Update use-def info as well
1465     // We remove all occurrences of old within use->in,
1466     // so as to avoid rehashing any node more than once.
1467     // The hash table probe swamps any outer loop overhead.
1468     uint num_edges = 0;
1469     for (uint jmax = use->len(), j = 0; j < jmax; j++) {
1470       if (use->in(j) == old) {
1471         use->set_req(j, nn);
1472         ++num_edges;
1473       }
1474     }
1475     i -= num_edges;    // we deleted 1 or more copies of this edge
1476   }
1477 
1478   // Search for instance field data PhiNodes in the same region pointing to the old
1479   // memory PhiNode and update their instance memory ids to point to the new node.
1480   if (old->is_Phi() && old->as_Phi()->type()->has_memory() && old->in(0) != NULL) {
1481     Node* region = old->in(0);
1482     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1483       PhiNode* phi = region->fast_out(i)->isa_Phi();
1484       if (phi != NULL && phi->inst_mem_id() == (int)old->_idx) {
1485         phi->set_inst_mem_id((int)nn->_idx);
1486       }
1487     }
1488   }
1489 
1490   // Smash all inputs to 'old', isolating him completely
1491   Node *temp = new Node(1);
1492   temp->init_req(0,nn);     // Add a use to nn to prevent him from dying
1493   remove_dead_node( old );
1494   temp->del_req(0);         // Yank bogus edge
1495 #ifndef PRODUCT
1496   if( VerifyIterativeGVN ) {
1497     for ( int i = 0; i < _verify_window_size; i++ ) {
1498       if ( _verify_window[i] == old )
1499         _verify_window[i] = nn;
1500     }
1501   }
1502 #endif
1503   _worklist.remove(temp);   // this can be necessary
1504   temp->destruct();         // reuse the _idx of this little guy
1505 }
1506 
1507 //------------------------------add_users_to_worklist--------------------------
1508 void PhaseIterGVN::add_users_to_worklist0( Node *n ) {
1509   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1510     _worklist.push(n->fast_out(i));  // Push on worklist
1511   }
1512 }
1513 
1514 // Return counted loop Phi if as a counted loop exit condition, cmp
1515 // compares the the induction variable with n
1516 static PhiNode* countedloop_phi_from_cmp(CmpINode* cmp, Node* n) {
1517   for (DUIterator_Fast imax, i = cmp->fast_outs(imax); i < imax; i++) {
1518     Node* bol = cmp->fast_out(i);
1519     for (DUIterator_Fast i2max, i2 = bol->fast_outs(i2max); i2 < i2max; i2++) {
1520       Node* iff = bol->fast_out(i2);
1521       if (iff->is_CountedLoopEnd()) {
1522         CountedLoopEndNode* cle = iff->as_CountedLoopEnd();
1523         if (cle->limit() == n) {
1524           PhiNode* phi = cle->phi();
1525           if (phi != NULL) {
1526             return phi;
1527           }
1528         }
1529       }
1530     }
1531   }
1532   return NULL;
1533 }
1534 
1535 void PhaseIterGVN::add_users_to_worklist( Node *n ) {
1536   add_users_to_worklist0(n);
1537 
1538   // Move users of node to worklist
1539   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1540     Node* use = n->fast_out(i); // Get use
1541 
1542     if( use->is_Multi() ||      // Multi-definer?  Push projs on worklist
1543         use->is_Store() )       // Enable store/load same address
1544       add_users_to_worklist0(use);
1545 
1546     // If we changed the receiver type to a call, we need to revisit
1547     // the Catch following the call.  It's looking for a non-NULL
1548     // receiver to know when to enable the regular fall-through path
1549     // in addition to the NullPtrException path.
1550     if (use->is_CallDynamicJava() && n == use->in(TypeFunc::Parms)) {
1551       Node* p = use->as_CallDynamicJava()->proj_out_or_null(TypeFunc::Control);
1552       if (p != NULL) {
1553         add_users_to_worklist0(p);
1554       }
1555     }
1556 
1557     uint use_op = use->Opcode();
1558     if(use->is_Cmp()) {       // Enable CMP/BOOL optimization
1559       add_users_to_worklist(use); // Put Bool on worklist
1560       if (use->outcnt() > 0) {
1561         Node* bol = use->raw_out(0);
1562         if (bol->outcnt() > 0) {
1563           Node* iff = bol->raw_out(0);
1564           if (iff->outcnt() == 2) {
1565             // Look for the 'is_x2logic' pattern: "x ? : 0 : 1" and put the
1566             // phi merging either 0 or 1 onto the worklist
1567             Node* ifproj0 = iff->raw_out(0);
1568             Node* ifproj1 = iff->raw_out(1);
1569             if (ifproj0->outcnt() > 0 && ifproj1->outcnt() > 0) {
1570               Node* region0 = ifproj0->raw_out(0);
1571               Node* region1 = ifproj1->raw_out(0);
1572               if( region0 == region1 )
1573                 add_users_to_worklist0(region0);
1574             }
1575           }
1576         }
1577       }
1578       if (use_op == Op_CmpI) {
1579         Node* phi = countedloop_phi_from_cmp((CmpINode*)use, n);
1580         if (phi != NULL) {
1581           // If an opaque node feeds into the limit condition of a
1582           // CountedLoop, we need to process the Phi node for the
1583           // induction variable when the opaque node is removed:
1584           // the range of values taken by the Phi is now known and
1585           // so its type is also known.
1586           _worklist.push(phi);
1587         }
1588         Node* in1 = use->in(1);
1589         for (uint i = 0; i < in1->outcnt(); i++) {
1590           if (in1->raw_out(i)->Opcode() == Op_CastII) {
1591             Node* castii = in1->raw_out(i);
1592             if (castii->in(0) != NULL && castii->in(0)->in(0) != NULL && castii->in(0)->in(0)->is_If()) {
1593               Node* ifnode = castii->in(0)->in(0);
1594               if (ifnode->in(1) != NULL && ifnode->in(1)->is_Bool() && ifnode->in(1)->in(1) == use) {
1595                 // Reprocess a CastII node that may depend on an
1596                 // opaque node value when the opaque node is
1597                 // removed. In case it carries a dependency we can do
1598                 // a better job of computing its type.
1599                 _worklist.push(castii);
1600               }
1601             }
1602           }
1603         }
1604       }
1605     }
1606 
1607     // If changed Cast input, check Phi users for simple cycles
1608     if (use->is_ConstraintCast()) {
1609       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1610         Node* u = use->fast_out(i2);
1611         if (u->is_Phi())
1612           _worklist.push(u);
1613       }
1614     }
1615     // If changed LShift inputs, check RShift users for useless sign-ext
1616     if( use_op == Op_LShiftI ) {
1617       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1618         Node* u = use->fast_out(i2);
1619         if (u->Opcode() == Op_RShiftI)
1620           _worklist.push(u);
1621       }
1622     }
1623     // If changed AddI/SubI inputs, check CmpU for range check optimization.
1624     if (use_op == Op_AddI || use_op == Op_SubI) {
1625       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1626         Node* u = use->fast_out(i2);
1627         if (u->is_Cmp() && (u->Opcode() == Op_CmpU)) {
1628           _worklist.push(u);
1629         }
1630       }
1631     }
1632     // If changed AddP inputs, check Stores for loop invariant
1633     if( use_op == Op_AddP ) {
1634       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1635         Node* u = use->fast_out(i2);
1636         if (u->is_Mem())
1637           _worklist.push(u);
1638       }
1639     }
1640     // If changed initialization activity, check dependent Stores
1641     if (use_op == Op_Allocate || use_op == Op_AllocateArray) {
1642       InitializeNode* init = use->as_Allocate()->initialization();
1643       if (init != NULL) {
1644         Node* imem = init->proj_out_or_null(TypeFunc::Memory);
1645         if (imem != NULL)  add_users_to_worklist0(imem);
1646       }
1647     }
1648     if (use_op == Op_Initialize) {
1649       Node* imem = use->as_Initialize()->proj_out_or_null(TypeFunc::Memory);
1650       if (imem != NULL)  add_users_to_worklist0(imem);
1651     }
1652     // Loading the java mirror from a Klass requires two loads and the type
1653     // of the mirror load depends on the type of 'n'. See LoadNode::Value().
1654     // If the code pattern requires a barrier for
1655     //   mirror = ((OopHandle)mirror)->resolve();
1656     // this won't match.
1657     if (use_op == Op_LoadP && use->bottom_type()->isa_rawptr()) {
1658       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1659         Node* u = use->fast_out(i2);
1660         const Type* ut = u->bottom_type();
1661         if (u->Opcode() == Op_LoadP && ut->isa_instptr()) {
1662           _worklist.push(u);
1663         }
1664       }
1665     }
1666 
1667     if (use->is_ShenandoahBarrier()) {
1668       Node* cmp = use->find_out_with(Op_CmpP);
1669       if (cmp != NULL) {
1670         _worklist.push(cmp);
1671       }
1672     }
1673   }
1674 }
1675 
1676 /**
1677  * Remove the speculative part of all types that we know of
1678  */
1679 void PhaseIterGVN::remove_speculative_types()  {
1680   assert(UseTypeSpeculation, "speculation is off");
1681   for (uint i = 0; i < _types.Size(); i++)  {
1682     const Type* t = _types.fast_lookup(i);
1683     if (t != NULL) {
1684       _types.map(i, t->remove_speculative());
1685     }
1686   }
1687   _table.check_no_speculative_types();
1688 }
1689 
1690 //=============================================================================
1691 #ifndef PRODUCT
1692 uint PhaseCCP::_total_invokes   = 0;
1693 uint PhaseCCP::_total_constants = 0;
1694 #endif
1695 //------------------------------PhaseCCP---------------------------------------
1696 // Conditional Constant Propagation, ala Wegman & Zadeck
1697 PhaseCCP::PhaseCCP( PhaseIterGVN *igvn ) : PhaseIterGVN(igvn) {
1698   NOT_PRODUCT( clear_constants(); )
1699   assert( _worklist.size() == 0, "" );
1700   // Clear out _nodes from IterGVN.  Must be clear to transform call.
1701   _nodes.clear();               // Clear out from IterGVN
1702   analyze();
1703 }
1704 
1705 #ifndef PRODUCT
1706 //------------------------------~PhaseCCP--------------------------------------
1707 PhaseCCP::~PhaseCCP() {
1708   inc_invokes();
1709   _total_constants += count_constants();
1710 }
1711 #endif
1712 
1713 
1714 #ifdef ASSERT
1715 static bool ccp_type_widens(const Type* t, const Type* t0) {
1716   assert(t->meet(t0) == t, "Not monotonic");
1717   switch (t->base() == t0->base() ? t->base() : Type::Top) {
1718   case Type::Int:
1719     assert(t0->isa_int()->_widen <= t->isa_int()->_widen, "widen increases");
1720     break;
1721   case Type::Long:
1722     assert(t0->isa_long()->_widen <= t->isa_long()->_widen, "widen increases");
1723     break;
1724   default:
1725     break;
1726   }
1727   return true;
1728 }
1729 #endif //ASSERT
1730 
1731 //------------------------------analyze----------------------------------------
1732 void PhaseCCP::analyze() {
1733   // Initialize all types to TOP, optimistic analysis
1734   for (int i = C->unique() - 1; i >= 0; i--)  {
1735     _types.map(i,Type::TOP);
1736   }
1737 
1738   // Push root onto worklist
1739   Unique_Node_List worklist;
1740   worklist.push(C->root());
1741 
1742   // Pull from worklist; compute new value; push changes out.
1743   // This loop is the meat of CCP.
1744   while( worklist.size() ) {
1745     Node *n = worklist.pop();
1746     const Type *t = n->Value(this);
1747     if (t != type(n)) {
1748       assert(ccp_type_widens(t, type(n)), "ccp type must widen");
1749 #ifndef PRODUCT
1750       if( TracePhaseCCP ) {
1751         t->dump();
1752         do { tty->print("\t"); } while (tty->position() < 16);
1753         n->dump();
1754       }
1755 #endif
1756       set_type(n, t);
1757       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1758         Node* m = n->fast_out(i);   // Get user
1759         if (m->is_Region()) {  // New path to Region?  Must recheck Phis too
1760           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1761             Node* p = m->fast_out(i2); // Propagate changes to uses
1762             if (p->bottom_type() != type(p)) { // If not already bottomed out
1763               worklist.push(p); // Propagate change to user
1764             }
1765           }
1766         }
1767         // If we changed the receiver type to a call, we need to revisit
1768         // the Catch following the call.  It's looking for a non-NULL
1769         // receiver to know when to enable the regular fall-through path
1770         // in addition to the NullPtrException path
1771         if (m->is_Call()) {
1772           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1773             Node* p = m->fast_out(i2);  // Propagate changes to uses
1774             if (p->is_Proj() && p->as_Proj()->_con == TypeFunc::Control && p->outcnt() == 1) {
1775               worklist.push(p->unique_out());
1776             }
1777           }
1778         }
1779         if (m->bottom_type() != type(m)) { // If not already bottomed out
1780           worklist.push(m);     // Propagate change to user
1781         }
1782 
1783         // CmpU nodes can get their type information from two nodes up in the
1784         // graph (instead of from the nodes immediately above). Make sure they
1785         // are added to the worklist if nodes they depend on are updated, since
1786         // they could be missed and get wrong types otherwise.
1787         uint m_op = m->Opcode();
1788         if (m_op == Op_AddI || m_op == Op_SubI) {
1789           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1790             Node* p = m->fast_out(i2); // Propagate changes to uses
1791             if (p->Opcode() == Op_CmpU) {
1792               // Got a CmpU which might need the new type information from node n.
1793               if(p->bottom_type() != type(p)) { // If not already bottomed out
1794                 worklist.push(p); // Propagate change to user
1795               }
1796             }
1797           }
1798         }
1799         // If n is used in a counted loop exit condition then the type
1800         // of the counted loop's Phi depends on the type of n. See
1801         // PhiNode::Value().
1802         if (m_op == Op_CmpI) {
1803           PhiNode* phi = countedloop_phi_from_cmp((CmpINode*)m, n);
1804           if (phi != NULL) {
1805             worklist.push(phi);
1806           }
1807         }
1808         // Loading the java mirror from a Klass requires two loads and the type
1809         // of the mirror load depends on the type of 'n'. See LoadNode::Value().
1810         // If the code pattern requires a barrier for
1811         //   mirror = ((OopHandle)mirror)->resolve();
1812         // this won't match.
1813         if (m_op == Op_LoadP && m->bottom_type()->isa_rawptr()) {
1814           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1815             Node* u = m->fast_out(i2);
1816             const Type* ut = u->bottom_type();
1817             if (u->Opcode() == Op_LoadP && ut->isa_instptr() && ut != type(u)) {
1818               worklist.push(u);
1819             }
1820           }
1821         }
1822         if (m->is_ShenandoahBarrier()) {
1823           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1824             Node* p = m->fast_out(i2);
1825             if (p->Opcode() == Op_CmpP) {
1826               if(p->bottom_type() != type(p)) {
1827                 worklist.push(p);
1828               }
1829             } else if (p->Opcode() == Op_AddP) {
1830               for (DUIterator_Fast i3max, i3 = p->fast_outs(i3max); i3 < i3max; i3++) {
1831                 Node* q = p->fast_out(i3);
1832                 if (q->is_Load()) {
1833                   if(q->bottom_type() != type(q)) {
1834                     worklist.push(q);
1835                   }
1836                 }
1837               }
1838             }
1839           }
1840         }
1841       }
1842     }
1843   }
1844 }
1845 
1846 //------------------------------do_transform-----------------------------------
1847 // Top level driver for the recursive transformer
1848 void PhaseCCP::do_transform() {
1849   // Correct leaves of new-space Nodes; they point to old-space.
1850   C->set_root( transform(C->root())->as_Root() );
1851   assert( C->top(),  "missing TOP node" );
1852   assert( C->root(), "missing root" );
1853 }
1854 
1855 //------------------------------transform--------------------------------------
1856 // Given a Node in old-space, clone him into new-space.
1857 // Convert any of his old-space children into new-space children.
1858 Node *PhaseCCP::transform( Node *n ) {
1859   Node *new_node = _nodes[n->_idx]; // Check for transformed node
1860   if( new_node != NULL )
1861     return new_node;                // Been there, done that, return old answer
1862   new_node = transform_once(n);     // Check for constant
1863   _nodes.map( n->_idx, new_node );  // Flag as having been cloned
1864 
1865   // Allocate stack of size _nodes.Size()/2 to avoid frequent realloc
1866   GrowableArray <Node *> trstack(C->live_nodes() >> 1);
1867 
1868   trstack.push(new_node);           // Process children of cloned node
1869   while ( trstack.is_nonempty() ) {
1870     Node *clone = trstack.pop();
1871     uint cnt = clone->req();
1872     for( uint i = 0; i < cnt; i++ ) {          // For all inputs do
1873       Node *input = clone->in(i);
1874       if( input != NULL ) {                    // Ignore NULLs
1875         Node *new_input = _nodes[input->_idx]; // Check for cloned input node
1876         if( new_input == NULL ) {
1877           new_input = transform_once(input);   // Check for constant
1878           _nodes.map( input->_idx, new_input );// Flag as having been cloned
1879           trstack.push(new_input);
1880         }
1881         assert( new_input == clone->in(i), "insanity check");
1882       }
1883     }
1884   }
1885   return new_node;
1886 }
1887 
1888 
1889 //------------------------------transform_once---------------------------------
1890 // For PhaseCCP, transformation is IDENTITY unless Node computed a constant.
1891 Node *PhaseCCP::transform_once( Node *n ) {
1892   const Type *t = type(n);
1893   // Constant?  Use constant Node instead
1894   if( t->singleton() ) {
1895     Node *nn = n;               // Default is to return the original constant
1896     if( t == Type::TOP ) {
1897       // cache my top node on the Compile instance
1898       if( C->cached_top_node() == NULL || C->cached_top_node()->in(0) == NULL ) {
1899         C->set_cached_top_node(ConNode::make(Type::TOP));
1900         set_type(C->top(), Type::TOP);
1901       }
1902       nn = C->top();
1903     }
1904     if( !n->is_Con() ) {
1905       if( t != Type::TOP ) {
1906         nn = makecon(t);        // ConNode::make(t);
1907         NOT_PRODUCT( inc_constants(); )
1908       } else if( n->is_Region() ) { // Unreachable region
1909         // Note: nn == C->top()
1910         n->set_req(0, NULL);        // Cut selfreference
1911         // Eagerly remove dead phis to avoid phis copies creation.
1912         for (DUIterator i = n->outs(); n->has_out(i); i++) {
1913           Node* m = n->out(i);
1914           if( m->is_Phi() ) {
1915             assert(type(m) == Type::TOP, "Unreachable region should not have live phis.");
1916             replace_node(m, nn);
1917             --i; // deleted this phi; rescan starting with next position
1918           }
1919         }
1920       }
1921       replace_node(n,nn);       // Update DefUse edges for new constant
1922     }
1923     return nn;
1924   }
1925 
1926   // If x is a TypeNode, capture any more-precise type permanently into Node
1927   if (t != n->bottom_type()) {
1928     hash_delete(n);             // changing bottom type may force a rehash
1929     n->raise_bottom_type(t);
1930     _worklist.push(n);          // n re-enters the hash table via the worklist
1931   }
1932 
1933   // TEMPORARY fix to ensure that 2nd GVN pass eliminates NULL checks
1934   switch( n->Opcode() ) {
1935   case Op_FastLock:      // Revisit FastLocks for lock coarsening
1936   case Op_If:
1937   case Op_CountedLoopEnd:
1938   case Op_Region:
1939   case Op_Loop:
1940   case Op_CountedLoop:
1941   case Op_Conv2B:
1942   case Op_Opaque1:
1943   case Op_Opaque2:
1944     _worklist.push(n);
1945     break;
1946   default:
1947     break;
1948   }
1949 
1950   return  n;
1951 }
1952 
1953 //---------------------------------saturate------------------------------------
1954 const Type* PhaseCCP::saturate(const Type* new_type, const Type* old_type,
1955                                const Type* limit_type) const {
1956   const Type* wide_type = new_type->widen(old_type, limit_type);
1957   if (wide_type != new_type) {          // did we widen?
1958     // If so, we may have widened beyond the limit type.  Clip it back down.
1959     new_type = wide_type->filter(limit_type);
1960   }
1961   return new_type;
1962 }
1963 
1964 //------------------------------print_statistics-------------------------------
1965 #ifndef PRODUCT
1966 void PhaseCCP::print_statistics() {
1967   tty->print_cr("CCP: %d  constants found: %d", _total_invokes, _total_constants);
1968 }
1969 #endif
1970 
1971 
1972 //=============================================================================
1973 #ifndef PRODUCT
1974 uint PhasePeephole::_total_peepholes = 0;
1975 #endif
1976 //------------------------------PhasePeephole----------------------------------
1977 // Conditional Constant Propagation, ala Wegman & Zadeck
1978 PhasePeephole::PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg )
1979   : PhaseTransform(Peephole), _regalloc(regalloc), _cfg(cfg) {
1980   NOT_PRODUCT( clear_peepholes(); )
1981 }
1982 
1983 #ifndef PRODUCT
1984 //------------------------------~PhasePeephole---------------------------------
1985 PhasePeephole::~PhasePeephole() {
1986   _total_peepholes += count_peepholes();
1987 }
1988 #endif
1989 
1990 //------------------------------transform--------------------------------------
1991 Node *PhasePeephole::transform( Node *n ) {
1992   ShouldNotCallThis();
1993   return NULL;
1994 }
1995 
1996 //------------------------------do_transform-----------------------------------
1997 void PhasePeephole::do_transform() {
1998   bool method_name_not_printed = true;
1999 
2000   // Examine each basic block
2001   for (uint block_number = 1; block_number < _cfg.number_of_blocks(); ++block_number) {
2002     Block* block = _cfg.get_block(block_number);
2003     bool block_not_printed = true;
2004 
2005     // and each instruction within a block
2006     uint end_index = block->number_of_nodes();
2007     // block->end_idx() not valid after PhaseRegAlloc
2008     for( uint instruction_index = 1; instruction_index < end_index; ++instruction_index ) {
2009       Node     *n = block->get_node(instruction_index);
2010       if( n->is_Mach() ) {
2011         MachNode *m = n->as_Mach();
2012         int deleted_count = 0;
2013         // check for peephole opportunities
2014         MachNode *m2 = m->peephole(block, instruction_index, _regalloc, deleted_count);
2015         if( m2 != NULL ) {
2016 #ifndef PRODUCT
2017           if( PrintOptoPeephole ) {
2018             // Print method, first time only
2019             if( C->method() && method_name_not_printed ) {
2020               C->method()->print_short_name(); tty->cr();
2021               method_name_not_printed = false;
2022             }
2023             // Print this block
2024             if( Verbose && block_not_printed) {
2025               tty->print_cr("in block");
2026               block->dump();
2027               block_not_printed = false;
2028             }
2029             // Print instructions being deleted
2030             for( int i = (deleted_count - 1); i >= 0; --i ) {
2031               block->get_node(instruction_index-i)->as_Mach()->format(_regalloc); tty->cr();
2032             }
2033             tty->print_cr("replaced with");
2034             // Print new instruction
2035             m2->format(_regalloc);
2036             tty->print("\n\n");
2037           }
2038 #endif
2039           // Remove old nodes from basic block and update instruction_index
2040           // (old nodes still exist and may have edges pointing to them
2041           //  as register allocation info is stored in the allocator using
2042           //  the node index to live range mappings.)
2043           uint safe_instruction_index = (instruction_index - deleted_count);
2044           for( ; (instruction_index > safe_instruction_index); --instruction_index ) {
2045             block->remove_node( instruction_index );
2046           }
2047           // install new node after safe_instruction_index
2048           block->insert_node(m2, safe_instruction_index + 1);
2049           end_index = block->number_of_nodes() - 1; // Recompute new block size
2050           NOT_PRODUCT( inc_peepholes(); )
2051         }
2052       }
2053     }
2054   }
2055 }
2056 
2057 //------------------------------print_statistics-------------------------------
2058 #ifndef PRODUCT
2059 void PhasePeephole::print_statistics() {
2060   tty->print_cr("Peephole: peephole rules applied: %d",  _total_peepholes);
2061 }
2062 #endif
2063 
2064 
2065 //=============================================================================
2066 //------------------------------set_req_X--------------------------------------
2067 void Node::set_req_X( uint i, Node *n, PhaseIterGVN *igvn ) {
2068   assert( is_not_dead(n), "can not use dead node");
2069   assert( igvn->hash_find(this) != this, "Need to remove from hash before changing edges" );
2070   Node *old = in(i);
2071   set_req(i, n);
2072 
2073   // old goes dead?
2074   if( old ) {
2075     switch (old->outcnt()) {
2076     case 0:
2077       // Put into the worklist to kill later. We do not kill it now because the
2078       // recursive kill will delete the current node (this) if dead-loop exists
2079       if (!old->is_top())
2080         igvn->_worklist.push( old );
2081       break;
2082     case 1:
2083       if( old->is_Store() || old->has_special_unique_user() )
2084         igvn->add_users_to_worklist( old );
2085       break;
2086     case 2:
2087       if( old->is_Store() )
2088         igvn->add_users_to_worklist( old );
2089       if( old->Opcode() == Op_Region )
2090         igvn->_worklist.push(old);
2091       break;
2092     case 3:
2093       if( old->Opcode() == Op_Region ) {
2094         igvn->_worklist.push(old);
2095         igvn->add_users_to_worklist( old );
2096       }
2097       break;
2098     default:
2099       break;
2100     }
2101 #if INCLUDE_SHENANDOAHGC
2102     if (old->Opcode() == Op_AddP && ShenandoahBarrierSetC2::has_only_shenandoah_wb_pre_uses(old)) {
2103       igvn->add_users_to_worklist(old);
2104     }
2105 #endif
2106   }
2107 
2108 }
2109 
2110 //-------------------------------replace_by-----------------------------------
2111 // Using def-use info, replace one node for another.  Follow the def-use info
2112 // to all users of the OLD node.  Then make all uses point to the NEW node.
2113 void Node::replace_by(Node *new_node) {
2114   assert(!is_top(), "top node has no DU info");
2115   for (DUIterator_Last imin, i = last_outs(imin); i >= imin; ) {
2116     Node* use = last_out(i);
2117     uint uses_found = 0;
2118     for (uint j = 0; j < use->len(); j++) {
2119       if (use->in(j) == this) {
2120         if (j < use->req())
2121               use->set_req(j, new_node);
2122         else  use->set_prec(j, new_node);
2123         uses_found++;
2124       }
2125     }
2126     i -= uses_found;    // we deleted 1 or more copies of this edge
2127   }
2128 }
2129 
2130 //=============================================================================
2131 //-----------------------------------------------------------------------------
2132 void Type_Array::grow( uint i ) {
2133   if( !_max ) {
2134     _max = 1;
2135     _types = (const Type**)_a->Amalloc( _max * sizeof(Type*) );
2136     _types[0] = NULL;
2137   }
2138   uint old = _max;
2139   while( i >= _max ) _max <<= 1;        // Double to fit
2140   _types = (const Type**)_a->Arealloc( _types, old*sizeof(Type*),_max*sizeof(Type*));
2141   memset( &_types[old], 0, (_max-old)*sizeof(Type*) );
2142 }
2143 
2144 //------------------------------dump-------------------------------------------
2145 #ifndef PRODUCT
2146 void Type_Array::dump() const {
2147   uint max = Size();
2148   for( uint i = 0; i < max; i++ ) {
2149     if( _types[i] != NULL ) {
2150       tty->print("  %d\t== ", i); _types[i]->dump(); tty->cr();
2151     }
2152   }
2153 }
2154 #endif