1 /*
   2  * Copyright (c) 1999, 2012, 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/callnode.hpp"
  28 #include "opto/loopnode.hpp"
  29 #include "opto/movenode.hpp"
  30 
  31 
  32 //------------------------------split_thru_region------------------------------
  33 // Split Node 'n' through merge point.
  34 Node *PhaseIdealLoop::split_thru_region( Node *n, Node *region ) {
  35   assert(n->Opcode() != Op_ShenandoahWriteBarrier, "not with write barriers");
  36   uint wins = 0;
  37   assert( n->is_CFG(), "" );
  38   assert( region->is_Region(), "" );
  39   Node *r = new RegionNode( region->req() );
  40   IdealLoopTree *loop = get_loop( n );
  41   for( uint i = 1; i < region->req(); i++ ) {
  42     Node *x = n->clone();
  43     Node *in0 = n->in(0);
  44     if( in0->in(0) == region ) x->set_req( 0, in0->in(i) );
  45     for( uint j = 1; j < n->req(); j++ ) {
  46       Node *in = n->in(j);
  47       if( get_ctrl(in) == region )
  48         x->set_req( j, in->in(i) );
  49     }
  50     _igvn.register_new_node_with_optimizer(x);
  51     set_loop(x, loop);
  52     set_idom(x, x->in(0), dom_depth(x->in(0))+1);
  53     r->init_req(i, x);
  54   }
  55 
  56   // Record region
  57   r->set_req(0,region);         // Not a TRUE RegionNode
  58   _igvn.register_new_node_with_optimizer(r);
  59   set_loop(r, loop);
  60   if( !loop->_child )
  61     loop->_body.push(r);
  62   return r;
  63 }
  64 
  65 //------------------------------split_up---------------------------------------
  66 // Split block-local op up through the phis to empty the current block
  67 bool PhaseIdealLoop::split_up( Node *n, Node *blk1, Node *blk2 ) {
  68   if( n->is_CFG() ) {
  69     assert( n->in(0) != blk1, "Lousy candidate for split-if" );
  70     return false;
  71   }
  72   if( get_ctrl(n) != blk1 && get_ctrl(n) != blk2 )
  73     return false;               // Not block local
  74   if( n->is_Phi() ) return false; // Local PHIs are expected
  75 
  76   // Recursively split-up inputs
  77   uint first_input = n->Opcode() == Op_ShenandoahWBMemProj ? 0 : 1;
  78   for (uint i = first_input; i < n->req(); i++) {
  79     if( split_up( n->in(i), blk1, blk2 ) ) {
  80       // Got split recursively and self went dead?
  81       if (n->outcnt() == 0)
  82         _igvn.remove_dead_node(n);
  83       return true;
  84     }
  85   }
  86 
  87   // Check for needing to clone-up a compare.  Can't do that, it forces
  88   // another (nested) split-if transform.  Instead, clone it "down".
  89   if( n->is_Cmp() ) {
  90     assert(get_ctrl(n) == blk2 || get_ctrl(n) == blk1, "must be in block with IF");
  91     // Check for simple Cmp/Bool/CMove which we can clone-up.  Cmp/Bool/CMove
  92     // sequence can have no other users and it must all reside in the split-if
  93     // block.  Non-simple Cmp/Bool/CMove sequences are 'cloned-down' below -
  94     // private, per-use versions of the Cmp and Bool are made.  These sink to
  95     // the CMove block.  If the CMove is in the split-if block, then in the
  96     // next iteration this will become a simple Cmp/Bool/CMove set to clone-up.
  97     Node *bol, *cmov;
  98     if( !(n->outcnt() == 1 && n->unique_out()->is_Bool() &&
  99           (bol = n->unique_out()->as_Bool()) &&
 100           (get_ctrl(bol) == blk1 ||
 101            get_ctrl(bol) == blk2) &&
 102           bol->outcnt() == 1 &&
 103           bol->unique_out()->is_CMove() &&
 104           (cmov = bol->unique_out()->as_CMove()) &&
 105           (get_ctrl(cmov) == blk1 ||
 106            get_ctrl(cmov) == blk2) ) ) {
 107 
 108       // Must clone down
 109 #ifndef PRODUCT
 110       if( PrintOpto && VerifyLoopOptimizations ) {
 111         tty->print("Cloning down: ");
 112         n->dump();
 113       }
 114 #endif
 115       // Clone down any block-local BoolNode uses of this CmpNode
 116       for (DUIterator i = n->outs(); n->has_out(i); i++) {
 117         Node* bol = n->out(i);
 118         assert( bol->is_Bool(), "" );
 119         if (bol->outcnt() == 1) {
 120           Node* use = bol->unique_out();
 121           Node *use_c = use->is_If() ? use->in(0) : get_ctrl(use);
 122           if (use_c == blk1 || use_c == blk2) {
 123             continue;
 124           }
 125         }
 126         if (get_ctrl(bol) == blk1 || get_ctrl(bol) == blk2) {
 127           // Recursively sink any BoolNode
 128 #ifndef PRODUCT
 129           if( PrintOpto && VerifyLoopOptimizations ) {
 130             tty->print("Cloning down: ");
 131             bol->dump();
 132           }
 133 #endif
 134           for (DUIterator_Last jmin, j = bol->last_outs(jmin); j >= jmin; --j) {
 135             // Uses are either IfNodes or CMoves
 136             Node* iff = bol->last_out(j);
 137             assert( iff->in(1) == bol, "" );
 138             // Get control block of either the CMove or the If input
 139             Node *iff_ctrl = iff->is_If() ? iff->in(0) : get_ctrl(iff);
 140             Node *x = bol->clone();
 141             register_new_node(x, iff_ctrl);
 142             _igvn.replace_input_of(iff, 1, x);
 143           }
 144           _igvn.remove_dead_node( bol );
 145           --i;
 146         }
 147       }
 148       // Clone down this CmpNode
 149       for (DUIterator_Last jmin, j = n->last_outs(jmin); j >= jmin; --j) {
 150         Node* bol = n->last_out(j);
 151         assert( bol->in(1) == n, "" );
 152         Node *x = n->clone();
 153         register_new_node(x, get_ctrl(bol));
 154         _igvn.replace_input_of(bol, 1, x);
 155       }
 156       _igvn.remove_dead_node( n );
 157 
 158       return true;
 159     }
 160   }
 161 
 162   // See if splitting-up a Store.  Any anti-dep loads must go up as
 163   // well.  An anti-dep load might be in the wrong block, because in
 164   // this particular layout/schedule we ignored anti-deps and allow
 165   // memory to be alive twice.  This only works if we do the same
 166   // operations on anti-dep loads as we do their killing stores.
 167   if( n->is_Store() && n->in(MemNode::Memory)->in(0) == n->in(0) ) {
 168     // Get store's memory slice
 169     int alias_idx = C->get_alias_index(_igvn.type(n->in(MemNode::Address))->is_ptr());
 170 
 171     // Get memory-phi anti-dep loads will be using
 172     Node *memphi = n->in(MemNode::Memory);
 173     assert( memphi->is_Phi(), "" );
 174     // Hoist any anti-dep load to the splitting block;
 175     // it will then "split-up".
 176     for (DUIterator_Fast imax,i = memphi->fast_outs(imax); i < imax; i++) {
 177       Node *load = memphi->fast_out(i);
 178       if( load->is_Load() && alias_idx == C->get_alias_index(_igvn.type(load->in(MemNode::Address))->is_ptr()) )
 179         set_ctrl(load,blk1);
 180     }
 181   }
 182 
 183   // Found some other Node; must clone it up
 184 #ifndef PRODUCT
 185   if( PrintOpto && VerifyLoopOptimizations ) {
 186     tty->print("Cloning up: ");
 187     n->dump();
 188   }
 189 #endif
 190 
 191   // ConvI2L may have type information on it which becomes invalid if
 192   // it moves up in the graph so change any clones so widen the type
 193   // to TypeLong::INT when pushing it up.
 194   const Type* rtype = NULL;
 195   if (n->Opcode() == Op_ConvI2L && n->bottom_type() != TypeLong::INT) {
 196     rtype = TypeLong::INT;
 197   }
 198 
 199   // Now actually split-up this guy.  One copy per control path merging.
 200   Node *phi = PhiNode::make_blank(blk1, n);
 201   for( uint j = 1; j < blk1->req(); j++ ) {
 202     Node *x = n->clone();
 203     // Widen the type of the ConvI2L when pushing up.
 204     if (rtype != NULL) x->as_Type()->set_type(rtype);
 205     if( n->in(0) && n->in(0) == blk1 )
 206       x->set_req( 0, blk1->in(j) );
 207     for( uint i = 1; i < n->req(); i++ ) {
 208       Node *m = n->in(i);
 209       if( get_ctrl(m) == blk1 ) {
 210         assert( m->in(0) == blk1, "" );
 211         x->set_req( i, m->in(j) );
 212       }
 213     }
 214     register_new_node( x, blk1->in(j) );
 215     phi->init_req( j, x );
 216   }
 217   // Announce phi to optimizer
 218   register_new_node(phi, blk1);
 219 
 220   // Remove cloned-up value from optimizer; use phi instead
 221   split_mem_thru_phi(n, blk1, phi);
 222   _igvn.replace_node( n, phi );
 223 
 224   // (There used to be a self-recursive call to split_up() here,
 225   // but it is not needed.  All necessary forward walking is done
 226   // by do_split_if() below.)
 227 
 228   return true;
 229 }
 230 
 231 //------------------------------register_new_node------------------------------
 232 void PhaseIdealLoop::register_new_node( Node *n, Node *blk ) {
 233   assert(!n->is_CFG(), "must be data node");
 234   _igvn.register_new_node_with_optimizer(n);
 235   set_ctrl(n, blk);
 236   IdealLoopTree *loop = get_loop(blk);
 237   if( !loop->_child )
 238     loop->_body.push(n);
 239 }
 240 
 241 //------------------------------small_cache------------------------------------
 242 struct small_cache : public Dict {
 243 
 244   small_cache() : Dict( cmpkey, hashptr ) {}
 245   Node *probe( Node *use_blk ) { return (Node*)((*this)[use_blk]); }
 246   void lru_insert( Node *use_blk, Node *new_def ) { Insert(use_blk,new_def); }
 247 };
 248 
 249 //------------------------------spinup-----------------------------------------
 250 // "Spin up" the dominator tree, starting at the use site and stopping when we
 251 // find the post-dominating point.
 252 
 253 // We must be at the merge point which post-dominates 'new_false' and
 254 // 'new_true'.  Figure out which edges into the RegionNode eventually lead up
 255 // to false and which to true.  Put in a PhiNode to merge values; plug in
 256 // the appropriate false-arm or true-arm values.  If some path leads to the
 257 // original IF, then insert a Phi recursively.
 258 Node *PhaseIdealLoop::spinup( Node *iff_dom, Node *new_false, Node *new_true, Node *use_blk, Node *def, small_cache *cache ) {
 259   if (use_blk->is_top())        // Handle dead uses
 260     return use_blk;
 261   Node *prior_n = (Node*)0xdeadbeef;
 262   Node *n = use_blk;            // Get path input
 263   assert( use_blk != iff_dom, "" );
 264   // Here's the "spinup" the dominator tree loop.  Do a cache-check
 265   // along the way, in case we've come this way before.
 266   while( n != iff_dom ) {       // Found post-dominating point?
 267     prior_n = n;
 268     n = idom(n);                // Search higher
 269     Node *s = cache->probe( prior_n ); // Check cache
 270     if( s ) return s;           // Cache hit!
 271   }
 272 
 273   Node *phi_post;
 274   if( prior_n == new_false || prior_n == new_true ) {
 275     phi_post = def->clone();
 276     phi_post->set_req(0, prior_n );
 277     register_new_node(phi_post, prior_n);
 278   } else {
 279     // This method handles both control uses (looking for Regions) or data
 280     // uses (looking for Phis).  If looking for a control use, then we need
 281     // to insert a Region instead of a Phi; however Regions always exist
 282     // previously (the hash_find_insert below would always hit) so we can
 283     // return the existing Region.
 284     if( def->is_CFG() ) {
 285       phi_post = prior_n;       // If looking for CFG, return prior
 286     } else {
 287       assert( def->is_Phi(), "" );
 288       assert( prior_n->is_Region(), "must be a post-dominating merge point" );
 289 
 290       // Need a Phi here
 291       phi_post = PhiNode::make_blank(prior_n, def);
 292       // Search for both true and false on all paths till find one.
 293       for( uint i = 1; i < phi_post->req(); i++ ) // For all paths
 294         phi_post->init_req( i, spinup( iff_dom, new_false, new_true, prior_n->in(i), def, cache ) );
 295       Node *t = _igvn.hash_find_insert(phi_post);
 296       if( t ) {                 // See if we already have this one
 297         // phi_post will not be used, so kill it
 298         _igvn.remove_dead_node(phi_post);
 299         phi_post->destruct();
 300         phi_post = t;
 301       } else {
 302         register_new_node( phi_post, prior_n );
 303       }
 304     }
 305   }
 306 
 307   // Update cache everywhere
 308   prior_n = (Node*)0xdeadbeef;  // Reset IDOM walk
 309   n = use_blk;                  // Get path input
 310   // Spin-up the idom tree again, basically doing path-compression.
 311   // Insert cache entries along the way, so that if we ever hit this
 312   // point in the IDOM tree again we'll stop immediately on a cache hit.
 313   while( n != iff_dom ) {       // Found post-dominating point?
 314     prior_n = n;
 315     n = idom(n);                // Search higher
 316     cache->lru_insert( prior_n, phi_post ); // Fill cache
 317   } // End of while not gone high enough
 318 
 319   return phi_post;
 320 }
 321 
 322 //------------------------------find_use_block---------------------------------
 323 // Find the block a USE is in.  Normally USE's are in the same block as the
 324 // using instruction.  For Phi-USE's, the USE is in the predecessor block
 325 // along the corresponding path.
 326 Node *PhaseIdealLoop::find_use_block( Node *use, Node *def, Node *old_false, Node *new_false, Node *old_true, Node *new_true ) {
 327   // CFG uses are their own block
 328   if( use->is_CFG() )
 329     return use;
 330 
 331   if( use->is_Phi() ) {         // Phi uses in prior block
 332     // Grab the first Phi use; there may be many.
 333     // Each will be handled as a separate iteration of
 334     // the "while( phi->outcnt() )" loop.
 335     uint j;
 336     for( j = 1; j < use->req(); j++ )
 337       if( use->in(j) == def )
 338         break;
 339     assert( j < use->req(), "def should be among use's inputs" );
 340     return use->in(0)->in(j);
 341   }
 342   // Normal (non-phi) use
 343   Node *use_blk = get_ctrl(use);
 344   // Some uses are directly attached to the old (and going away)
 345   // false and true branches.
 346   if( use_blk == old_false ) {
 347     use_blk = new_false;
 348     set_ctrl(use, new_false);
 349   }
 350   if( use_blk == old_true ) {
 351     use_blk = new_true;
 352     set_ctrl(use, new_true);
 353   }
 354 
 355   if (use_blk == NULL) {        // He's dead, Jim
 356     _igvn.replace_node(use, C->top());
 357   }
 358 
 359   return use_blk;
 360 }
 361 
 362 //------------------------------handle_use-------------------------------------
 363 // Handle uses of the merge point.  Basically, split-if makes the merge point
 364 // go away so all uses of the merge point must go away as well.  Most block
 365 // local uses have already been split-up, through the merge point.  Uses from
 366 // far below the merge point can't always be split up (e.g., phi-uses are
 367 // pinned) and it makes too much stuff live.  Instead we use a path-based
 368 // solution to move uses down.
 369 //
 370 // If the use is along the pre-split-CFG true branch, then the new use will
 371 // be from the post-split-CFG true merge point.  Vice-versa for the false
 372 // path.  Some uses will be along both paths; then we sink the use to the
 373 // post-dominating location; we may need to insert a Phi there.
 374 void PhaseIdealLoop::handle_use( Node *use, Node *def, small_cache *cache, Node *region_dom, Node *new_false, Node *new_true, Node *old_false, Node *old_true ) {
 375 
 376   Node *use_blk = find_use_block(use,def,old_false,new_false,old_true,new_true);
 377   if( !use_blk ) return;        // He's dead, Jim
 378 
 379   // Walk up the dominator tree until I hit either the old IfFalse, the old
 380   // IfTrue or the old If.  Insert Phis where needed.
 381   Node *new_def = spinup( region_dom, new_false, new_true, use_blk, def, cache );
 382 
 383   // Found where this USE goes.  Re-point him.
 384   uint i;
 385   for( i = 0; i < use->req(); i++ )
 386     if( use->in(i) == def )
 387       break;
 388   assert( i < use->req(), "def should be among use's inputs" );
 389   _igvn.replace_input_of(use, i, new_def);
 390 }
 391 
 392 //------------------------------do_split_if------------------------------------
 393 // Found an If getting its condition-code input from a Phi in the same block.
 394 // Split thru the Region.
 395 void PhaseIdealLoop::do_split_if( Node *iff ) {
 396 #ifndef PRODUCT
 397   if( PrintOpto && VerifyLoopOptimizations )
 398     tty->print_cr("Split-if");
 399   if (TraceLoopOpts) {
 400     tty->print_cr("SplitIf");
 401   }
 402 #endif
 403   C->set_major_progress();
 404   Node *region = iff->in(0);
 405   Node *region_dom = idom(region);
 406 
 407   // We are going to clone this test (and the control flow with it) up through
 408   // the incoming merge point.  We need to empty the current basic block.
 409   // Clone any instructions which must be in this block up through the merge
 410   // point.
 411   DUIterator i, j;
 412   bool progress = true;
 413   while (progress) {
 414     progress = false;
 415     for (i = region->outs(); region->has_out(i); i++) {
 416       Node* n = region->out(i);
 417       if( n == region ) continue;
 418       // The IF to be split is OK.
 419       if( n == iff ) continue;
 420       if( !n->is_Phi() ) {      // Found pinned memory op or such
 421         if (split_up(n, region, iff)) {
 422           i = region->refresh_out_pos(i);
 423           progress = true;
 424         }
 425         continue;
 426       }
 427       assert( n->in(0) == region, "" );
 428 
 429       // Recursively split up all users of a Phi
 430       for (j = n->outs(); n->has_out(j); j++) {
 431         Node* m = n->out(j);
 432         // If m is dead, throw it away, and declare progress
 433         if (_nodes[m->_idx] == NULL) {
 434           _igvn.remove_dead_node(m);
 435           // fall through
 436         }
 437         else if (m != iff && split_up(m, region, iff)) {
 438           // fall through
 439         } else {
 440           continue;
 441         }
 442         // Something unpredictable changed.
 443         // Tell the iterators to refresh themselves, and rerun the loop.
 444         i = region->refresh_out_pos(i);
 445         j = region->refresh_out_pos(j);
 446         progress = true;
 447       }
 448     }
 449   }
 450 
 451   // Now we have no instructions in the block containing the IF.
 452   // Split the IF.
 453   Node *new_iff = split_thru_region( iff, region );
 454 
 455   // Replace both uses of 'new_iff' with Regions merging True/False
 456   // paths.  This makes 'new_iff' go dead.
 457   Node *old_false, *old_true;
 458   Node *new_false, *new_true;
 459   for (DUIterator_Last j2min, j2 = iff->last_outs(j2min); j2 >= j2min; --j2) {
 460     Node *ifp = iff->last_out(j2);
 461     assert( ifp->Opcode() == Op_IfFalse || ifp->Opcode() == Op_IfTrue, "" );
 462     ifp->set_req(0, new_iff);
 463     Node *ifpx = split_thru_region( ifp, region );
 464 
 465     // Replace 'If' projection of a Region with a Region of
 466     // 'If' projections.
 467     ifpx->set_req(0, ifpx);       // A TRUE RegionNode
 468 
 469     // Setup dominator info
 470     set_idom(ifpx, region_dom, dom_depth(region_dom) + 1);
 471 
 472     // Check for splitting loop tails
 473     if( get_loop(iff)->tail() == ifp )
 474       get_loop(iff)->_tail = ifpx;
 475 
 476     // Replace in the graph with lazy-update mechanism
 477     new_iff->set_req(0, new_iff); // hook self so it does not go dead
 478     lazy_replace_proj( ifp, ifpx );
 479     new_iff->set_req(0, region);
 480 
 481     // Record bits for later xforms
 482     if( ifp->Opcode() == Op_IfFalse ) {
 483       old_false = ifp;
 484       new_false = ifpx;
 485     } else {
 486       old_true = ifp;
 487       new_true = ifpx;
 488     }
 489   }
 490   _igvn.remove_dead_node(new_iff);
 491   // Lazy replace IDOM info with the region's dominator
 492   lazy_replace( iff, region_dom );
 493 
 494   // Now make the original merge point go dead, by handling all its uses.
 495   small_cache region_cache;
 496   // Preload some control flow in region-cache
 497   region_cache.lru_insert( new_false, new_false );
 498   region_cache.lru_insert( new_true , new_true  );
 499   // Now handle all uses of the splitting block
 500   for (DUIterator k = region->outs(); region->has_out(k); k++) {
 501     Node* phi = region->out(k);
 502     if (!phi->in(0)) {         // Dead phi?  Remove it
 503       _igvn.remove_dead_node(phi);
 504     } else if (phi == region) { // Found the self-reference
 505       continue;                 // No roll-back of DUIterator
 506     } else if (phi->is_Phi()) { // Expected common case: Phi hanging off of Region
 507       assert(phi->in(0) == region, "Inconsistent graph");
 508       // Need a per-def cache.  Phi represents a def, so make a cache
 509       small_cache phi_cache;
 510 
 511       // Inspect all Phi uses to make the Phi go dead
 512       for (DUIterator_Last lmin, l = phi->last_outs(lmin); l >= lmin; --l) {
 513         Node* use = phi->last_out(l);
 514         // Compute the new DEF for this USE.  New DEF depends on the path
 515         // taken from the original DEF to the USE.  The new DEF may be some
 516         // collection of PHI's merging values from different paths.  The Phis
 517         // inserted depend only on the location of the USE.  We use a
 518         // 2-element cache to handle multiple uses from the same block.
 519         handle_use(use, phi, &phi_cache, region_dom, new_false, new_true, old_false, old_true);
 520       } // End of while phi has uses
 521       // Remove the dead Phi
 522       _igvn.remove_dead_node( phi );
 523     } else {
 524       assert(phi->in(0) == region, "Inconsistent graph");
 525       // Random memory op guarded by Region.  Compute new DEF for USE.
 526       handle_use(phi, region, &region_cache, region_dom, new_false, new_true, old_false, old_true);
 527     }
 528     // Every path above deletes a use of the region, except for the region
 529     // self-cycle (which is needed by handle_use calling find_use_block
 530     // calling get_ctrl calling get_ctrl_no_update looking for dead
 531     // regions).  So roll back the DUIterator innards.
 532     --k;
 533   } // End of while merge point has phis
 534 
 535   assert(region->outcnt() == 1, "Only self reference should remain"); // Just Self on the Region
 536   region->set_req(0, NULL);       // Break the self-cycle
 537 
 538   // Any leftover bits in the splitting block must not have depended on local
 539   // Phi inputs (these have already been split-up).  Hence it's safe to hoist
 540   // these guys to the dominating point.
 541   lazy_replace( region, region_dom );
 542 #ifndef PRODUCT
 543   if( VerifyLoopOptimizations ) verify();
 544 #endif
 545 }