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