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