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