Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 1 | //===-- LoopPredication.cpp - Guard based loop predication pass -----------===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // The LoopPredication pass tries to convert loop variant range checks to loop |
| 10 | // invariant by widening checks across loop iterations. For example, it will |
| 11 | // convert |
| 12 | // |
| 13 | // for (i = 0; i < n; i++) { |
| 14 | // guard(i < len); |
| 15 | // ... |
| 16 | // } |
| 17 | // |
| 18 | // to |
| 19 | // |
| 20 | // for (i = 0; i < n; i++) { |
| 21 | // guard(n - 1 < len); |
| 22 | // ... |
| 23 | // } |
| 24 | // |
| 25 | // After this transformation the condition of the guard is loop invariant, so |
| 26 | // loop-unswitch can later unswitch the loop by this condition which basically |
| 27 | // predicates the loop by the widened condition: |
| 28 | // |
| 29 | // if (n - 1 < len) |
| 30 | // for (i = 0; i < n; i++) { |
| 31 | // ... |
| 32 | // } |
| 33 | // else |
| 34 | // deoptimize |
| 35 | // |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 36 | // It's tempting to rely on SCEV here, but it has proven to be problematic. |
| 37 | // Generally the facts SCEV provides about the increment step of add |
| 38 | // recurrences are true if the backedge of the loop is taken, which implicitly |
| 39 | // assumes that the guard doesn't fail. Using these facts to optimize the |
| 40 | // guard results in a circular logic where the guard is optimized under the |
| 41 | // assumption that it never fails. |
| 42 | // |
| 43 | // For example, in the loop below the induction variable will be marked as nuw |
| 44 | // basing on the guard. Basing on nuw the guard predicate will be considered |
| 45 | // monotonic. Given a monotonic condition it's tempting to replace the induction |
| 46 | // variable in the condition with its value on the last iteration. But this |
| 47 | // transformation is not correct, e.g. e = 4, b = 5 breaks the loop. |
| 48 | // |
| 49 | // for (int i = b; i != e; i++) |
| 50 | // guard(i u< len) |
| 51 | // |
| 52 | // One of the ways to reason about this problem is to use an inductive proof |
| 53 | // approach. Given the loop: |
| 54 | // |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 55 | // if (B(0)) { |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 56 | // do { |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 57 | // I = PHI(0, I.INC) |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 58 | // I.INC = I + Step |
| 59 | // guard(G(I)); |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 60 | // } while (B(I)); |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 61 | // } |
| 62 | // |
| 63 | // where B(x) and G(x) are predicates that map integers to booleans, we want a |
| 64 | // loop invariant expression M such the following program has the same semantics |
| 65 | // as the above: |
| 66 | // |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 67 | // if (B(0)) { |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 68 | // do { |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 69 | // I = PHI(0, I.INC) |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 70 | // I.INC = I + Step |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 71 | // guard(G(0) && M); |
| 72 | // } while (B(I)); |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 73 | // } |
| 74 | // |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 75 | // One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step) |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 76 | // |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 77 | // Informal proof that the transformation above is correct: |
| 78 | // |
| 79 | // By the definition of guards we can rewrite the guard condition to: |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 80 | // G(I) && G(0) && M |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 81 | // |
| 82 | // Let's prove that for each iteration of the loop: |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 83 | // G(0) && M => G(I) |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 84 | // And the condition above can be simplified to G(Start) && M. |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 85 | // |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 86 | // Induction base. |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 87 | // G(0) && M => G(0) |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 88 | // |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 89 | // Induction step. Assuming G(0) && M => G(I) on the subsequent |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 90 | // iteration: |
| 91 | // |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 92 | // B(I) is true because it's the backedge condition. |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 93 | // G(I) is true because the backedge is guarded by this condition. |
| 94 | // |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 95 | // So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step). |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 96 | // |
| 97 | // Note that we can use anything stronger than M, i.e. any condition which |
| 98 | // implies M. |
| 99 | // |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 100 | // When S = 1 (i.e. forward iterating loop), the transformation is supported |
| 101 | // when: |
Artur Pilipenko | b4527e1 | 2017-10-12 20:40:27 +0000 | [diff] [blame] | 102 | // * The loop has a single latch with the condition of the form: |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 103 | // B(X) = latchStart + X <pred> latchLimit, |
| 104 | // where <pred> is u<, u<=, s<, or s<=. |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 105 | // * The guard condition is of the form |
| 106 | // G(X) = guardStart + X u< guardLimit |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 107 | // |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 108 | // For the ult latch comparison case M is: |
| 109 | // forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit => |
| 110 | // guardStart + X + 1 u< guardLimit |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 111 | // |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 112 | // The only way the antecedent can be true and the consequent can be false is |
| 113 | // if |
| 114 | // X == guardLimit - 1 - guardStart |
| 115 | // (and guardLimit is non-zero, but we won't use this latter fact). |
| 116 | // If X == guardLimit - 1 - guardStart then the second half of the antecedent is |
| 117 | // latchStart + guardLimit - 1 - guardStart u< latchLimit |
| 118 | // and its negation is |
| 119 | // latchStart + guardLimit - 1 - guardStart u>= latchLimit |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 120 | // |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 121 | // In other words, if |
| 122 | // latchLimit u<= latchStart + guardLimit - 1 - guardStart |
| 123 | // then: |
| 124 | // (the ranges below are written in ConstantRange notation, where [A, B) is the |
| 125 | // set for (I = A; I != B; I++ /*maywrap*/) yield(I);) |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 126 | // |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 127 | // forall X . guardStart + X u< guardLimit && |
| 128 | // latchStart + X u< latchLimit => |
| 129 | // guardStart + X + 1 u< guardLimit |
| 130 | // == forall X . guardStart + X u< guardLimit && |
| 131 | // latchStart + X u< latchStart + guardLimit - 1 - guardStart => |
| 132 | // guardStart + X + 1 u< guardLimit |
| 133 | // == forall X . (guardStart + X) in [0, guardLimit) && |
| 134 | // (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) => |
| 135 | // (guardStart + X + 1) in [0, guardLimit) |
| 136 | // == forall X . X in [-guardStart, guardLimit - guardStart) && |
| 137 | // X in [-latchStart, guardLimit - 1 - guardStart) => |
| 138 | // X in [-guardStart - 1, guardLimit - guardStart - 1) |
| 139 | // == true |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 140 | // |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 141 | // So the widened condition is: |
| 142 | // guardStart u< guardLimit && |
| 143 | // latchStart + guardLimit - 1 - guardStart u>= latchLimit |
| 144 | // Similarly for ule condition the widened condition is: |
| 145 | // guardStart u< guardLimit && |
| 146 | // latchStart + guardLimit - 1 - guardStart u> latchLimit |
| 147 | // For slt condition the widened condition is: |
| 148 | // guardStart u< guardLimit && |
| 149 | // latchStart + guardLimit - 1 - guardStart s>= latchLimit |
| 150 | // For sle condition the widened condition is: |
| 151 | // guardStart u< guardLimit && |
| 152 | // latchStart + guardLimit - 1 - guardStart s> latchLimit |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 153 | // |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 154 | // When S = -1 (i.e. reverse iterating loop), the transformation is supported |
| 155 | // when: |
| 156 | // * The loop has a single latch with the condition of the form: |
Serguei Katkov | c8016e7 | 2018-02-08 10:34:08 +0000 | [diff] [blame] | 157 | // B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=. |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 158 | // * The guard condition is of the form |
| 159 | // G(X) = X - 1 u< guardLimit |
| 160 | // |
| 161 | // For the ugt latch comparison case M is: |
| 162 | // forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit |
| 163 | // |
| 164 | // The only way the antecedent can be true and the consequent can be false is if |
| 165 | // X == 1. |
| 166 | // If X == 1 then the second half of the antecedent is |
| 167 | // 1 u> latchLimit, and its negation is latchLimit u>= 1. |
| 168 | // |
| 169 | // So the widened condition is: |
| 170 | // guardStart u< guardLimit && latchLimit u>= 1. |
| 171 | // Similarly for sgt condition the widened condition is: |
| 172 | // guardStart u< guardLimit && latchLimit s>= 1. |
Serguei Katkov | c8016e7 | 2018-02-08 10:34:08 +0000 | [diff] [blame] | 173 | // For uge condition the widened condition is: |
| 174 | // guardStart u< guardLimit && latchLimit u> 1. |
| 175 | // For sge condition the widened condition is: |
| 176 | // guardStart u< guardLimit && latchLimit s> 1. |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 177 | //===----------------------------------------------------------------------===// |
| 178 | |
| 179 | #include "llvm/Transforms/Scalar/LoopPredication.h" |
Fedor Sergeev | c297e84 | 2018-10-17 09:02:54 +0000 | [diff] [blame] | 180 | #include "llvm/ADT/Statistic.h" |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 181 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Max Kazantsev | 28298e9 | 2018-12-26 08:22:25 +0000 | [diff] [blame] | 182 | #include "llvm/Analysis/GuardUtils.h" |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 183 | #include "llvm/Analysis/LoopInfo.h" |
| 184 | #include "llvm/Analysis/LoopPass.h" |
| 185 | #include "llvm/Analysis/ScalarEvolution.h" |
| 186 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
| 187 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
| 188 | #include "llvm/IR/Function.h" |
| 189 | #include "llvm/IR/GlobalValue.h" |
| 190 | #include "llvm/IR/IntrinsicInst.h" |
| 191 | #include "llvm/IR/Module.h" |
| 192 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 193 | #include "llvm/Pass.h" |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 194 | #include "llvm/Support/Debug.h" |
| 195 | #include "llvm/Transforms/Scalar.h" |
| 196 | #include "llvm/Transforms/Utils/LoopUtils.h" |
| 197 | |
| 198 | #define DEBUG_TYPE "loop-predication" |
| 199 | |
Fedor Sergeev | c297e84 | 2018-10-17 09:02:54 +0000 | [diff] [blame] | 200 | STATISTIC(TotalConsidered, "Number of guards considered"); |
| 201 | STATISTIC(TotalWidened, "Number of checks widened"); |
| 202 | |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 203 | using namespace llvm; |
| 204 | |
Anna Thomas | 1d02b13 | 2017-11-02 21:21:02 +0000 | [diff] [blame] | 205 | static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation", |
| 206 | cl::Hidden, cl::init(true)); |
| 207 | |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 208 | static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop", |
| 209 | cl::Hidden, cl::init(true)); |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 210 | |
| 211 | static cl::opt<bool> |
| 212 | SkipProfitabilityChecks("loop-predication-skip-profitability-checks", |
| 213 | cl::Hidden, cl::init(false)); |
| 214 | |
| 215 | // This is the scale factor for the latch probability. We use this during |
| 216 | // profitability analysis to find other exiting blocks that have a much higher |
| 217 | // probability of exiting the loop instead of loop exiting via latch. |
| 218 | // This value should be greater than 1 for a sane profitability check. |
| 219 | static cl::opt<float> LatchExitProbabilityScale( |
| 220 | "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0), |
| 221 | cl::desc("scale factor for the latch probability. Value should be greater " |
| 222 | "than 1. Lower values are ignored")); |
| 223 | |
Max Kazantsev | feb475f | 2019-01-22 11:49:06 +0000 | [diff] [blame^] | 224 | static cl::opt<bool> PredicateWidenableBranchGuards( |
| 225 | "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden, |
| 226 | cl::desc("Whether or not we should predicate guards " |
| 227 | "expressed as widenable branches to deoptimize blocks"), |
| 228 | cl::init(true)); |
| 229 | |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 230 | namespace { |
| 231 | class LoopPredication { |
Artur Pilipenko | a6c27804 | 2017-05-19 14:02:46 +0000 | [diff] [blame] | 232 | /// Represents an induction variable check: |
| 233 | /// icmp Pred, <induction variable>, <loop invariant limit> |
| 234 | struct LoopICmp { |
| 235 | ICmpInst::Predicate Pred; |
| 236 | const SCEVAddRecExpr *IV; |
| 237 | const SCEV *Limit; |
Artur Pilipenko | c488dfa | 2017-05-22 12:01:32 +0000 | [diff] [blame] | 238 | LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV, |
| 239 | const SCEV *Limit) |
Artur Pilipenko | a6c27804 | 2017-05-19 14:02:46 +0000 | [diff] [blame] | 240 | : Pred(Pred), IV(IV), Limit(Limit) {} |
| 241 | LoopICmp() {} |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 242 | void dump() { |
| 243 | dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV |
| 244 | << ", Limit = " << *Limit << "\n"; |
| 245 | } |
Artur Pilipenko | a6c27804 | 2017-05-19 14:02:46 +0000 | [diff] [blame] | 246 | }; |
Artur Pilipenko | c488dfa | 2017-05-22 12:01:32 +0000 | [diff] [blame] | 247 | |
| 248 | ScalarEvolution *SE; |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 249 | BranchProbabilityInfo *BPI; |
Artur Pilipenko | c488dfa | 2017-05-22 12:01:32 +0000 | [diff] [blame] | 250 | |
| 251 | Loop *L; |
| 252 | const DataLayout *DL; |
| 253 | BasicBlock *Preheader; |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 254 | LoopICmp LatchCheck; |
Artur Pilipenko | c488dfa | 2017-05-22 12:01:32 +0000 | [diff] [blame] | 255 | |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 256 | bool isSupportedStep(const SCEV* Step); |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 257 | Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) { |
| 258 | return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0), |
| 259 | ICI->getOperand(1)); |
| 260 | } |
| 261 | Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS, |
| 262 | Value *RHS); |
| 263 | |
| 264 | Optional<LoopICmp> parseLoopLatchICmp(); |
Artur Pilipenko | a6c27804 | 2017-05-19 14:02:46 +0000 | [diff] [blame] | 265 | |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 266 | bool CanExpand(const SCEV* S); |
Artur Pilipenko | 6780ba6 | 2017-05-19 14:00:58 +0000 | [diff] [blame] | 267 | Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder, |
| 268 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, |
| 269 | Instruction *InsertAt); |
| 270 | |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 271 | Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, |
| 272 | IRBuilder<> &Builder); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 273 | Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck, |
| 274 | LoopICmp RangeCheck, |
| 275 | SCEVExpander &Expander, |
| 276 | IRBuilder<> &Builder); |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 277 | Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck, |
| 278 | LoopICmp RangeCheck, |
| 279 | SCEVExpander &Expander, |
| 280 | IRBuilder<> &Builder); |
Max Kazantsev | ca45087 | 2019-01-22 10:13:36 +0000 | [diff] [blame] | 281 | unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition, |
| 282 | SCEVExpander &Expander, IRBuilder<> &Builder); |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 283 | bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander); |
Max Kazantsev | feb475f | 2019-01-22 11:49:06 +0000 | [diff] [blame^] | 284 | bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander); |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 285 | // If the loop always exits through another block in the loop, we should not |
| 286 | // predicate based on the latch check. For example, the latch check can be a |
| 287 | // very coarse grained check and there can be more fine grained exit checks |
| 288 | // within the loop. We identify such unprofitable loops through BPI. |
| 289 | bool isLoopProfitableToPredicate(); |
| 290 | |
Anna Thomas | 1d02b13 | 2017-11-02 21:21:02 +0000 | [diff] [blame] | 291 | // When the IV type is wider than the range operand type, we can still do loop |
| 292 | // predication, by generating SCEVs for the range and latch that are of the |
| 293 | // same type. We achieve this by generating a SCEV truncate expression for the |
| 294 | // latch IV. This is done iff truncation of the IV is a safe operation, |
| 295 | // without loss of information. |
| 296 | // Another way to achieve this is by generating a wider type SCEV for the |
| 297 | // range check operand, however, this needs a more involved check that |
| 298 | // operands do not overflow. This can lead to loss of information when the |
| 299 | // range operand is of the form: add i32 %offset, %iv. We need to prove that |
| 300 | // sext(x + y) is same as sext(x) + sext(y). |
| 301 | // This function returns true if we can safely represent the IV type in |
| 302 | // the RangeCheckType without loss of information. |
| 303 | bool isSafeToTruncateWideIVType(Type *RangeCheckType); |
| 304 | // Return the loopLatchCheck corresponding to the RangeCheckType if safe to do |
| 305 | // so. |
| 306 | Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType); |
Serguei Katkov | ebc9031 | 2018-02-07 06:53:37 +0000 | [diff] [blame] | 307 | |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 308 | public: |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 309 | LoopPredication(ScalarEvolution *SE, BranchProbabilityInfo *BPI) |
| 310 | : SE(SE), BPI(BPI){}; |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 311 | bool runOnLoop(Loop *L); |
| 312 | }; |
| 313 | |
| 314 | class LoopPredicationLegacyPass : public LoopPass { |
| 315 | public: |
| 316 | static char ID; |
| 317 | LoopPredicationLegacyPass() : LoopPass(ID) { |
| 318 | initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry()); |
| 319 | } |
| 320 | |
| 321 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 322 | AU.addRequired<BranchProbabilityInfoWrapperPass>(); |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 323 | getLoopAnalysisUsage(AU); |
| 324 | } |
| 325 | |
| 326 | bool runOnLoop(Loop *L, LPPassManager &LPM) override { |
| 327 | if (skipLoop(L)) |
| 328 | return false; |
| 329 | auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 330 | BranchProbabilityInfo &BPI = |
| 331 | getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); |
| 332 | LoopPredication LP(SE, &BPI); |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 333 | return LP.runOnLoop(L); |
| 334 | } |
| 335 | }; |
| 336 | |
| 337 | char LoopPredicationLegacyPass::ID = 0; |
| 338 | } // end namespace llvm |
| 339 | |
| 340 | INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", |
| 341 | "Loop predication", false, false) |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 342 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 343 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
| 344 | INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication", |
| 345 | "Loop predication", false, false) |
| 346 | |
| 347 | Pass *llvm::createLoopPredicationPass() { |
| 348 | return new LoopPredicationLegacyPass(); |
| 349 | } |
| 350 | |
| 351 | PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM, |
| 352 | LoopStandardAnalysisResults &AR, |
| 353 | LPMUpdater &U) { |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 354 | const auto &FAM = |
| 355 | AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); |
| 356 | Function *F = L.getHeader()->getParent(); |
| 357 | auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F); |
| 358 | LoopPredication LP(&AR.SE, BPI); |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 359 | if (!LP.runOnLoop(&L)) |
| 360 | return PreservedAnalyses::all(); |
| 361 | |
| 362 | return getLoopPassPreservedAnalyses(); |
| 363 | } |
| 364 | |
Artur Pilipenko | a6c27804 | 2017-05-19 14:02:46 +0000 | [diff] [blame] | 365 | Optional<LoopPredication::LoopICmp> |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 366 | LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS, |
| 367 | Value *RHS) { |
Artur Pilipenko | a6c27804 | 2017-05-19 14:02:46 +0000 | [diff] [blame] | 368 | const SCEV *LHSS = SE->getSCEV(LHS); |
| 369 | if (isa<SCEVCouldNotCompute>(LHSS)) |
| 370 | return None; |
| 371 | const SCEV *RHSS = SE->getSCEV(RHS); |
| 372 | if (isa<SCEVCouldNotCompute>(RHSS)) |
| 373 | return None; |
| 374 | |
| 375 | // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV |
| 376 | if (SE->isLoopInvariant(LHSS, L)) { |
| 377 | std::swap(LHS, RHS); |
| 378 | std::swap(LHSS, RHSS); |
| 379 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 380 | } |
| 381 | |
| 382 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS); |
| 383 | if (!AR || AR->getLoop() != L) |
| 384 | return None; |
| 385 | |
| 386 | return LoopICmp(Pred, AR, RHSS); |
| 387 | } |
| 388 | |
Artur Pilipenko | 6780ba6 | 2017-05-19 14:00:58 +0000 | [diff] [blame] | 389 | Value *LoopPredication::expandCheck(SCEVExpander &Expander, |
| 390 | IRBuilder<> &Builder, |
| 391 | ICmpInst::Predicate Pred, const SCEV *LHS, |
| 392 | const SCEV *RHS, Instruction *InsertAt) { |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 393 | // TODO: we can check isLoopEntryGuardedByCond before emitting the check |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 394 | |
Artur Pilipenko | 6780ba6 | 2017-05-19 14:00:58 +0000 | [diff] [blame] | 395 | Type *Ty = LHS->getType(); |
| 396 | assert(Ty == RHS->getType() && "expandCheck operands have different types?"); |
Artur Pilipenko | ead69ee | 2017-10-12 21:21:17 +0000 | [diff] [blame] | 397 | |
| 398 | if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS)) |
| 399 | return Builder.getTrue(); |
| 400 | |
Artur Pilipenko | 6780ba6 | 2017-05-19 14:00:58 +0000 | [diff] [blame] | 401 | Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt); |
| 402 | Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt); |
| 403 | return Builder.CreateICmp(Pred, LHSV, RHSV); |
| 404 | } |
| 405 | |
Anna Thomas | 1d02b13 | 2017-11-02 21:21:02 +0000 | [diff] [blame] | 406 | Optional<LoopPredication::LoopICmp> |
| 407 | LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) { |
| 408 | |
| 409 | auto *LatchType = LatchCheck.IV->getType(); |
| 410 | if (RangeCheckType == LatchType) |
| 411 | return LatchCheck; |
| 412 | // For now, bail out if latch type is narrower than range type. |
| 413 | if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType)) |
| 414 | return None; |
| 415 | if (!isSafeToTruncateWideIVType(RangeCheckType)) |
| 416 | return None; |
| 417 | // We can now safely identify the truncated version of the IV and limit for |
| 418 | // RangeCheckType. |
| 419 | LoopICmp NewLatchCheck; |
| 420 | NewLatchCheck.Pred = LatchCheck.Pred; |
| 421 | NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>( |
| 422 | SE->getTruncateExpr(LatchCheck.IV, RangeCheckType)); |
| 423 | if (!NewLatchCheck.IV) |
| 424 | return None; |
| 425 | NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 426 | LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType |
| 427 | << "can be represented as range check type:" |
| 428 | << *RangeCheckType << "\n"); |
| 429 | LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n"); |
| 430 | LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n"); |
Anna Thomas | 1d02b13 | 2017-11-02 21:21:02 +0000 | [diff] [blame] | 431 | return NewLatchCheck; |
| 432 | } |
| 433 | |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 434 | bool LoopPredication::isSupportedStep(const SCEV* Step) { |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 435 | return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 436 | } |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 437 | |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 438 | bool LoopPredication::CanExpand(const SCEV* S) { |
| 439 | return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE); |
| 440 | } |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 441 | |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 442 | Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop( |
| 443 | LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck, |
| 444 | SCEVExpander &Expander, IRBuilder<> &Builder) { |
| 445 | auto *Ty = RangeCheck.IV->getType(); |
| 446 | // Generate the widened condition for the forward loop: |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 447 | // guardStart u< guardLimit && |
| 448 | // latchLimit <pred> guardLimit - 1 - guardStart + latchStart |
Artur Pilipenko | b4527e1 | 2017-10-12 20:40:27 +0000 | [diff] [blame] | 449 | // where <pred> depends on the latch condition predicate. See the file |
| 450 | // header comment for the reasoning. |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 451 | // guardLimit - guardStart + latchStart - 1 |
| 452 | const SCEV *GuardStart = RangeCheck.IV->getStart(); |
| 453 | const SCEV *GuardLimit = RangeCheck.Limit; |
| 454 | const SCEV *LatchStart = LatchCheck.IV->getStart(); |
| 455 | const SCEV *LatchLimit = LatchCheck.Limit; |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 456 | |
| 457 | // guardLimit - guardStart + latchStart - 1 |
| 458 | const SCEV *RHS = |
| 459 | SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart), |
| 460 | SE->getMinusSCEV(LatchStart, SE->getOne(Ty))); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 461 | if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) || |
| 462 | !CanExpand(LatchLimit) || !CanExpand(RHS)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 463 | LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 464 | return None; |
| 465 | } |
Serguei Katkov | 3cb4c34 | 2018-02-09 07:59:07 +0000 | [diff] [blame] | 466 | auto LimitCheckPred = |
| 467 | ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); |
Artur Pilipenko | aab2866 | 2017-05-19 14:00:04 +0000 | [diff] [blame] | 468 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 469 | LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n"); |
| 470 | LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n"); |
| 471 | LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n"); |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 472 | |
Artur Pilipenko | 0860bfc | 2017-02-27 15:44:49 +0000 | [diff] [blame] | 473 | Instruction *InsertAt = Preheader->getTerminator(); |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 474 | auto *LimitCheck = |
| 475 | expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS, InsertAt); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 476 | auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck.Pred, |
Artur Pilipenko | 8aadc64 | 2017-10-27 14:46:17 +0000 | [diff] [blame] | 477 | GuardStart, GuardLimit, InsertAt); |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 478 | return Builder.CreateAnd(FirstIterationCheck, LimitCheck); |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 479 | } |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 480 | |
| 481 | Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop( |
| 482 | LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck, |
| 483 | SCEVExpander &Expander, IRBuilder<> &Builder) { |
| 484 | auto *Ty = RangeCheck.IV->getType(); |
| 485 | const SCEV *GuardStart = RangeCheck.IV->getStart(); |
| 486 | const SCEV *GuardLimit = RangeCheck.Limit; |
| 487 | const SCEV *LatchLimit = LatchCheck.Limit; |
| 488 | if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) || |
| 489 | !CanExpand(LatchLimit)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 490 | LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 491 | return None; |
| 492 | } |
| 493 | // The decrement of the latch check IV should be the same as the |
| 494 | // rangeCheckIV. |
| 495 | auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE); |
| 496 | if (RangeCheck.IV != PostDecLatchCheckIV) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 497 | LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: " |
| 498 | << *PostDecLatchCheckIV |
| 499 | << " and RangeCheckIV: " << *RangeCheck.IV << "\n"); |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 500 | return None; |
| 501 | } |
| 502 | |
| 503 | // Generate the widened condition for CountDownLoop: |
| 504 | // guardStart u< guardLimit && |
| 505 | // latchLimit <pred> 1. |
| 506 | // See the header comment for reasoning of the checks. |
| 507 | Instruction *InsertAt = Preheader->getTerminator(); |
Serguei Katkov | 3cb4c34 | 2018-02-09 07:59:07 +0000 | [diff] [blame] | 508 | auto LimitCheckPred = |
| 509 | ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 510 | auto *FirstIterationCheck = expandCheck(Expander, Builder, ICmpInst::ICMP_ULT, |
| 511 | GuardStart, GuardLimit, InsertAt); |
| 512 | auto *LimitCheck = expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, |
| 513 | SE->getOne(Ty), InsertAt); |
| 514 | return Builder.CreateAnd(FirstIterationCheck, LimitCheck); |
| 515 | } |
| 516 | |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 517 | /// If ICI can be widened to a loop invariant condition emits the loop |
| 518 | /// invariant condition in the loop preheader and return it, otherwise |
| 519 | /// returns None. |
| 520 | Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, |
| 521 | SCEVExpander &Expander, |
| 522 | IRBuilder<> &Builder) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 523 | LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n"); |
| 524 | LLVM_DEBUG(ICI->dump()); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 525 | |
| 526 | // parseLoopStructure guarantees that the latch condition is: |
| 527 | // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=. |
| 528 | // We are looking for the range checks of the form: |
| 529 | // i u< guardLimit |
| 530 | auto RangeCheck = parseLoopICmp(ICI); |
| 531 | if (!RangeCheck) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 532 | LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 533 | return None; |
| 534 | } |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 535 | LLVM_DEBUG(dbgs() << "Guard check:\n"); |
| 536 | LLVM_DEBUG(RangeCheck->dump()); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 537 | if (RangeCheck->Pred != ICmpInst::ICMP_ULT) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 538 | LLVM_DEBUG(dbgs() << "Unsupported range check predicate(" |
| 539 | << RangeCheck->Pred << ")!\n"); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 540 | return None; |
| 541 | } |
| 542 | auto *RangeCheckIV = RangeCheck->IV; |
| 543 | if (!RangeCheckIV->isAffine()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 544 | LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n"); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 545 | return None; |
| 546 | } |
| 547 | auto *Step = RangeCheckIV->getStepRecurrence(*SE); |
| 548 | // We cannot just compare with latch IV step because the latch and range IVs |
| 549 | // may have different types. |
| 550 | if (!isSupportedStep(Step)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 551 | LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n"); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 552 | return None; |
| 553 | } |
| 554 | auto *Ty = RangeCheckIV->getType(); |
| 555 | auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty); |
| 556 | if (!CurrLatchCheckOpt) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 557 | LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check " |
| 558 | "corresponding to range type: " |
| 559 | << *Ty << "\n"); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 560 | return None; |
| 561 | } |
| 562 | |
| 563 | LoopICmp CurrLatchCheck = *CurrLatchCheckOpt; |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 564 | // At this point, the range and latch step should have the same type, but need |
| 565 | // not have the same value (we support both 1 and -1 steps). |
| 566 | assert(Step->getType() == |
| 567 | CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() && |
| 568 | "Range and latch steps should be of same type!"); |
| 569 | if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 570 | LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n"); |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 571 | return None; |
| 572 | } |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 573 | |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 574 | if (Step->isOne()) |
| 575 | return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck, |
| 576 | Expander, Builder); |
| 577 | else { |
| 578 | assert(Step->isAllOnesValue() && "Step should be -1!"); |
| 579 | return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck, |
| 580 | Expander, Builder); |
| 581 | } |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 582 | } |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 583 | |
Max Kazantsev | ca45087 | 2019-01-22 10:13:36 +0000 | [diff] [blame] | 584 | unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks, |
| 585 | Value *Condition, |
| 586 | SCEVExpander &Expander, |
| 587 | IRBuilder<> &Builder) { |
| 588 | unsigned NumWidened = 0; |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 589 | // The guard condition is expected to be in form of: |
| 590 | // cond1 && cond2 && cond3 ... |
Hiroshi Inoue | 0909ca1 | 2018-01-26 08:15:29 +0000 | [diff] [blame] | 591 | // Iterate over subconditions looking for icmp conditions which can be |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 592 | // widened across loop iterations. Widening these conditions remember the |
| 593 | // resulting list of subconditions in Checks vector. |
Max Kazantsev | ca45087 | 2019-01-22 10:13:36 +0000 | [diff] [blame] | 594 | SmallVector<Value *, 4> Worklist(1, Condition); |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 595 | SmallPtrSet<Value *, 4> Visited; |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 596 | do { |
| 597 | Value *Condition = Worklist.pop_back_val(); |
| 598 | if (!Visited.insert(Condition).second) |
| 599 | continue; |
| 600 | |
| 601 | Value *LHS, *RHS; |
| 602 | using namespace llvm::PatternMatch; |
| 603 | if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) { |
| 604 | Worklist.push_back(LHS); |
| 605 | Worklist.push_back(RHS); |
| 606 | continue; |
| 607 | } |
| 608 | |
| 609 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) { |
| 610 | if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) { |
| 611 | Checks.push_back(NewRangeCheck.getValue()); |
| 612 | NumWidened++; |
| 613 | continue; |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | // Save the condition as is if we can't widen it |
| 618 | Checks.push_back(Condition); |
Max Kazantsev | ca45087 | 2019-01-22 10:13:36 +0000 | [diff] [blame] | 619 | } while (!Worklist.empty()); |
| 620 | return NumWidened; |
| 621 | } |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 622 | |
Max Kazantsev | ca45087 | 2019-01-22 10:13:36 +0000 | [diff] [blame] | 623 | bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard, |
| 624 | SCEVExpander &Expander) { |
| 625 | LLVM_DEBUG(dbgs() << "Processing guard:\n"); |
| 626 | LLVM_DEBUG(Guard->dump()); |
| 627 | |
| 628 | TotalConsidered++; |
| 629 | SmallVector<Value *, 4> Checks; |
| 630 | IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator())); |
| 631 | unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander, |
| 632 | Builder); |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 633 | if (NumWidened == 0) |
| 634 | return false; |
| 635 | |
Fedor Sergeev | c297e84 | 2018-10-17 09:02:54 +0000 | [diff] [blame] | 636 | TotalWidened += NumWidened; |
| 637 | |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 638 | // Emit the new guard condition |
| 639 | Builder.SetInsertPoint(Guard); |
| 640 | Value *LastCheck = nullptr; |
| 641 | for (auto *Check : Checks) |
| 642 | if (!LastCheck) |
| 643 | LastCheck = Check; |
| 644 | else |
| 645 | LastCheck = Builder.CreateAnd(LastCheck, Check); |
| 646 | Guard->setOperand(0, LastCheck); |
| 647 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 648 | LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 649 | return true; |
| 650 | } |
| 651 | |
Max Kazantsev | feb475f | 2019-01-22 11:49:06 +0000 | [diff] [blame^] | 652 | bool LoopPredication::widenWidenableBranchGuardConditions( |
| 653 | BranchInst *Guard, SCEVExpander &Expander) { |
| 654 | assert(isGuardAsWidenableBranch(Guard) && "Must be!"); |
| 655 | LLVM_DEBUG(dbgs() << "Processing guard:\n"); |
| 656 | LLVM_DEBUG(Guard->dump()); |
| 657 | |
| 658 | TotalConsidered++; |
| 659 | SmallVector<Value *, 4> Checks; |
| 660 | IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator())); |
| 661 | Value *Condition = nullptr, *WidenableCondition = nullptr; |
| 662 | BasicBlock *GBB = nullptr, *DBB = nullptr; |
| 663 | parseWidenableBranch(Guard, Condition, WidenableCondition, GBB, DBB); |
| 664 | unsigned NumWidened = collectChecks(Checks, Condition, Expander, Builder); |
| 665 | if (NumWidened == 0) |
| 666 | return false; |
| 667 | |
| 668 | TotalWidened += NumWidened; |
| 669 | |
| 670 | // Emit the new guard condition |
| 671 | Builder.SetInsertPoint(Guard); |
| 672 | Value *LastCheck = nullptr; |
| 673 | for (auto *Check : Checks) |
| 674 | if (!LastCheck) |
| 675 | LastCheck = Check; |
| 676 | else |
| 677 | LastCheck = Builder.CreateAnd(LastCheck, Check); |
| 678 | // Make sure that the check contains widenable condition and therefore can be |
| 679 | // further widened. |
| 680 | LastCheck = Builder.CreateAnd(LastCheck, WidenableCondition); |
| 681 | Guard->setOperand(0, LastCheck); |
| 682 | assert(isGuardAsWidenableBranch(Guard) && |
| 683 | "Stopped being a guard after transform?"); |
| 684 | |
| 685 | LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); |
| 686 | return true; |
| 687 | } |
| 688 | |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 689 | Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() { |
| 690 | using namespace PatternMatch; |
| 691 | |
| 692 | BasicBlock *LoopLatch = L->getLoopLatch(); |
| 693 | if (!LoopLatch) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 694 | LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n"); |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 695 | return None; |
| 696 | } |
| 697 | |
| 698 | ICmpInst::Predicate Pred; |
| 699 | Value *LHS, *RHS; |
| 700 | BasicBlock *TrueDest, *FalseDest; |
| 701 | |
| 702 | if (!match(LoopLatch->getTerminator(), |
| 703 | m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest, |
| 704 | FalseDest))) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 705 | LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n"); |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 706 | return None; |
| 707 | } |
| 708 | assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) && |
| 709 | "One of the latch's destinations must be the header"); |
| 710 | if (TrueDest != L->getHeader()) |
| 711 | Pred = ICmpInst::getInversePredicate(Pred); |
| 712 | |
| 713 | auto Result = parseLoopICmp(Pred, LHS, RHS); |
| 714 | if (!Result) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 715 | LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 716 | return None; |
| 717 | } |
| 718 | |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 719 | // Check affine first, so if it's not we don't try to compute the step |
| 720 | // recurrence. |
| 721 | if (!Result->IV->isAffine()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 722 | LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n"); |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 723 | return None; |
| 724 | } |
| 725 | |
| 726 | auto *Step = Result->IV->getStepRecurrence(*SE); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 727 | if (!isSupportedStep(Step)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 728 | LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n"); |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 729 | return None; |
| 730 | } |
| 731 | |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 732 | auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) { |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 733 | if (Step->isOne()) { |
| 734 | return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT && |
| 735 | Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE; |
| 736 | } else { |
| 737 | assert(Step->isAllOnesValue() && "Step should be -1!"); |
Serguei Katkov | c8016e7 | 2018-02-08 10:34:08 +0000 | [diff] [blame] | 738 | return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT && |
| 739 | Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE; |
Anna Thomas | 7b36043 | 2017-12-04 15:11:48 +0000 | [diff] [blame] | 740 | } |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 741 | }; |
| 742 | |
| 743 | if (IsUnsupportedPredicate(Step, Result->Pred)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 744 | LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred |
| 745 | << ")!\n"); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 746 | return None; |
| 747 | } |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 748 | return Result; |
| 749 | } |
| 750 | |
Anna Thomas | 1d02b13 | 2017-11-02 21:21:02 +0000 | [diff] [blame] | 751 | // Returns true if its safe to truncate the IV to RangeCheckType. |
| 752 | bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) { |
| 753 | if (!EnableIVTruncation) |
| 754 | return false; |
| 755 | assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) > |
| 756 | DL->getTypeSizeInBits(RangeCheckType) && |
| 757 | "Expected latch check IV type to be larger than range check operand " |
| 758 | "type!"); |
| 759 | // The start and end values of the IV should be known. This is to guarantee |
| 760 | // that truncating the wide type will not lose information. |
| 761 | auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit); |
| 762 | auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart()); |
| 763 | if (!Limit || !Start) |
| 764 | return false; |
| 765 | // This check makes sure that the IV does not change sign during loop |
| 766 | // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE, |
| 767 | // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the |
| 768 | // IV wraps around, and the truncation of the IV would lose the range of |
| 769 | // iterations between 2^32 and 2^64. |
| 770 | bool Increasing; |
| 771 | if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing)) |
| 772 | return false; |
| 773 | // The active bits should be less than the bits in the RangeCheckType. This |
| 774 | // guarantees that truncating the latch check to RangeCheckType is a safe |
| 775 | // operation. |
| 776 | auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType); |
| 777 | return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize && |
| 778 | Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize; |
| 779 | } |
| 780 | |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 781 | bool LoopPredication::isLoopProfitableToPredicate() { |
| 782 | if (SkipProfitabilityChecks || !BPI) |
| 783 | return true; |
| 784 | |
| 785 | SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 8> ExitEdges; |
| 786 | L->getExitEdges(ExitEdges); |
| 787 | // If there is only one exiting edge in the loop, it is always profitable to |
| 788 | // predicate the loop. |
| 789 | if (ExitEdges.size() == 1) |
| 790 | return true; |
| 791 | |
| 792 | // Calculate the exiting probabilities of all exiting edges from the loop, |
| 793 | // starting with the LatchExitProbability. |
| 794 | // Heuristic for profitability: If any of the exiting blocks' probability of |
| 795 | // exiting the loop is larger than exiting through the latch block, it's not |
| 796 | // profitable to predicate the loop. |
| 797 | auto *LatchBlock = L->getLoopLatch(); |
| 798 | assert(LatchBlock && "Should have a single latch at this point!"); |
| 799 | auto *LatchTerm = LatchBlock->getTerminator(); |
| 800 | assert(LatchTerm->getNumSuccessors() == 2 && |
| 801 | "expected to be an exiting block with 2 succs!"); |
| 802 | unsigned LatchBrExitIdx = |
| 803 | LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0; |
| 804 | BranchProbability LatchExitProbability = |
| 805 | BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx); |
| 806 | |
| 807 | // Protect against degenerate inputs provided by the user. Providing a value |
| 808 | // less than one, can invert the definition of profitable loop predication. |
| 809 | float ScaleFactor = LatchExitProbabilityScale; |
| 810 | if (ScaleFactor < 1) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 811 | LLVM_DEBUG( |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 812 | dbgs() |
| 813 | << "Ignored user setting for loop-predication-latch-probability-scale: " |
| 814 | << LatchExitProbabilityScale << "\n"); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 815 | LLVM_DEBUG(dbgs() << "The value is set to 1.0\n"); |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 816 | ScaleFactor = 1.0; |
| 817 | } |
| 818 | const auto LatchProbabilityThreshold = |
| 819 | LatchExitProbability * ScaleFactor; |
| 820 | |
| 821 | for (const auto &ExitEdge : ExitEdges) { |
| 822 | BranchProbability ExitingBlockProbability = |
| 823 | BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second); |
| 824 | // Some exiting edge has higher probability than the latch exiting edge. |
| 825 | // No longer profitable to predicate. |
| 826 | if (ExitingBlockProbability > LatchProbabilityThreshold) |
| 827 | return false; |
| 828 | } |
| 829 | // Using BPI, we have concluded that the most probable way to exit from the |
| 830 | // loop is through the latch (or there's no profile information and all |
| 831 | // exits are equally likely). |
| 832 | return true; |
| 833 | } |
| 834 | |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 835 | bool LoopPredication::runOnLoop(Loop *Loop) { |
| 836 | L = Loop; |
| 837 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 838 | LLVM_DEBUG(dbgs() << "Analyzing "); |
| 839 | LLVM_DEBUG(L->dump()); |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 840 | |
| 841 | Module *M = L->getHeader()->getModule(); |
| 842 | |
| 843 | // There is nothing to do if the module doesn't use guards |
| 844 | auto *GuardDecl = |
| 845 | M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard)); |
Max Kazantsev | feb475f | 2019-01-22 11:49:06 +0000 | [diff] [blame^] | 846 | bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty(); |
| 847 | auto *WCDecl = M->getFunction( |
| 848 | Intrinsic::getName(Intrinsic::experimental_widenable_condition)); |
| 849 | bool HasWidenableConditions = |
| 850 | PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty(); |
| 851 | if (!HasIntrinsicGuards && !HasWidenableConditions) |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 852 | return false; |
| 853 | |
| 854 | DL = &M->getDataLayout(); |
| 855 | |
| 856 | Preheader = L->getLoopPreheader(); |
| 857 | if (!Preheader) |
| 858 | return false; |
| 859 | |
Artur Pilipenko | 889dc1e | 2017-09-22 13:13:57 +0000 | [diff] [blame] | 860 | auto LatchCheckOpt = parseLoopLatchICmp(); |
| 861 | if (!LatchCheckOpt) |
| 862 | return false; |
| 863 | LatchCheck = *LatchCheckOpt; |
| 864 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 865 | LLVM_DEBUG(dbgs() << "Latch check:\n"); |
| 866 | LLVM_DEBUG(LatchCheck.dump()); |
Anna Thomas | 6879721 | 2017-11-03 14:25:39 +0000 | [diff] [blame] | 867 | |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 868 | if (!isLoopProfitableToPredicate()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 869 | LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n"); |
Anna Thomas | 9b1176b | 2018-03-22 16:03:59 +0000 | [diff] [blame] | 870 | return false; |
| 871 | } |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 872 | // Collect all the guards into a vector and process later, so as not |
| 873 | // to invalidate the instruction iterator. |
| 874 | SmallVector<IntrinsicInst *, 4> Guards; |
Max Kazantsev | feb475f | 2019-01-22 11:49:06 +0000 | [diff] [blame^] | 875 | SmallVector<BranchInst *, 4> GuardsAsWidenableBranches; |
| 876 | for (const auto BB : L->blocks()) { |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 877 | for (auto &I : *BB) |
Max Kazantsev | 28298e9 | 2018-12-26 08:22:25 +0000 | [diff] [blame] | 878 | if (isGuard(&I)) |
| 879 | Guards.push_back(cast<IntrinsicInst>(&I)); |
Max Kazantsev | feb475f | 2019-01-22 11:49:06 +0000 | [diff] [blame^] | 880 | if (PredicateWidenableBranchGuards && |
| 881 | isGuardAsWidenableBranch(BB->getTerminator())) |
| 882 | GuardsAsWidenableBranches.push_back( |
| 883 | cast<BranchInst>(BB->getTerminator())); |
| 884 | } |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 885 | |
Max Kazantsev | feb475f | 2019-01-22 11:49:06 +0000 | [diff] [blame^] | 886 | if (Guards.empty() && GuardsAsWidenableBranches.empty()) |
Artur Pilipenko | 46c4e0a | 2017-05-19 13:59:34 +0000 | [diff] [blame] | 887 | return false; |
| 888 | |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 889 | SCEVExpander Expander(*SE, *DL, "loop-predication"); |
| 890 | |
| 891 | bool Changed = false; |
| 892 | for (auto *Guard : Guards) |
| 893 | Changed |= widenGuardConditions(Guard, Expander); |
Max Kazantsev | feb475f | 2019-01-22 11:49:06 +0000 | [diff] [blame^] | 894 | for (auto *Guard : GuardsAsWidenableBranches) |
| 895 | Changed |= widenWidenableBranchGuardConditions(Guard, Expander); |
Artur Pilipenko | 8fb3d57 | 2017-01-25 16:00:44 +0000 | [diff] [blame] | 896 | |
| 897 | return Changed; |
| 898 | } |