Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1 | //===-- InductiveRangeCheckElimination.cpp - ------------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // The InductiveRangeCheckElimination pass splits a loop's iteration space into |
| 10 | // three disjoint ranges. It does that in a way such that the loop running in |
| 11 | // the middle loop provably does not need range checks. As an example, it will |
| 12 | // convert |
| 13 | // |
| 14 | // len = < known positive > |
| 15 | // for (i = 0; i < n; i++) { |
| 16 | // if (0 <= i && i < len) { |
| 17 | // do_something(); |
| 18 | // } else { |
| 19 | // throw_out_of_bounds(); |
| 20 | // } |
| 21 | // } |
| 22 | // |
| 23 | // to |
| 24 | // |
| 25 | // len = < known positive > |
| 26 | // limit = smin(n, len) |
| 27 | // // no first segment |
| 28 | // for (i = 0; i < limit; i++) { |
| 29 | // if (0 <= i && i < len) { // this check is fully redundant |
| 30 | // do_something(); |
| 31 | // } else { |
| 32 | // throw_out_of_bounds(); |
| 33 | // } |
| 34 | // } |
| 35 | // for (i = limit; i < n; i++) { |
| 36 | // if (0 <= i && i < len) { |
| 37 | // do_something(); |
| 38 | // } else { |
| 39 | // throw_out_of_bounds(); |
| 40 | // } |
| 41 | // } |
| 42 | //===----------------------------------------------------------------------===// |
| 43 | |
| 44 | #include "llvm/ADT/Optional.h" |
Sanjoy Das | dcf2651 | 2015-01-27 21:38:12 +0000 | [diff] [blame] | 45 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 46 | #include "llvm/Analysis/InstructionSimplify.h" |
| 47 | #include "llvm/Analysis/LoopInfo.h" |
| 48 | #include "llvm/Analysis/LoopPass.h" |
| 49 | #include "llvm/Analysis/ScalarEvolution.h" |
| 50 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
| 51 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
| 52 | #include "llvm/Analysis/ValueTracking.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 53 | #include "llvm/IR/Dominators.h" |
| 54 | #include "llvm/IR/Function.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 55 | #include "llvm/IR/IRBuilder.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 56 | #include "llvm/IR/Instructions.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 57 | #include "llvm/IR/Module.h" |
| 58 | #include "llvm/IR/PatternMatch.h" |
| 59 | #include "llvm/IR/ValueHandle.h" |
| 60 | #include "llvm/IR/Verifier.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 61 | #include "llvm/Pass.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 62 | #include "llvm/Support/Debug.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 63 | #include "llvm/Support/raw_ostream.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 64 | #include "llvm/Transforms/Scalar.h" |
| 65 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 66 | #include "llvm/Transforms/Utils/Cloning.h" |
| 67 | #include "llvm/Transforms/Utils/LoopUtils.h" |
| 68 | #include "llvm/Transforms/Utils/SimplifyIndVar.h" |
| 69 | #include "llvm/Transforms/Utils/UnrollLoop.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 70 | |
| 71 | using namespace llvm; |
| 72 | |
Benjamin Kramer | 970eac4 | 2015-02-06 17:51:54 +0000 | [diff] [blame] | 73 | static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden, |
| 74 | cl::init(64)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 75 | |
Benjamin Kramer | 970eac4 | 2015-02-06 17:51:54 +0000 | [diff] [blame] | 76 | static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden, |
| 77 | cl::init(false)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 78 | |
Sanjoy Das | 9c1bfae | 2015-03-17 01:40:22 +0000 | [diff] [blame] | 79 | static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden, |
| 80 | cl::init(false)); |
| 81 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 82 | static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal", |
| 83 | cl::Hidden, cl::init(10)); |
| 84 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 85 | #define DEBUG_TYPE "irce" |
| 86 | |
| 87 | namespace { |
| 88 | |
| 89 | /// An inductive range check is conditional branch in a loop with |
| 90 | /// |
| 91 | /// 1. a very cold successor (i.e. the branch jumps to that successor very |
| 92 | /// rarely) |
| 93 | /// |
| 94 | /// and |
| 95 | /// |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 96 | /// 2. a condition that is provably true for some contiguous range of values |
| 97 | /// taken by the containing loop's induction variable. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 98 | /// |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 99 | class InductiveRangeCheck { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 100 | // Classifies a range check |
Reid Kleckner | 0b16859 | 2015-03-17 16:50:20 +0000 | [diff] [blame] | 101 | enum RangeCheckKind : unsigned { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 102 | // Range check of the form "0 <= I". |
| 103 | RANGE_CHECK_LOWER = 1, |
| 104 | |
| 105 | // Range check of the form "I < L" where L is known positive. |
| 106 | RANGE_CHECK_UPPER = 2, |
| 107 | |
| 108 | // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER |
| 109 | // conditions. |
| 110 | RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER, |
| 111 | |
| 112 | // Unrecognized range check condition. |
| 113 | RANGE_CHECK_UNKNOWN = (unsigned)-1 |
| 114 | }; |
| 115 | |
Sanjoy Das | 2eac48d | 2016-03-09 02:34:19 +0000 | [diff] [blame] | 116 | static StringRef rangeCheckKindToStr(RangeCheckKind); |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 117 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 118 | const SCEV *Offset; |
| 119 | const SCEV *Scale; |
| 120 | Value *Length; |
Sanjoy Das | aa83c47 | 2016-05-23 22:16:45 +0000 | [diff] [blame] | 121 | Use *CheckUse; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 122 | RangeCheckKind Kind; |
| 123 | |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 124 | static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI, |
| 125 | ScalarEvolution &SE, Value *&Index, |
| 126 | Value *&Length); |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 127 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 128 | static void |
| 129 | extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse, |
| 130 | SmallVectorImpl<InductiveRangeCheck> &Checks, |
| 131 | SmallPtrSetImpl<Value *> &Visited); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 132 | |
Sanjoy Das | aa83c47 | 2016-05-23 22:16:45 +0000 | [diff] [blame] | 133 | InductiveRangeCheck() |
| 134 | : Offset(nullptr), Scale(nullptr), Length(nullptr), |
| 135 | CheckUse(nullptr) {} |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 136 | |
| 137 | public: |
| 138 | const SCEV *getOffset() const { return Offset; } |
| 139 | const SCEV *getScale() const { return Scale; } |
| 140 | Value *getLength() const { return Length; } |
| 141 | |
| 142 | void print(raw_ostream &OS) const { |
| 143 | OS << "InductiveRangeCheck:\n"; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 144 | OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n"; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 145 | OS << " Offset: "; |
| 146 | Offset->print(OS); |
| 147 | OS << " Scale: "; |
| 148 | Scale->print(OS); |
| 149 | OS << " Length: "; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 150 | if (Length) |
| 151 | Length->print(OS); |
| 152 | else |
| 153 | OS << "(null)"; |
Sanjoy Das | aa83c47 | 2016-05-23 22:16:45 +0000 | [diff] [blame] | 154 | OS << "\n CheckUse: "; |
| 155 | getCheckUse()->getUser()->print(OS); |
| 156 | OS << " Operand: " << getCheckUse()->getOperandNo() << "\n"; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 157 | } |
| 158 | |
| 159 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 160 | void dump() { |
| 161 | print(dbgs()); |
| 162 | } |
| 163 | #endif |
| 164 | |
Sanjoy Das | aa83c47 | 2016-05-23 22:16:45 +0000 | [diff] [blame] | 165 | Use *getCheckUse() const { return CheckUse; } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 166 | |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 167 | /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If |
| 168 | /// R.getEnd() sle R.getBegin(), then R denotes the empty range. |
| 169 | |
| 170 | class Range { |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 171 | const SCEV *Begin; |
| 172 | const SCEV *End; |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 173 | |
| 174 | public: |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 175 | Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) { |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 176 | assert(Begin->getType() == End->getType() && "ill-typed range!"); |
| 177 | } |
| 178 | |
| 179 | Type *getType() const { return Begin->getType(); } |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 180 | const SCEV *getBegin() const { return Begin; } |
| 181 | const SCEV *getEnd() const { return End; } |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 182 | }; |
| 183 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 184 | /// This is the value the condition of the branch needs to evaluate to for the |
| 185 | /// branch to take the hot successor (see (1) above). |
| 186 | bool getPassingDirection() { return true; } |
| 187 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 188 | /// Computes a range for the induction variable (IndVar) in which the range |
| 189 | /// check is redundant and can be constant-folded away. The induction |
| 190 | /// variable is not required to be the canonical {0,+,1} induction variable. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 191 | Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE, |
Sanjoy Das | 5977673 | 2016-05-21 02:31:51 +0000 | [diff] [blame] | 192 | const SCEVAddRecExpr *IndVar) const; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 193 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 194 | /// Parse out a set of inductive range checks from \p BI and append them to \p |
| 195 | /// Checks. |
| 196 | /// |
| 197 | /// NB! There may be conditions feeding into \p BI that aren't inductive range |
| 198 | /// checks, and hence don't end up in \p Checks. |
| 199 | static void |
| 200 | extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE, |
| 201 | BranchProbabilityInfo &BPI, |
| 202 | SmallVectorImpl<InductiveRangeCheck> &Checks); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 203 | }; |
| 204 | |
| 205 | class InductiveRangeCheckElimination : public LoopPass { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 206 | public: |
| 207 | static char ID; |
| 208 | InductiveRangeCheckElimination() : LoopPass(ID) { |
| 209 | initializeInductiveRangeCheckEliminationPass( |
| 210 | *PassRegistry::getPassRegistry()); |
| 211 | } |
| 212 | |
| 213 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 214 | AU.addRequired<BranchProbabilityInfoWrapperPass>(); |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 215 | getLoopAnalysisUsage(AU); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 216 | } |
| 217 | |
| 218 | bool runOnLoop(Loop *L, LPPassManager &LPM) override; |
| 219 | }; |
| 220 | |
| 221 | char InductiveRangeCheckElimination::ID = 0; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 222 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 223 | |
Sanjoy Das | da0d79e | 2015-09-09 03:47:18 +0000 | [diff] [blame] | 224 | INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce", |
| 225 | "Inductive range check elimination", false, false) |
Sanjoy Das | da0d79e | 2015-09-09 03:47:18 +0000 | [diff] [blame] | 226 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 227 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Sanjoy Das | da0d79e | 2015-09-09 03:47:18 +0000 | [diff] [blame] | 228 | INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce", |
| 229 | "Inductive range check elimination", false, false) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 230 | |
Sanjoy Das | 2eac48d | 2016-03-09 02:34:19 +0000 | [diff] [blame] | 231 | StringRef InductiveRangeCheck::rangeCheckKindToStr( |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 232 | InductiveRangeCheck::RangeCheckKind RCK) { |
| 233 | switch (RCK) { |
| 234 | case InductiveRangeCheck::RANGE_CHECK_UNKNOWN: |
| 235 | return "RANGE_CHECK_UNKNOWN"; |
| 236 | |
| 237 | case InductiveRangeCheck::RANGE_CHECK_UPPER: |
| 238 | return "RANGE_CHECK_UPPER"; |
| 239 | |
| 240 | case InductiveRangeCheck::RANGE_CHECK_LOWER: |
| 241 | return "RANGE_CHECK_LOWER"; |
| 242 | |
| 243 | case InductiveRangeCheck::RANGE_CHECK_BOTH: |
| 244 | return "RANGE_CHECK_BOTH"; |
| 245 | } |
| 246 | |
| 247 | llvm_unreachable("unknown range check type!"); |
| 248 | } |
| 249 | |
Sanjoy Das | f13900f | 2016-03-09 02:34:15 +0000 | [diff] [blame] | 250 | /// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 251 | /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set |
Sanjoy Das | f13900f | 2016-03-09 02:34:15 +0000 | [diff] [blame] | 252 | /// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 253 | /// range checked, and set `Length` to the upper limit `Index` is being range |
| 254 | /// checked with if (and only if) the range check type is stronger or equal to |
| 255 | /// RANGE_CHECK_UPPER. |
| 256 | /// |
| 257 | InductiveRangeCheck::RangeCheckKind |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 258 | InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI, |
| 259 | ScalarEvolution &SE, Value *&Index, |
| 260 | Value *&Length) { |
| 261 | |
| 262 | auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) { |
| 263 | const SCEV *S = SE.getSCEV(V); |
| 264 | if (isa<SCEVCouldNotCompute>(S)) |
| 265 | return false; |
| 266 | |
| 267 | return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant && |
| 268 | SE.isKnownNonNegative(S); |
| 269 | }; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 270 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 271 | using namespace llvm::PatternMatch; |
| 272 | |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 273 | ICmpInst::Predicate Pred = ICI->getPredicate(); |
| 274 | Value *LHS = ICI->getOperand(0); |
| 275 | Value *RHS = ICI->getOperand(1); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 276 | |
| 277 | switch (Pred) { |
| 278 | default: |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 279 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 280 | |
| 281 | case ICmpInst::ICMP_SLE: |
| 282 | std::swap(LHS, RHS); |
| 283 | // fallthrough |
| 284 | case ICmpInst::ICMP_SGE: |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 285 | if (match(RHS, m_ConstantInt<0>())) { |
| 286 | Index = LHS; |
| 287 | return RANGE_CHECK_LOWER; |
| 288 | } |
| 289 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 290 | |
| 291 | case ICmpInst::ICMP_SLT: |
| 292 | std::swap(LHS, RHS); |
| 293 | // fallthrough |
| 294 | case ICmpInst::ICMP_SGT: |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 295 | if (match(RHS, m_ConstantInt<-1>())) { |
| 296 | Index = LHS; |
| 297 | return RANGE_CHECK_LOWER; |
| 298 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 299 | |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 300 | if (IsNonNegativeAndNotLoopVarying(LHS)) { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 301 | Index = RHS; |
| 302 | Length = LHS; |
| 303 | return RANGE_CHECK_UPPER; |
| 304 | } |
| 305 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 306 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 307 | case ICmpInst::ICMP_ULT: |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 308 | std::swap(LHS, RHS); |
| 309 | // fallthrough |
| 310 | case ICmpInst::ICMP_UGT: |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 311 | if (IsNonNegativeAndNotLoopVarying(LHS)) { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 312 | Index = RHS; |
| 313 | Length = LHS; |
| 314 | return RANGE_CHECK_BOTH; |
| 315 | } |
| 316 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 317 | } |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 318 | |
| 319 | llvm_unreachable("default clause returns!"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 320 | } |
| 321 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 322 | void InductiveRangeCheck::extractRangeChecksFromCond( |
| 323 | Loop *L, ScalarEvolution &SE, Use &ConditionUse, |
| 324 | SmallVectorImpl<InductiveRangeCheck> &Checks, |
| 325 | SmallPtrSetImpl<Value *> &Visited) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 326 | using namespace llvm::PatternMatch; |
| 327 | |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 328 | Value *Condition = ConditionUse.get(); |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 329 | if (!Visited.insert(Condition).second) |
| 330 | return; |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 331 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 332 | if (match(Condition, m_And(m_Value(), m_Value()))) { |
| 333 | SmallVector<InductiveRangeCheck, 8> SubChecks; |
| 334 | extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0), |
| 335 | SubChecks, Visited); |
| 336 | extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1), |
| 337 | SubChecks, Visited); |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 338 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 339 | if (SubChecks.size() == 2) { |
| 340 | // Handle a special case where we know how to merge two checks separately |
| 341 | // checking the upper and lower bounds into a full range check. |
| 342 | const auto &RChkA = SubChecks[0]; |
| 343 | const auto &RChkB = SubChecks[1]; |
| 344 | if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) && |
| 345 | RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 346 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 347 | // If RChkA.Kind == RChkB.Kind then we just found two identical checks. |
| 348 | // But if one of them is a RANGE_CHECK_LOWER and the other is a |
| 349 | // RANGE_CHECK_UPPER (only possibility if they're different) then |
| 350 | // together they form a RANGE_CHECK_BOTH. |
| 351 | SubChecks[0].Kind = |
| 352 | (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind); |
| 353 | SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length; |
| 354 | SubChecks[0].CheckUse = &ConditionUse; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 355 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 356 | // We updated one of the checks in place, now erase the other. |
| 357 | SubChecks.pop_back(); |
| 358 | } |
| 359 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 360 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 361 | Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end()); |
| 362 | return; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 363 | } |
| 364 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 365 | ICmpInst *ICI = dyn_cast<ICmpInst>(Condition); |
| 366 | if (!ICI) |
| 367 | return; |
| 368 | |
| 369 | Value *Length = nullptr, *Index; |
| 370 | auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length); |
| 371 | if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN) |
| 372 | return; |
| 373 | |
Sanjoy Das | 5fd7ac4 | 2016-05-24 17:19:56 +0000 | [diff] [blame] | 374 | const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 375 | bool IsAffineIndex = |
| 376 | IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine(); |
| 377 | |
| 378 | if (!IsAffineIndex) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 379 | return; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 380 | |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 381 | InductiveRangeCheck IRC; |
| 382 | IRC.Length = Length; |
| 383 | IRC.Offset = IndexAddRec->getStart(); |
| 384 | IRC.Scale = IndexAddRec->getStepRecurrence(SE); |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 385 | IRC.CheckUse = &ConditionUse; |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 386 | IRC.Kind = RCKind; |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 387 | Checks.push_back(IRC); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 388 | } |
| 389 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 390 | void InductiveRangeCheck::extractRangeChecksFromBranch( |
| 391 | BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI, |
| 392 | SmallVectorImpl<InductiveRangeCheck> &Checks) { |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 393 | |
| 394 | if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch()) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 395 | return; |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 396 | |
| 397 | BranchProbability LikelyTaken(15, 16); |
| 398 | |
| 399 | if (BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 400 | return; |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 401 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 402 | SmallPtrSet<Value *, 8> Visited; |
| 403 | InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0), |
| 404 | Checks, Visited); |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 405 | } |
| 406 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 407 | namespace { |
| 408 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 409 | // Keeps track of the structure of a loop. This is similar to llvm::Loop, |
| 410 | // except that it is more lightweight and can track the state of a loop through |
| 411 | // changing and potentially invalid IR. This structure also formalizes the |
| 412 | // kinds of loops we can deal with -- ones that have a single latch that is also |
| 413 | // an exiting block *and* have a canonical induction variable. |
| 414 | struct LoopStructure { |
| 415 | const char *Tag; |
| 416 | |
| 417 | BasicBlock *Header; |
| 418 | BasicBlock *Latch; |
| 419 | |
| 420 | // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th |
| 421 | // successor is `LatchExit', the exit block of the loop. |
| 422 | BranchInst *LatchBr; |
| 423 | BasicBlock *LatchExit; |
| 424 | unsigned LatchBrExitIdx; |
| 425 | |
| 426 | Value *IndVarNext; |
| 427 | Value *IndVarStart; |
| 428 | Value *LoopExitAt; |
| 429 | bool IndVarIncreasing; |
| 430 | |
| 431 | LoopStructure() |
| 432 | : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr), |
| 433 | LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr), |
| 434 | IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {} |
| 435 | |
| 436 | template <typename M> LoopStructure map(M Map) const { |
| 437 | LoopStructure Result; |
| 438 | Result.Tag = Tag; |
| 439 | Result.Header = cast<BasicBlock>(Map(Header)); |
| 440 | Result.Latch = cast<BasicBlock>(Map(Latch)); |
| 441 | Result.LatchBr = cast<BranchInst>(Map(LatchBr)); |
| 442 | Result.LatchExit = cast<BasicBlock>(Map(LatchExit)); |
| 443 | Result.LatchBrExitIdx = LatchBrExitIdx; |
| 444 | Result.IndVarNext = Map(IndVarNext); |
| 445 | Result.IndVarStart = Map(IndVarStart); |
| 446 | Result.LoopExitAt = Map(LoopExitAt); |
| 447 | Result.IndVarIncreasing = IndVarIncreasing; |
| 448 | return Result; |
| 449 | } |
| 450 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 451 | static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &, |
| 452 | BranchProbabilityInfo &BPI, |
| 453 | Loop &, |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 454 | const char *&); |
| 455 | }; |
| 456 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 457 | /// This class is used to constrain loops to run within a given iteration space. |
| 458 | /// The algorithm this class implements is given a Loop and a range [Begin, |
| 459 | /// End). The algorithm then tries to break out a "main loop" out of the loop |
| 460 | /// it is given in a way that the "main loop" runs with the induction variable |
| 461 | /// in a subset of [Begin, End). The algorithm emits appropriate pre and post |
| 462 | /// loops to run any remaining iterations. The pre loop runs any iterations in |
| 463 | /// which the induction variable is < Begin, and the post loop runs any |
| 464 | /// iterations in which the induction variable is >= End. |
| 465 | /// |
| 466 | class LoopConstrainer { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 467 | // The representation of a clone of the original loop we started out with. |
| 468 | struct ClonedLoop { |
| 469 | // The cloned blocks |
| 470 | std::vector<BasicBlock *> Blocks; |
| 471 | |
| 472 | // `Map` maps values in the clonee into values in the cloned version |
| 473 | ValueToValueMapTy Map; |
| 474 | |
| 475 | // An instance of `LoopStructure` for the cloned loop |
| 476 | LoopStructure Structure; |
| 477 | }; |
| 478 | |
| 479 | // Result of rewriting the range of a loop. See changeIterationSpaceEnd for |
| 480 | // more details on what these fields mean. |
| 481 | struct RewrittenRangeInfo { |
| 482 | BasicBlock *PseudoExit; |
| 483 | BasicBlock *ExitSelector; |
| 484 | std::vector<PHINode *> PHIValuesAtPseudoExit; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 485 | PHINode *IndVarEnd; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 486 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 487 | RewrittenRangeInfo() |
| 488 | : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {} |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 489 | }; |
| 490 | |
| 491 | // Calculated subranges we restrict the iteration space of the main loop to. |
| 492 | // See the implementation of `calculateSubRanges' for more details on how |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 493 | // these fields are computed. `LowLimit` is None if there is no restriction |
| 494 | // on low end of the restricted iteration space of the main loop. `HighLimit` |
| 495 | // is None if there is no restriction on high end of the restricted iteration |
| 496 | // space of the main loop. |
| 497 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 498 | struct SubRanges { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 499 | Optional<const SCEV *> LowLimit; |
| 500 | Optional<const SCEV *> HighLimit; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 501 | }; |
| 502 | |
| 503 | // A utility function that does a `replaceUsesOfWith' on the incoming block |
| 504 | // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's |
| 505 | // incoming block list with `ReplaceBy'. |
| 506 | static void replacePHIBlock(PHINode *PN, BasicBlock *Block, |
| 507 | BasicBlock *ReplaceBy); |
| 508 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 509 | // Compute a safe set of limits for the main loop to run in -- effectively the |
| 510 | // intersection of `Range' and the iteration space of the original loop. |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 511 | // Return None if unable to compute the set of subranges. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 512 | // |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 513 | Optional<SubRanges> calculateSubRanges() const; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 514 | |
| 515 | // Clone `OriginalLoop' and return the result in CLResult. The IR after |
| 516 | // running `cloneLoop' is well formed except for the PHI nodes in CLResult -- |
| 517 | // the PHI nodes say that there is an incoming edge from `OriginalPreheader` |
| 518 | // but there is no such edge. |
| 519 | // |
| 520 | void cloneLoop(ClonedLoop &CLResult, const char *Tag) const; |
| 521 | |
| 522 | // Rewrite the iteration space of the loop denoted by (LS, Preheader). The |
| 523 | // iteration space of the rewritten loop ends at ExitLoopAt. The start of the |
| 524 | // iteration space is not changed. `ExitLoopAt' is assumed to be slt |
| 525 | // `OriginalHeaderCount'. |
| 526 | // |
| 527 | // If there are iterations left to execute, control is made to jump to |
| 528 | // `ContinuationBlock', otherwise they take the normal loop exit. The |
| 529 | // returned `RewrittenRangeInfo' object is populated as follows: |
| 530 | // |
| 531 | // .PseudoExit is a basic block that unconditionally branches to |
| 532 | // `ContinuationBlock'. |
| 533 | // |
| 534 | // .ExitSelector is a basic block that decides, on exit from the loop, |
| 535 | // whether to branch to the "true" exit or to `PseudoExit'. |
| 536 | // |
| 537 | // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value |
| 538 | // for each PHINode in the loop header on taking the pseudo exit. |
| 539 | // |
| 540 | // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate |
| 541 | // preheader because it is made to branch to the loop header only |
| 542 | // conditionally. |
| 543 | // |
| 544 | RewrittenRangeInfo |
| 545 | changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader, |
| 546 | Value *ExitLoopAt, |
| 547 | BasicBlock *ContinuationBlock) const; |
| 548 | |
| 549 | // The loop denoted by `LS' has `OldPreheader' as its preheader. This |
| 550 | // function creates a new preheader for `LS' and returns it. |
| 551 | // |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 552 | BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader, |
| 553 | const char *Tag) const; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 554 | |
| 555 | // `ContinuationBlockAndPreheader' was the continuation block for some call to |
| 556 | // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'. |
| 557 | // This function rewrites the PHI nodes in `LS.Header' to start with the |
| 558 | // correct value. |
| 559 | void rewriteIncomingValuesForPHIs( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 560 | LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 561 | const LoopConstrainer::RewrittenRangeInfo &RRI) const; |
| 562 | |
| 563 | // Even though we do not preserve any passes at this time, we at least need to |
| 564 | // keep the parent loop structure consistent. The `LPPassManager' seems to |
| 565 | // verify this after running a loop pass. This function adds the list of |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 566 | // blocks denoted by BBs to this loops parent loop if required. |
| 567 | void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 568 | |
| 569 | // Some global state. |
| 570 | Function &F; |
| 571 | LLVMContext &Ctx; |
| 572 | ScalarEvolution &SE; |
| 573 | |
| 574 | // Information about the original loop we started out with. |
| 575 | Loop &OriginalLoop; |
| 576 | LoopInfo &OriginalLoopInfo; |
| 577 | const SCEV *LatchTakenCount; |
| 578 | BasicBlock *OriginalPreheader; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 579 | |
| 580 | // The preheader of the main loop. This may or may not be different from |
| 581 | // `OriginalPreheader'. |
| 582 | BasicBlock *MainLoopPreheader; |
| 583 | |
| 584 | // The range we need to run the main loop in. |
| 585 | InductiveRangeCheck::Range Range; |
| 586 | |
| 587 | // The structure of the main loop (see comment at the beginning of this class |
| 588 | // for a definition) |
| 589 | LoopStructure MainLoopStructure; |
| 590 | |
| 591 | public: |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 592 | LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS, |
| 593 | ScalarEvolution &SE, InductiveRangeCheck::Range R) |
| 594 | : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), |
| 595 | SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr), |
| 596 | OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R), |
| 597 | MainLoopStructure(LS) {} |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 598 | |
| 599 | // Entry point for the algorithm. Returns true on success. |
| 600 | bool run(); |
| 601 | }; |
| 602 | |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 603 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 604 | |
| 605 | void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block, |
| 606 | BasicBlock *ReplaceBy) { |
| 607 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 608 | if (PN->getIncomingBlock(i) == Block) |
| 609 | PN->setIncomingBlock(i, ReplaceBy); |
| 610 | } |
| 611 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 612 | static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) { |
| 613 | APInt SMax = |
| 614 | APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()); |
| 615 | return SE.getSignedRange(S).contains(SMax) && |
| 616 | SE.getUnsignedRange(S).contains(SMax); |
| 617 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 618 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 619 | static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) { |
| 620 | APInt SMin = |
| 621 | APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()); |
| 622 | return SE.getSignedRange(S).contains(SMin) && |
| 623 | SE.getUnsignedRange(S).contains(SMin); |
| 624 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 625 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 626 | Optional<LoopStructure> |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 627 | LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI, |
| 628 | Loop &L, const char *&FailureReason) { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 629 | assert(L.isLoopSimplifyForm() && "should follow from addRequired<>"); |
| 630 | |
| 631 | BasicBlock *Latch = L.getLoopLatch(); |
| 632 | if (!L.isLoopExiting(Latch)) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 633 | FailureReason = "no loop latch"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 634 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 635 | } |
| 636 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 637 | BasicBlock *Header = L.getHeader(); |
| 638 | BasicBlock *Preheader = L.getLoopPreheader(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 639 | if (!Preheader) { |
| 640 | FailureReason = "no preheader"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 641 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 642 | } |
| 643 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 644 | BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 645 | if (!LatchBr || LatchBr->isUnconditional()) { |
| 646 | FailureReason = "latch terminator not conditional branch"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 647 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 648 | } |
| 649 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 650 | unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 651 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 652 | BranchProbability ExitProbability = |
| 653 | BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx); |
| 654 | |
| 655 | if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) { |
| 656 | FailureReason = "short running loop, not profitable"; |
| 657 | return None; |
| 658 | } |
| 659 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 660 | ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition()); |
| 661 | if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) { |
| 662 | FailureReason = "latch terminator branch not conditional on integral icmp"; |
| 663 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 664 | } |
| 665 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 666 | const SCEV *LatchCount = SE.getExitCount(&L, Latch); |
| 667 | if (isa<SCEVCouldNotCompute>(LatchCount)) { |
| 668 | FailureReason = "could not compute latch count"; |
| 669 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 670 | } |
| 671 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 672 | ICmpInst::Predicate Pred = ICI->getPredicate(); |
| 673 | Value *LeftValue = ICI->getOperand(0); |
| 674 | const SCEV *LeftSCEV = SE.getSCEV(LeftValue); |
| 675 | IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType()); |
| 676 | |
| 677 | Value *RightValue = ICI->getOperand(1); |
| 678 | const SCEV *RightSCEV = SE.getSCEV(RightValue); |
| 679 | |
| 680 | // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence. |
| 681 | if (!isa<SCEVAddRecExpr>(LeftSCEV)) { |
| 682 | if (isa<SCEVAddRecExpr>(RightSCEV)) { |
| 683 | std::swap(LeftSCEV, RightSCEV); |
| 684 | std::swap(LeftValue, RightValue); |
| 685 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 686 | } else { |
| 687 | FailureReason = "no add recurrences in the icmp"; |
| 688 | return None; |
| 689 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 690 | } |
| 691 | |
Sanjoy Das | 45dc94a | 2015-03-24 19:29:22 +0000 | [diff] [blame] | 692 | auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) { |
| 693 | if (AR->getNoWrapFlags(SCEV::FlagNSW)) |
| 694 | return true; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 695 | |
| 696 | IntegerType *Ty = cast<IntegerType>(AR->getType()); |
| 697 | IntegerType *WideTy = |
| 698 | IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2); |
| 699 | |
Sanjoy Das | 45dc94a | 2015-03-24 19:29:22 +0000 | [diff] [blame] | 700 | const SCEVAddRecExpr *ExtendAfterOp = |
| 701 | dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy)); |
| 702 | if (ExtendAfterOp) { |
| 703 | const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy); |
| 704 | const SCEV *ExtendedStep = |
| 705 | SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy); |
| 706 | |
| 707 | bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart && |
| 708 | ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep; |
| 709 | |
| 710 | if (NoSignedWrap) |
| 711 | return true; |
| 712 | } |
| 713 | |
| 714 | // We may have proved this when computing the sign extension above. |
| 715 | return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap; |
| 716 | }; |
| 717 | |
| 718 | auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) { |
| 719 | if (!AR->isAffine()) |
| 720 | return false; |
| 721 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 722 | // Currently we only work with induction variables that have been proved to |
| 723 | // not wrap. This restriction can potentially be lifted in the future. |
| 724 | |
Sanjoy Das | 45dc94a | 2015-03-24 19:29:22 +0000 | [diff] [blame] | 725 | if (!HasNoSignedWrap(AR)) |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 726 | return false; |
| 727 | |
| 728 | if (const SCEVConstant *StepExpr = |
| 729 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) { |
| 730 | ConstantInt *StepCI = StepExpr->getValue(); |
| 731 | if (StepCI->isOne() || StepCI->isMinusOne()) { |
| 732 | IsIncreasing = StepCI->isOne(); |
| 733 | return true; |
| 734 | } |
| 735 | } |
| 736 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 737 | return false; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 738 | }; |
| 739 | |
| 740 | // `ICI` is interpreted as taking the backedge if the *next* value of the |
| 741 | // induction variable satisfies some constraint. |
| 742 | |
| 743 | const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV); |
| 744 | bool IsIncreasing = false; |
| 745 | if (!IsInductionVar(IndVarNext, IsIncreasing)) { |
| 746 | FailureReason = "LHS in icmp not induction variable"; |
| 747 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 748 | } |
| 749 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 750 | ConstantInt *One = ConstantInt::get(IndVarTy, 1); |
| 751 | // TODO: generalize the predicates here to also match their unsigned variants. |
| 752 | if (IsIncreasing) { |
| 753 | bool FoundExpectedPred = |
| 754 | (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) || |
| 755 | (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0); |
| 756 | |
| 757 | if (!FoundExpectedPred) { |
| 758 | FailureReason = "expected icmp slt semantically, found something else"; |
| 759 | return None; |
| 760 | } |
| 761 | |
| 762 | if (LatchBrExitIdx == 0) { |
| 763 | if (CanBeSMax(SE, RightSCEV)) { |
| 764 | // TODO: this restriction is easily removable -- we just have to |
| 765 | // remember that the icmp was an slt and not an sle. |
| 766 | FailureReason = "limit may overflow when coercing sle to slt"; |
| 767 | return None; |
| 768 | } |
| 769 | |
| 770 | IRBuilder<> B(&*Preheader->rbegin()); |
| 771 | RightValue = B.CreateAdd(RightValue, One); |
| 772 | } |
| 773 | |
| 774 | } else { |
| 775 | bool FoundExpectedPred = |
| 776 | (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) || |
| 777 | (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0); |
| 778 | |
| 779 | if (!FoundExpectedPred) { |
| 780 | FailureReason = "expected icmp sgt semantically, found something else"; |
| 781 | return None; |
| 782 | } |
| 783 | |
| 784 | if (LatchBrExitIdx == 0) { |
| 785 | if (CanBeSMin(SE, RightSCEV)) { |
| 786 | // TODO: this restriction is easily removable -- we just have to |
| 787 | // remember that the icmp was an sgt and not an sge. |
| 788 | FailureReason = "limit may overflow when coercing sge to sgt"; |
| 789 | return None; |
| 790 | } |
| 791 | |
| 792 | IRBuilder<> B(&*Preheader->rbegin()); |
| 793 | RightValue = B.CreateSub(RightValue, One); |
| 794 | } |
| 795 | } |
| 796 | |
| 797 | const SCEV *StartNext = IndVarNext->getStart(); |
| 798 | const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE)); |
| 799 | const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend); |
| 800 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 801 | BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx); |
| 802 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 803 | assert(SE.getLoopDisposition(LatchCount, &L) == |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 804 | ScalarEvolution::LoopInvariant && |
| 805 | "loop variant exit count doesn't make sense!"); |
| 806 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 807 | assert(!L.contains(LatchExit) && "expected an exit block!"); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 808 | const DataLayout &DL = Preheader->getModule()->getDataLayout(); |
| 809 | Value *IndVarStartV = |
| 810 | SCEVExpander(SE, DL, "irce") |
| 811 | .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 812 | IndVarStartV->setName("indvar.start"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 813 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 814 | LoopStructure Result; |
| 815 | |
| 816 | Result.Tag = "main"; |
| 817 | Result.Header = Header; |
| 818 | Result.Latch = Latch; |
| 819 | Result.LatchBr = LatchBr; |
| 820 | Result.LatchExit = LatchExit; |
| 821 | Result.LatchBrExitIdx = LatchBrExitIdx; |
| 822 | Result.IndVarStart = IndVarStartV; |
| 823 | Result.IndVarNext = LeftValue; |
| 824 | Result.IndVarIncreasing = IsIncreasing; |
| 825 | Result.LoopExitAt = RightValue; |
| 826 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 827 | FailureReason = nullptr; |
| 828 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 829 | return Result; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 830 | } |
| 831 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 832 | Optional<LoopConstrainer::SubRanges> |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 833 | LoopConstrainer::calculateSubRanges() const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 834 | IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType()); |
| 835 | |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 836 | if (Range.getType() != Ty) |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 837 | return None; |
| 838 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 839 | LoopConstrainer::SubRanges Result; |
| 840 | |
| 841 | // I think we can be more aggressive here and make this nuw / nsw if the |
| 842 | // addition that feeds into the icmp for the latch's terminating branch is nuw |
| 843 | // / nsw. In any case, a wrapping 2's complement addition is safe. |
| 844 | ConstantInt *One = ConstantInt::get(Ty, 1); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 845 | const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart); |
| 846 | const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 847 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 848 | bool Increasing = MainLoopStructure.IndVarIncreasing; |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 849 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 850 | // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the |
| 851 | // range of values the induction variable takes. |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 852 | |
| 853 | const SCEV *Smallest = nullptr, *Greatest = nullptr; |
| 854 | |
| 855 | if (Increasing) { |
| 856 | Smallest = Start; |
| 857 | Greatest = End; |
| 858 | } else { |
| 859 | // These two computations may sign-overflow. Here is why that is okay: |
| 860 | // |
| 861 | // We know that the induction variable does not sign-overflow on any |
| 862 | // iteration except the last one, and it starts at `Start` and ends at |
| 863 | // `End`, decrementing by one every time. |
| 864 | // |
| 865 | // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the |
| 866 | // induction variable is decreasing we know that that the smallest value |
| 867 | // the loop body is actually executed with is `INT_SMIN` == `Smallest`. |
| 868 | // |
| 869 | // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In |
| 870 | // that case, `Clamp` will always return `Smallest` and |
| 871 | // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`) |
| 872 | // will be an empty range. Returning an empty range is always safe. |
| 873 | // |
| 874 | |
| 875 | Smallest = SE.getAddExpr(End, SE.getSCEV(One)); |
| 876 | Greatest = SE.getAddExpr(Start, SE.getSCEV(One)); |
| 877 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 878 | |
| 879 | auto Clamp = [this, Smallest, Greatest](const SCEV *S) { |
| 880 | return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S)); |
| 881 | }; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 882 | |
| 883 | // In some cases we can prove that we don't need a pre or post loop |
| 884 | |
| 885 | bool ProvablyNoPreloop = |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 886 | SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest); |
| 887 | if (!ProvablyNoPreloop) |
| 888 | Result.LowLimit = Clamp(Range.getBegin()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 889 | |
| 890 | bool ProvablyNoPostLoop = |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 891 | SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd()); |
| 892 | if (!ProvablyNoPostLoop) |
| 893 | Result.HighLimit = Clamp(Range.getEnd()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 894 | |
| 895 | return Result; |
| 896 | } |
| 897 | |
| 898 | void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result, |
| 899 | const char *Tag) const { |
| 900 | for (BasicBlock *BB : OriginalLoop.getBlocks()) { |
| 901 | BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F); |
| 902 | Result.Blocks.push_back(Clone); |
| 903 | Result.Map[BB] = Clone; |
| 904 | } |
| 905 | |
| 906 | auto GetClonedValue = [&Result](Value *V) { |
| 907 | assert(V && "null values not in domain!"); |
| 908 | auto It = Result.Map.find(V); |
| 909 | if (It == Result.Map.end()) |
| 910 | return V; |
| 911 | return static_cast<Value *>(It->second); |
| 912 | }; |
| 913 | |
| 914 | Result.Structure = MainLoopStructure.map(GetClonedValue); |
| 915 | Result.Structure.Tag = Tag; |
| 916 | |
| 917 | for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) { |
| 918 | BasicBlock *ClonedBB = Result.Blocks[i]; |
| 919 | BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i]; |
| 920 | |
| 921 | assert(Result.Map[OriginalBB] == ClonedBB && "invariant!"); |
| 922 | |
| 923 | for (Instruction &I : *ClonedBB) |
| 924 | RemapInstruction(&I, Result.Map, |
Duncan P. N. Exon Smith | da68cbc | 2016-04-07 00:26:43 +0000 | [diff] [blame] | 925 | RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 926 | |
| 927 | // Exit blocks will now have one more predecessor and their PHI nodes need |
| 928 | // to be edited to reflect that. No phi nodes need to be introduced because |
| 929 | // the loop is in LCSSA. |
| 930 | |
| 931 | for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB); |
| 932 | SBBI != SBBE; ++SBBI) { |
| 933 | |
| 934 | if (OriginalLoop.contains(*SBBI)) |
| 935 | continue; // not an exit block |
| 936 | |
| 937 | for (Instruction &I : **SBBI) { |
| 938 | if (!isa<PHINode>(&I)) |
| 939 | break; |
| 940 | |
| 941 | PHINode *PN = cast<PHINode>(&I); |
| 942 | Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB); |
| 943 | PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB); |
| 944 | } |
| 945 | } |
| 946 | } |
| 947 | } |
| 948 | |
| 949 | LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 950 | const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 951 | BasicBlock *ContinuationBlock) const { |
| 952 | |
| 953 | // We start with a loop with a single latch: |
| 954 | // |
| 955 | // +--------------------+ |
| 956 | // | | |
| 957 | // | preheader | |
| 958 | // | | |
| 959 | // +--------+-----------+ |
| 960 | // | ----------------\ |
| 961 | // | / | |
| 962 | // +--------v----v------+ | |
| 963 | // | | | |
| 964 | // | header | | |
| 965 | // | | | |
| 966 | // +--------------------+ | |
| 967 | // | |
| 968 | // ..... | |
| 969 | // | |
| 970 | // +--------------------+ | |
| 971 | // | | | |
| 972 | // | latch >----------/ |
| 973 | // | | |
| 974 | // +-------v------------+ |
| 975 | // | |
| 976 | // | |
| 977 | // | +--------------------+ |
| 978 | // | | | |
| 979 | // +---> original exit | |
| 980 | // | | |
| 981 | // +--------------------+ |
| 982 | // |
| 983 | // We change the control flow to look like |
| 984 | // |
| 985 | // |
| 986 | // +--------------------+ |
| 987 | // | | |
| 988 | // | preheader >-------------------------+ |
| 989 | // | | | |
| 990 | // +--------v-----------+ | |
| 991 | // | /-------------+ | |
| 992 | // | / | | |
| 993 | // +--------v--v--------+ | | |
| 994 | // | | | | |
| 995 | // | header | | +--------+ | |
| 996 | // | | | | | | |
| 997 | // +--------------------+ | | +-----v-----v-----------+ |
| 998 | // | | | | |
| 999 | // | | | .pseudo.exit | |
| 1000 | // | | | | |
| 1001 | // | | +-----------v-----------+ |
| 1002 | // | | | |
| 1003 | // ..... | | | |
| 1004 | // | | +--------v-------------+ |
| 1005 | // +--------------------+ | | | | |
| 1006 | // | | | | | ContinuationBlock | |
| 1007 | // | latch >------+ | | | |
| 1008 | // | | | +----------------------+ |
| 1009 | // +---------v----------+ | |
| 1010 | // | | |
| 1011 | // | | |
| 1012 | // | +---------------^-----+ |
| 1013 | // | | | |
| 1014 | // +-----> .exit.selector | |
| 1015 | // | | |
| 1016 | // +----------v----------+ |
| 1017 | // | |
| 1018 | // +--------------------+ | |
| 1019 | // | | | |
| 1020 | // | original exit <----+ |
| 1021 | // | | |
| 1022 | // +--------------------+ |
| 1023 | // |
| 1024 | |
| 1025 | RewrittenRangeInfo RRI; |
| 1026 | |
| 1027 | auto BBInsertLocation = std::next(Function::iterator(LS.Latch)); |
| 1028 | RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector", |
Duncan P. N. Exon Smith | 3a9c9e3 | 2015-10-13 18:26:00 +0000 | [diff] [blame] | 1029 | &F, &*BBInsertLocation); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1030 | RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F, |
Duncan P. N. Exon Smith | 3a9c9e3 | 2015-10-13 18:26:00 +0000 | [diff] [blame] | 1031 | &*BBInsertLocation); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1032 | |
| 1033 | BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1034 | bool Increasing = LS.IndVarIncreasing; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1035 | |
| 1036 | IRBuilder<> B(PreheaderJump); |
| 1037 | |
| 1038 | // EnterLoopCond - is it okay to start executing this `LS'? |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1039 | Value *EnterLoopCond = Increasing |
| 1040 | ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt) |
| 1041 | : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt); |
| 1042 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1043 | B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit); |
| 1044 | PreheaderJump->eraseFromParent(); |
| 1045 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1046 | LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1047 | B.SetInsertPoint(LS.LatchBr); |
| 1048 | Value *TakeBackedgeLoopCond = |
| 1049 | Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt) |
| 1050 | : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt); |
| 1051 | Value *CondForBranch = LS.LatchBrExitIdx == 1 |
| 1052 | ? TakeBackedgeLoopCond |
| 1053 | : B.CreateNot(TakeBackedgeLoopCond); |
| 1054 | |
| 1055 | LS.LatchBr->setCondition(CondForBranch); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1056 | |
| 1057 | B.SetInsertPoint(RRI.ExitSelector); |
| 1058 | |
| 1059 | // IterationsLeft - are there any more iterations left, given the original |
| 1060 | // upper bound on the induction variable? If not, we branch to the "real" |
| 1061 | // exit. |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1062 | Value *IterationsLeft = Increasing |
| 1063 | ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt) |
| 1064 | : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1065 | B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit); |
| 1066 | |
| 1067 | BranchInst *BranchToContinuation = |
| 1068 | BranchInst::Create(ContinuationBlock, RRI.PseudoExit); |
| 1069 | |
| 1070 | // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of |
| 1071 | // each of the PHI nodes in the loop header. This feeds into the initial |
| 1072 | // value of the same PHI nodes if/when we continue execution. |
| 1073 | for (Instruction &I : *LS.Header) { |
| 1074 | if (!isa<PHINode>(&I)) |
| 1075 | break; |
| 1076 | |
| 1077 | PHINode *PN = cast<PHINode>(&I); |
| 1078 | |
| 1079 | PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy", |
| 1080 | BranchToContinuation); |
| 1081 | |
| 1082 | NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader); |
| 1083 | NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch), |
| 1084 | RRI.ExitSelector); |
| 1085 | RRI.PHIValuesAtPseudoExit.push_back(NewPHI); |
| 1086 | } |
| 1087 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1088 | RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end", |
| 1089 | BranchToContinuation); |
| 1090 | RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader); |
| 1091 | RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector); |
| 1092 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1093 | // The latch exit now has a branch from `RRI.ExitSelector' instead of |
| 1094 | // `LS.Latch'. The PHI nodes need to be updated to reflect that. |
| 1095 | for (Instruction &I : *LS.LatchExit) { |
| 1096 | if (PHINode *PN = dyn_cast<PHINode>(&I)) |
| 1097 | replacePHIBlock(PN, LS.Latch, RRI.ExitSelector); |
| 1098 | else |
| 1099 | break; |
| 1100 | } |
| 1101 | |
| 1102 | return RRI; |
| 1103 | } |
| 1104 | |
| 1105 | void LoopConstrainer::rewriteIncomingValuesForPHIs( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1106 | LoopStructure &LS, BasicBlock *ContinuationBlock, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1107 | const LoopConstrainer::RewrittenRangeInfo &RRI) const { |
| 1108 | |
| 1109 | unsigned PHIIndex = 0; |
| 1110 | for (Instruction &I : *LS.Header) { |
| 1111 | if (!isa<PHINode>(&I)) |
| 1112 | break; |
| 1113 | |
| 1114 | PHINode *PN = cast<PHINode>(&I); |
| 1115 | |
| 1116 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) |
| 1117 | if (PN->getIncomingBlock(i) == ContinuationBlock) |
| 1118 | PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]); |
| 1119 | } |
| 1120 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1121 | LS.IndVarStart = RRI.IndVarEnd; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1122 | } |
| 1123 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1124 | BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS, |
| 1125 | BasicBlock *OldPreheader, |
| 1126 | const char *Tag) const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1127 | |
| 1128 | BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header); |
| 1129 | BranchInst::Create(LS.Header, Preheader); |
| 1130 | |
| 1131 | for (Instruction &I : *LS.Header) { |
| 1132 | if (!isa<PHINode>(&I)) |
| 1133 | break; |
| 1134 | |
| 1135 | PHINode *PN = cast<PHINode>(&I); |
| 1136 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) |
| 1137 | replacePHIBlock(PN, OldPreheader, Preheader); |
| 1138 | } |
| 1139 | |
| 1140 | return Preheader; |
| 1141 | } |
| 1142 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1143 | void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1144 | Loop *ParentLoop = OriginalLoop.getParentLoop(); |
| 1145 | if (!ParentLoop) |
| 1146 | return; |
| 1147 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1148 | for (BasicBlock *BB : BBs) |
| 1149 | ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1150 | } |
| 1151 | |
| 1152 | bool LoopConstrainer::run() { |
| 1153 | BasicBlock *Preheader = nullptr; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1154 | LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch); |
| 1155 | Preheader = OriginalLoop.getLoopPreheader(); |
| 1156 | assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr && |
| 1157 | "preconditions!"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1158 | |
| 1159 | OriginalPreheader = Preheader; |
| 1160 | MainLoopPreheader = Preheader; |
| 1161 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1162 | Optional<SubRanges> MaybeSR = calculateSubRanges(); |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1163 | if (!MaybeSR.hasValue()) { |
| 1164 | DEBUG(dbgs() << "irce: could not compute subranges\n"); |
| 1165 | return false; |
| 1166 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1167 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1168 | SubRanges SR = MaybeSR.getValue(); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1169 | bool Increasing = MainLoopStructure.IndVarIncreasing; |
| 1170 | IntegerType *IVTy = |
| 1171 | cast<IntegerType>(MainLoopStructure.IndVarNext->getType()); |
| 1172 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1173 | SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1174 | Instruction *InsertPt = OriginalPreheader->getTerminator(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1175 | |
| 1176 | // It would have been better to make `PreLoop' and `PostLoop' |
| 1177 | // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy |
| 1178 | // constructor. |
| 1179 | ClonedLoop PreLoop, PostLoop; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1180 | bool NeedsPreLoop = |
| 1181 | Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue(); |
| 1182 | bool NeedsPostLoop = |
| 1183 | Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue(); |
| 1184 | |
| 1185 | Value *ExitPreLoopAt = nullptr; |
| 1186 | Value *ExitMainLoopAt = nullptr; |
| 1187 | const SCEVConstant *MinusOneS = |
| 1188 | cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */)); |
| 1189 | |
| 1190 | if (NeedsPreLoop) { |
| 1191 | const SCEV *ExitPreLoopAtSCEV = nullptr; |
| 1192 | |
| 1193 | if (Increasing) |
| 1194 | ExitPreLoopAtSCEV = *SR.LowLimit; |
| 1195 | else { |
| 1196 | if (CanBeSMin(SE, *SR.HighLimit)) { |
| 1197 | DEBUG(dbgs() << "irce: could not prove no-overflow when computing " |
| 1198 | << "preloop exit limit. HighLimit = " << *(*SR.HighLimit) |
| 1199 | << "\n"); |
| 1200 | return false; |
| 1201 | } |
| 1202 | ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS); |
| 1203 | } |
| 1204 | |
| 1205 | ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt); |
| 1206 | ExitPreLoopAt->setName("exit.preloop.at"); |
| 1207 | } |
| 1208 | |
| 1209 | if (NeedsPostLoop) { |
| 1210 | const SCEV *ExitMainLoopAtSCEV = nullptr; |
| 1211 | |
| 1212 | if (Increasing) |
| 1213 | ExitMainLoopAtSCEV = *SR.HighLimit; |
| 1214 | else { |
| 1215 | if (CanBeSMin(SE, *SR.LowLimit)) { |
| 1216 | DEBUG(dbgs() << "irce: could not prove no-overflow when computing " |
| 1217 | << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit) |
| 1218 | << "\n"); |
| 1219 | return false; |
| 1220 | } |
| 1221 | ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS); |
| 1222 | } |
| 1223 | |
| 1224 | ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt); |
| 1225 | ExitMainLoopAt->setName("exit.mainloop.at"); |
| 1226 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1227 | |
| 1228 | // We clone these ahead of time so that we don't have to deal with changing |
| 1229 | // and temporarily invalid IR as we transform the loops. |
| 1230 | if (NeedsPreLoop) |
| 1231 | cloneLoop(PreLoop, "preloop"); |
| 1232 | if (NeedsPostLoop) |
| 1233 | cloneLoop(PostLoop, "postloop"); |
| 1234 | |
| 1235 | RewrittenRangeInfo PreLoopRRI; |
| 1236 | |
| 1237 | if (NeedsPreLoop) { |
| 1238 | Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header, |
| 1239 | PreLoop.Structure.Header); |
| 1240 | |
| 1241 | MainLoopPreheader = |
| 1242 | createPreheader(MainLoopStructure, Preheader, "mainloop"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1243 | PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader, |
| 1244 | ExitPreLoopAt, MainLoopPreheader); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1245 | rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader, |
| 1246 | PreLoopRRI); |
| 1247 | } |
| 1248 | |
| 1249 | BasicBlock *PostLoopPreheader = nullptr; |
| 1250 | RewrittenRangeInfo PostLoopRRI; |
| 1251 | |
| 1252 | if (NeedsPostLoop) { |
| 1253 | PostLoopPreheader = |
| 1254 | createPreheader(PostLoop.Structure, Preheader, "postloop"); |
| 1255 | PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader, |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1256 | ExitMainLoopAt, PostLoopPreheader); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1257 | rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader, |
| 1258 | PostLoopRRI); |
| 1259 | } |
| 1260 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1261 | BasicBlock *NewMainLoopPreheader = |
| 1262 | MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr; |
| 1263 | BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit, |
| 1264 | PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit, |
| 1265 | PostLoopRRI.ExitSelector, NewMainLoopPreheader}; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1266 | |
| 1267 | // Some of the above may be nullptr, filter them out before passing to |
| 1268 | // addToParentLoopIfNeeded. |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1269 | auto NewBlocksEnd = |
| 1270 | std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1271 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1272 | addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd)); |
| 1273 | addToParentLoopIfNeeded(PreLoop.Blocks); |
| 1274 | addToParentLoopIfNeeded(PostLoop.Blocks); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1275 | |
| 1276 | return true; |
| 1277 | } |
| 1278 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1279 | /// Computes and returns a range of values for the induction variable (IndVar) |
| 1280 | /// in which the range check can be safely elided. If it cannot compute such a |
| 1281 | /// range, returns None. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1282 | Optional<InductiveRangeCheck::Range> |
Sanjoy Das | 5977673 | 2016-05-21 02:31:51 +0000 | [diff] [blame] | 1283 | InductiveRangeCheck::computeSafeIterationSpace( |
| 1284 | ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const { |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1285 | // IndVar is of the form "A + B * I" (where "I" is the canonical induction |
| 1286 | // variable, that may or may not exist as a real llvm::Value in the loop) and |
| 1287 | // this inductive range check is a range check on the "C + D * I" ("C" is |
| 1288 | // getOffset() and "D" is getScale()). We rewrite the value being range |
| 1289 | // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA". |
| 1290 | // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code |
| 1291 | // can be generalized as needed. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1292 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1293 | // The actual inequalities we solve are of the form |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1294 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1295 | // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1) |
| 1296 | // |
| 1297 | // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions |
| 1298 | // and subtractions are twos-complement wrapping and comparisons are signed. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1299 | // |
| 1300 | // Proof: |
| 1301 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1302 | // If there exists IndVar such that -M <= IndVar < (L - M) then it follows |
| 1303 | // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows |
| 1304 | // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have |
| 1305 | // overflown. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1306 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1307 | // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t. |
| 1308 | // Hence 0 <= (IndVar + M) < L |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1309 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1310 | // [^1]: Note that the solution does _not_ apply if L < 0; consider values M = |
| 1311 | // 127, IndVar = 126 and L = -2 in an i8 world. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1312 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1313 | if (!IndVar->isAffine()) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1314 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1315 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1316 | const SCEV *A = IndVar->getStart(); |
| 1317 | const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE)); |
| 1318 | if (!B) |
| 1319 | return None; |
| 1320 | |
| 1321 | const SCEV *C = getOffset(); |
| 1322 | const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale()); |
| 1323 | if (D != B) |
| 1324 | return None; |
| 1325 | |
| 1326 | ConstantInt *ConstD = D->getValue(); |
| 1327 | if (!(ConstD->isMinusOne() || ConstD->isOne())) |
| 1328 | return None; |
| 1329 | |
| 1330 | const SCEV *M = SE.getMinusSCEV(C, A); |
| 1331 | |
| 1332 | const SCEV *Begin = SE.getNegativeSCEV(M); |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 1333 | const SCEV *UpperLimit = nullptr; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1334 | |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 1335 | // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L". |
| 1336 | // We can potentially do much better here. |
| 1337 | if (Value *V = getLength()) { |
| 1338 | UpperLimit = SE.getSCEV(V); |
| 1339 | } else { |
| 1340 | assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!"); |
| 1341 | unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth(); |
| 1342 | UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth)); |
| 1343 | } |
| 1344 | |
| 1345 | const SCEV *End = SE.getMinusSCEV(UpperLimit, M); |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 1346 | return InductiveRangeCheck::Range(Begin, End); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1347 | } |
| 1348 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1349 | static Optional<InductiveRangeCheck::Range> |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 1350 | IntersectRange(ScalarEvolution &SE, |
| 1351 | const Optional<InductiveRangeCheck::Range> &R1, |
Sanjoy Das | 5977673 | 2016-05-21 02:31:51 +0000 | [diff] [blame] | 1352 | const InductiveRangeCheck::Range &R2) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1353 | if (!R1.hasValue()) |
| 1354 | return R2; |
| 1355 | auto &R1Value = R1.getValue(); |
| 1356 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1357 | // TODO: we could widen the smaller range and have this work; but for now we |
| 1358 | // bail out to keep things simple. |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 1359 | if (R1Value.getType() != R2.getType()) |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1360 | return None; |
| 1361 | |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 1362 | const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin()); |
| 1363 | const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd()); |
| 1364 | |
| 1365 | return InductiveRangeCheck::Range(NewBegin, NewEnd); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1366 | } |
| 1367 | |
| 1368 | bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) { |
Andrew Kaylor | 50271f7 | 2016-05-03 22:32:30 +0000 | [diff] [blame] | 1369 | if (skipLoop(L)) |
| 1370 | return false; |
| 1371 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1372 | if (L->getBlocks().size() >= LoopSizeCutoff) { |
| 1373 | DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";); |
| 1374 | return false; |
| 1375 | } |
| 1376 | |
| 1377 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 1378 | if (!Preheader) { |
| 1379 | DEBUG(dbgs() << "irce: loop has no preheader, leaving\n"); |
| 1380 | return false; |
| 1381 | } |
| 1382 | |
| 1383 | LLVMContext &Context = Preheader->getContext(); |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1384 | SmallVector<InductiveRangeCheck, 16> RangeChecks; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1385 | ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1386 | BranchProbabilityInfo &BPI = |
| 1387 | getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1388 | |
| 1389 | for (auto BBI : L->getBlocks()) |
| 1390 | if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator())) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame^] | 1391 | InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI, |
| 1392 | RangeChecks); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1393 | |
| 1394 | if (RangeChecks.empty()) |
| 1395 | return false; |
| 1396 | |
Sanjoy Das | 9c1bfae | 2015-03-17 01:40:22 +0000 | [diff] [blame] | 1397 | auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) { |
| 1398 | OS << "irce: looking at loop "; L->print(OS); |
| 1399 | OS << "irce: loop has " << RangeChecks.size() |
| 1400 | << " inductive range checks: \n"; |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1401 | for (InductiveRangeCheck &IRC : RangeChecks) |
| 1402 | IRC.print(OS); |
Sanjoy Das | 9c1bfae | 2015-03-17 01:40:22 +0000 | [diff] [blame] | 1403 | }; |
| 1404 | |
| 1405 | DEBUG(PrintRecognizedRangeChecks(dbgs())); |
| 1406 | |
| 1407 | if (PrintRangeChecks) |
| 1408 | PrintRecognizedRangeChecks(errs()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1409 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1410 | const char *FailureReason = nullptr; |
| 1411 | Optional<LoopStructure> MaybeLoopStructure = |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 1412 | LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1413 | if (!MaybeLoopStructure.hasValue()) { |
| 1414 | DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason |
| 1415 | << "\n";); |
| 1416 | return false; |
| 1417 | } |
| 1418 | LoopStructure LS = MaybeLoopStructure.getValue(); |
| 1419 | bool Increasing = LS.IndVarIncreasing; |
| 1420 | const SCEV *MinusOne = |
| 1421 | SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true); |
| 1422 | const SCEVAddRecExpr *IndVar = |
| 1423 | cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne)); |
| 1424 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1425 | Optional<InductiveRangeCheck::Range> SafeIterRange; |
| 1426 | Instruction *ExprInsertPt = Preheader->getTerminator(); |
| 1427 | |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1428 | SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1429 | |
| 1430 | IRBuilder<> B(ExprInsertPt); |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1431 | for (InductiveRangeCheck &IRC : RangeChecks) { |
| 1432 | auto Result = IRC.computeSafeIterationSpace(SE, IndVar); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1433 | if (Result.hasValue()) { |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1434 | auto MaybeSafeIterRange = |
Sanjoy Das | 5977673 | 2016-05-21 02:31:51 +0000 | [diff] [blame] | 1435 | IntersectRange(SE, SafeIterRange, Result.getValue()); |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1436 | if (MaybeSafeIterRange.hasValue()) { |
| 1437 | RangeChecksToEliminate.push_back(IRC); |
| 1438 | SafeIterRange = MaybeSafeIterRange.getValue(); |
| 1439 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1440 | } |
| 1441 | } |
| 1442 | |
| 1443 | if (!SafeIterRange.hasValue()) |
| 1444 | return false; |
| 1445 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1446 | LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS, |
| 1447 | SE, SafeIterRange.getValue()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1448 | bool Changed = LC.run(); |
| 1449 | |
| 1450 | if (Changed) { |
| 1451 | auto PrintConstrainedLoopInfo = [L]() { |
| 1452 | dbgs() << "irce: in function "; |
| 1453 | dbgs() << L->getHeader()->getParent()->getName() << ": "; |
| 1454 | dbgs() << "constrained "; |
| 1455 | L->print(dbgs()); |
| 1456 | }; |
| 1457 | |
| 1458 | DEBUG(PrintConstrainedLoopInfo()); |
| 1459 | |
| 1460 | if (PrintChangedLoops) |
| 1461 | PrintConstrainedLoopInfo(); |
| 1462 | |
| 1463 | // Optimize away the now-redundant range checks. |
| 1464 | |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1465 | for (InductiveRangeCheck &IRC : RangeChecksToEliminate) { |
| 1466 | ConstantInt *FoldedRangeCheck = IRC.getPassingDirection() |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1467 | ? ConstantInt::getTrue(Context) |
| 1468 | : ConstantInt::getFalse(Context); |
Sanjoy Das | aa83c47 | 2016-05-23 22:16:45 +0000 | [diff] [blame] | 1469 | IRC.getCheckUse()->set(FoldedRangeCheck); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1470 | } |
| 1471 | } |
| 1472 | |
| 1473 | return Changed; |
| 1474 | } |
| 1475 | |
| 1476 | Pass *llvm::createInductiveRangeCheckEliminationPass() { |
| 1477 | return new InductiveRangeCheckElimination; |
| 1478 | } |