1 /*
   2  * Copyright (c) 2006, 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/connode.hpp"
  28 #include "opto/convertnode.hpp"
  29 #include "opto/loopnode.hpp"
  30 #include "opto/opaquenode.hpp"
  31 #include "opto/rootnode.hpp"
  32 
  33 //================= Loop Unswitching =====================
  34 //
  35 // orig:                       transformed:
  36 //                               if (invariant-test) then
  37 //  predicate                      predicate
  38 //  loop                           loop
  39 //    stmt1                          stmt1
  40 //    if (invariant-test) then       stmt2
  41 //      stmt2                        stmt4
  42 //    else                         endloop
  43 //      stmt3                    else
  44 //    endif                        predicate [clone]
  45 //    stmt4                        loop [clone]
  46 //  endloop                          stmt1 [clone]
  47 //                                   stmt3
  48 //                                   stmt4 [clone]
  49 //                                 endloop
  50 //                               endif
  51 //
  52 // Note: the "else" clause may be empty
  53 
  54 //------------------------------policy_unswitching-----------------------------
  55 // Return TRUE or FALSE if the loop should be unswitched
  56 // (ie. clone loop with an invariant test that does not exit the loop)
  57 bool IdealLoopTree::policy_unswitching( PhaseIdealLoop *phase ) const {
  58   if( !LoopUnswitching ) {
  59     return false;
  60   }
  61   if (!_head->is_Loop()) {
  62     return false;
  63   }
  64 
  65   // check for vectorized loops, any unswitching was already applied
  66   if (_head->is_CountedLoop() && _head->as_CountedLoop()->do_unroll_only()) {
  67     return false;
  68   }
  69 
  70   int nodes_left = phase->C->max_node_limit() - phase->C->live_nodes();
  71   if ((int)(2 * _body.size()) > nodes_left) {
  72     return false; // Too speculative if running low on nodes.
  73   }
  74   LoopNode* head = _head->as_Loop();
  75   if (head->unswitch_count() + 1 > head->unswitch_max()) {
  76     return false;
  77   }
  78   return phase->find_unswitching_candidate(this) != NULL;
  79 }
  80 
  81 //------------------------------find_unswitching_candidate-----------------------------
  82 // Find candidate "if" for unswitching
  83 IfNode* PhaseIdealLoop::find_unswitching_candidate(const IdealLoopTree *loop) const {
  84 
  85   // Find first invariant test that doesn't exit the loop
  86   LoopNode *head = loop->_head->as_Loop();
  87   IfNode* unswitch_iff = NULL;
  88   Node* n = head->in(LoopNode::LoopBackControl);
  89   while (n != head) {
  90     Node* n_dom = idom(n);
  91     if (n->is_Region()) {
  92       if (n_dom->is_If()) {
  93         IfNode* iff = n_dom->as_If();
  94         if (iff->in(1)->is_Bool()) {
  95           BoolNode* bol = iff->in(1)->as_Bool();
  96           if (bol->in(1)->is_Cmp()) {
  97             // If condition is invariant and not a loop exit,
  98             // then found reason to unswitch.
  99             if (loop->is_invariant(bol) && !loop->is_loop_exit(iff)) {
 100               unswitch_iff = iff;
 101             }
 102           }
 103         }
 104       }
 105     }
 106     n = n_dom;
 107   }
 108   return unswitch_iff;
 109 }
 110 
 111 //------------------------------do_unswitching-----------------------------
 112 // Clone loop with an invariant test (that does not exit) and
 113 // insert a clone of the test that selects which version to
 114 // execute.
 115 void PhaseIdealLoop::do_unswitching (IdealLoopTree *loop, Node_List &old_new) {
 116 
 117   // Find first invariant test that doesn't exit the loop
 118   LoopNode *head = loop->_head->as_Loop();
 119 
 120   IfNode* unswitch_iff = find_unswitching_candidate((const IdealLoopTree *)loop);
 121   assert(unswitch_iff != NULL, "should be at least one");
 122 
 123 #ifndef PRODUCT
 124   if (TraceLoopOpts) {
 125     tty->print("Unswitch   %d ", head->unswitch_count()+1);
 126     loop->dump_head();
 127   }
 128 #endif
 129 
 130   // Need to revert back to normal loop
 131   if (head->is_CountedLoop() && !head->as_CountedLoop()->is_normal_loop()) {
 132     head->as_CountedLoop()->set_normal_loop();
 133   }
 134 
 135   ProjNode* proj_true = create_slow_version_of_loop(loop, old_new, unswitch_iff->Opcode(), CloneIncludesStripMined);
 136 
 137 #ifdef ASSERT
 138   Node* uniqc = proj_true->unique_ctrl_out();
 139   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
 140   Node* predicate = find_predicate(entry);
 141   if (predicate != NULL) {
 142     entry = skip_loop_predicates(entry);
 143   }
 144   if (predicate != NULL && UseLoopPredicate) {
 145     // We may have two predicates, find first.
 146     Node* n = find_predicate(entry);
 147     if (n != NULL) {
 148       predicate = n;
 149       entry = skip_loop_predicates(entry);
 150     }
 151   }
 152   if (predicate != NULL && UseProfiledLoopPredicate) {
 153     entry = find_predicate(entry);
 154     if (entry != NULL) predicate = entry;
 155   }
 156   if (predicate != NULL) predicate = predicate->in(0);
 157   assert(proj_true->is_IfTrue() &&
 158          (predicate == NULL && uniqc == head && !head->is_strip_mined() ||
 159           predicate == NULL && uniqc == head->in(LoopNode::EntryControl) && head->is_strip_mined() ||
 160           predicate != NULL && uniqc == predicate), "by construction");
 161 #endif
 162   // Increment unswitch count
 163   LoopNode* head_clone = old_new[head->_idx]->as_Loop();
 164   int nct = head->unswitch_count() + 1;
 165   head->set_unswitch_count(nct);
 166   head_clone->set_unswitch_count(nct);
 167 
 168   // Add test to new "if" outside of loop
 169   IfNode* invar_iff   = proj_true->in(0)->as_If();
 170   Node* invar_iff_c   = invar_iff->in(0);
 171   BoolNode* bol       = unswitch_iff->in(1)->as_Bool();
 172   invar_iff->set_req(1, bol);
 173   invar_iff->_prob    = unswitch_iff->_prob;
 174 
 175   ProjNode* proj_false = invar_iff->proj_out(0)->as_Proj();
 176 
 177   // Hoist invariant casts out of each loop to the appropriate
 178   // control projection.
 179 
 180   Node_List worklist;
 181 
 182   for (DUIterator_Fast imax, i = unswitch_iff->fast_outs(imax); i < imax; i++) {
 183     ProjNode* proj= unswitch_iff->fast_out(i)->as_Proj();
 184     // Copy to a worklist for easier manipulation
 185     for (DUIterator_Fast jmax, j = proj->fast_outs(jmax); j < jmax; j++) {
 186       Node* use = proj->fast_out(j);
 187       if (use->Opcode() == Op_CheckCastPP && loop->is_invariant(use->in(1))) {
 188         worklist.push(use);
 189       }
 190     }
 191     ProjNode* invar_proj = invar_iff->proj_out(proj->_con)->as_Proj();
 192     while (worklist.size() > 0) {
 193       Node* use = worklist.pop();
 194       Node* nuse = use->clone();
 195       nuse->set_req(0, invar_proj);
 196       _igvn.replace_input_of(use, 1, nuse);
 197       register_new_node(nuse, invar_proj);
 198       // Same for the clone
 199       Node* use_clone = old_new[use->_idx];
 200       _igvn.replace_input_of(use_clone, 1, nuse);
 201     }
 202   }
 203 
 204   // Hardwire the control paths in the loops into if(true) and if(false)
 205   _igvn.rehash_node_delayed(unswitch_iff);
 206   short_circuit_if(unswitch_iff, proj_true);
 207 
 208   IfNode* unswitch_iff_clone = old_new[unswitch_iff->_idx]->as_If();
 209   _igvn.rehash_node_delayed(unswitch_iff_clone);
 210   short_circuit_if(unswitch_iff_clone, proj_false);
 211 
 212   // Reoptimize loops
 213   loop->record_for_igvn();
 214   for(int i = loop->_body.size() - 1; i >= 0 ; i--) {
 215     Node *n = loop->_body[i];
 216     Node *n_clone = old_new[n->_idx];
 217     _igvn._worklist.push(n_clone);
 218   }
 219 
 220 #ifndef PRODUCT
 221   if (TraceLoopUnswitching) {
 222     tty->print_cr("Loop unswitching orig: %d @ %d  new: %d @ %d",
 223                   head->_idx,                unswitch_iff->_idx,
 224                   old_new[head->_idx]->_idx, unswitch_iff_clone->_idx);
 225   }
 226 #endif
 227 
 228   C->set_major_progress();
 229 }
 230 
 231 //-------------------------create_slow_version_of_loop------------------------
 232 // Create a slow version of the loop by cloning the loop
 233 // and inserting an if to select fast-slow versions.
 234 // Return control projection of the entry to the fast version.
 235 ProjNode* PhaseIdealLoop::create_slow_version_of_loop(IdealLoopTree *loop,
 236                                                       Node_List &old_new,
 237                                                       int opcode,
 238                                                       CloneLoopMode mode) {
 239   LoopNode* head  = loop->_head->as_Loop();
 240   bool counted_loop = head->is_CountedLoop();
 241   Node*     entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
 242   _igvn.rehash_node_delayed(entry);
 243   IdealLoopTree* outer_loop = loop->_parent;
 244 
 245   head->verify_strip_mined(1);
 246 
 247   Node *cont      = _igvn.intcon(1);
 248   set_ctrl(cont, C->root());
 249   Node* opq       = new Opaque1Node(C, cont);
 250   register_node(opq, outer_loop, entry, dom_depth(entry));
 251   Node *bol       = new Conv2BNode(opq);
 252   register_node(bol, outer_loop, entry, dom_depth(entry));
 253   IfNode* iff = (opcode == Op_RangeCheck) ? new RangeCheckNode(entry, bol, PROB_MAX, COUNT_UNKNOWN) :
 254     new IfNode(entry, bol, PROB_MAX, COUNT_UNKNOWN);
 255   register_node(iff, outer_loop, entry, dom_depth(entry));
 256   ProjNode* iffast = new IfTrueNode(iff);
 257   register_node(iffast, outer_loop, iff, dom_depth(iff));
 258   ProjNode* ifslow = new IfFalseNode(iff);
 259   register_node(ifslow, outer_loop, iff, dom_depth(iff));
 260 
 261   // Clone the loop body.  The clone becomes the fast loop.  The
 262   // original pre-header will (illegally) have 3 control users
 263   // (old & new loops & new if).
 264   clone_loop(loop, old_new, dom_depth(head->skip_strip_mined()), mode, iff);
 265   assert(old_new[head->_idx]->is_Loop(), "" );
 266 
 267   // Fast (true) control
 268   Node* iffast_pred = clone_loop_predicates(entry, iffast, !counted_loop);
 269 
 270   // Slow (false) control
 271   Node* ifslow_pred = clone_loop_predicates(entry, ifslow, !counted_loop);
 272 
 273   Node* l = head->skip_strip_mined();
 274   _igvn.replace_input_of(l, LoopNode::EntryControl, iffast_pred);
 275   set_idom(l, iffast_pred, dom_depth(l));
 276   LoopNode* slow_l = old_new[head->_idx]->as_Loop()->skip_strip_mined();
 277   _igvn.replace_input_of(slow_l, LoopNode::EntryControl, ifslow_pred);
 278   set_idom(slow_l, ifslow_pred, dom_depth(l));
 279 
 280   recompute_dom_depth();
 281 
 282   return iffast;
 283 }
 284 
 285 LoopNode* PhaseIdealLoop::create_reserve_version_of_loop(IdealLoopTree *loop, CountedLoopReserveKit* lk) {
 286   Node_List old_new;
 287   LoopNode* head  = loop->_head->as_Loop();
 288   bool counted_loop = head->is_CountedLoop();
 289   Node*     entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
 290   _igvn.rehash_node_delayed(entry);
 291   IdealLoopTree* outer_loop = head->is_strip_mined() ? loop->_parent->_parent : loop->_parent;
 292 
 293   ConINode* const_1 = _igvn.intcon(1);
 294   set_ctrl(const_1, C->root());
 295   IfNode* iff = new IfNode(entry, const_1, PROB_MAX, COUNT_UNKNOWN);
 296   register_node(iff, outer_loop, entry, dom_depth(entry));
 297   ProjNode* iffast = new IfTrueNode(iff);
 298   register_node(iffast, outer_loop, iff, dom_depth(iff));
 299   ProjNode* ifslow = new IfFalseNode(iff);
 300   register_node(ifslow, outer_loop, iff, dom_depth(iff));
 301 
 302   // Clone the loop body.  The clone becomes the fast loop.  The
 303   // original pre-header will (illegally) have 3 control users
 304   // (old & new loops & new if).
 305   clone_loop(loop, old_new, dom_depth(head), CloneIncludesStripMined, iff);
 306   assert(old_new[head->_idx]->is_Loop(), "" );
 307 
 308   LoopNode* slow_head = old_new[head->_idx]->as_Loop();
 309 
 310 #ifndef PRODUCT
 311   if (TraceLoopOpts) {
 312     tty->print_cr("PhaseIdealLoop::create_reserve_version_of_loop:");
 313     tty->print("\t iff = %d, ", iff->_idx); iff->dump();
 314     tty->print("\t iffast = %d, ", iffast->_idx); iffast->dump();
 315     tty->print("\t ifslow = %d, ", ifslow->_idx); ifslow->dump();
 316     tty->print("\t before replace_input_of: head = %d, ", head->_idx); head->dump();
 317     tty->print("\t before replace_input_of: slow_head = %d, ", slow_head->_idx); slow_head->dump();
 318   }
 319 #endif
 320 
 321   // Fast (true) control
 322   _igvn.replace_input_of(head->skip_strip_mined(), LoopNode::EntryControl, iffast);
 323   // Slow (false) control
 324   _igvn.replace_input_of(slow_head->skip_strip_mined(), LoopNode::EntryControl, ifslow);
 325 
 326   recompute_dom_depth();
 327 
 328   lk->set_iff(iff);
 329 
 330 #ifndef PRODUCT
 331   if (TraceLoopOpts ) {
 332     tty->print("\t after  replace_input_of: head = %d, ", head->_idx); head->dump();
 333     tty->print("\t after  replace_input_of: slow_head = %d, ", slow_head->_idx); slow_head->dump();
 334   }
 335 #endif
 336 
 337   return slow_head->as_Loop();
 338 }
 339 
 340 CountedLoopReserveKit::CountedLoopReserveKit(PhaseIdealLoop* phase, IdealLoopTree *loop, bool active = true) :
 341   _phase(phase),
 342   _lpt(loop),
 343   _lp(NULL),
 344   _iff(NULL),
 345   _lp_reserved(NULL),
 346   _has_reserved(false),
 347   _use_new(false),
 348   _active(active)
 349   {
 350     create_reserve();
 351   };
 352 
 353 CountedLoopReserveKit::~CountedLoopReserveKit() {
 354   if (!_active) {
 355     return;
 356   }
 357 
 358   if (_has_reserved && !_use_new) {
 359     // intcon(0)->iff-node reverts CF to the reserved copy
 360     ConINode* const_0 = _phase->_igvn.intcon(0);
 361     _phase->set_ctrl(const_0, _phase->C->root());
 362     _iff->set_req(1, const_0);
 363 
 364     #ifndef PRODUCT
 365       if (TraceLoopOpts) {
 366         tty->print_cr("CountedLoopReserveKit::~CountedLoopReserveKit()");
 367         tty->print("\t discard loop %d and revert to the reserved loop clone %d: ", _lp->_idx, _lp_reserved->_idx);
 368         _lp_reserved->dump();
 369       }
 370     #endif
 371   }
 372 }
 373 
 374 bool CountedLoopReserveKit::create_reserve() {
 375   if (!_active) {
 376     return false;
 377   }
 378 
 379   if(!_lpt->_head->is_CountedLoop()) {
 380     if (TraceLoopOpts) {
 381       tty->print_cr("CountedLoopReserveKit::create_reserve: %d not counted loop", _lpt->_head->_idx);
 382     }
 383     return false;
 384   }
 385   CountedLoopNode *cl = _lpt->_head->as_CountedLoop();
 386   if (!cl->is_valid_counted_loop()) {
 387     if (TraceLoopOpts) {
 388       tty->print_cr("CountedLoopReserveKit::create_reserve: %d not valid counted loop", cl->_idx);
 389     }
 390     return false; // skip malformed counted loop
 391   }
 392   if (!cl->is_main_loop()) {
 393     bool loop_not_canonical = true;
 394     if (cl->is_post_loop() && (cl->slp_max_unroll() > 0)) {
 395       loop_not_canonical = false;
 396     }
 397     // only reject some loop forms
 398     if (loop_not_canonical) {
 399       if (TraceLoopOpts) {
 400         tty->print_cr("CountedLoopReserveKit::create_reserve: %d not canonical loop", cl->_idx);
 401       }
 402       return false; // skip normal, pre, and post (conditionally) loops
 403     }
 404   }
 405 
 406   _lp = _lpt->_head->as_Loop();
 407   _lp_reserved = _phase->create_reserve_version_of_loop(_lpt, this);
 408 
 409   if (!_lp_reserved->is_CountedLoop()) {
 410     return false;
 411   }
 412 
 413   Node* ifslow_pred = _lp_reserved->skip_strip_mined()->in(LoopNode::EntryControl);
 414 
 415   if (!ifslow_pred->is_IfFalse()) {
 416     return false;
 417   }
 418 
 419   Node* iff = ifslow_pred->in(0);
 420   if (!iff->is_If() || iff != _iff) {
 421     return false;
 422   }
 423 
 424   if (iff->in(1)->Opcode() != Op_ConI) {
 425     return false;
 426   }
 427 
 428   return _has_reserved = true;
 429 }