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