Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 1 | //===- InductiveRangeCheckElimination.cpp - -------------------------------===// |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 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 | //===----------------------------------------------------------------------===// |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 9 | // |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 10 | // The InductiveRangeCheckElimination pass splits a loop's iteration space into |
| 11 | // three disjoint ranges. It does that in a way such that the loop running in |
| 12 | // the middle loop provably does not need range checks. As an example, it will |
| 13 | // convert |
| 14 | // |
| 15 | // len = < known positive > |
| 16 | // for (i = 0; i < n; i++) { |
| 17 | // if (0 <= i && i < len) { |
| 18 | // do_something(); |
| 19 | // } else { |
| 20 | // throw_out_of_bounds(); |
| 21 | // } |
| 22 | // } |
| 23 | // |
| 24 | // to |
| 25 | // |
| 26 | // len = < known positive > |
| 27 | // limit = smin(n, len) |
| 28 | // // no first segment |
| 29 | // for (i = 0; i < limit; i++) { |
| 30 | // if (0 <= i && i < len) { // this check is fully redundant |
| 31 | // do_something(); |
| 32 | // } else { |
| 33 | // throw_out_of_bounds(); |
| 34 | // } |
| 35 | // } |
| 36 | // for (i = limit; i < n; i++) { |
| 37 | // if (0 <= i && i < len) { |
| 38 | // do_something(); |
| 39 | // } else { |
| 40 | // throw_out_of_bounds(); |
| 41 | // } |
| 42 | // } |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 43 | // |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 44 | //===----------------------------------------------------------------------===// |
| 45 | |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 46 | #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 47 | #include "llvm/ADT/APInt.h" |
| 48 | #include "llvm/ADT/ArrayRef.h" |
| 49 | #include "llvm/ADT/None.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 50 | #include "llvm/ADT/Optional.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 51 | #include "llvm/ADT/SmallPtrSet.h" |
| 52 | #include "llvm/ADT/SmallVector.h" |
| 53 | #include "llvm/ADT/StringRef.h" |
| 54 | #include "llvm/ADT/Twine.h" |
Sanjoy Das | dcf2651 | 2015-01-27 21:38:12 +0000 | [diff] [blame] | 55 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 56 | #include "llvm/Analysis/LoopAnalysisManager.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 57 | #include "llvm/Analysis/LoopInfo.h" |
| 58 | #include "llvm/Analysis/LoopPass.h" |
| 59 | #include "llvm/Analysis/ScalarEvolution.h" |
| 60 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
| 61 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 62 | #include "llvm/IR/BasicBlock.h" |
| 63 | #include "llvm/IR/CFG.h" |
| 64 | #include "llvm/IR/Constants.h" |
| 65 | #include "llvm/IR/DerivedTypes.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 66 | #include "llvm/IR/Dominators.h" |
| 67 | #include "llvm/IR/Function.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 68 | #include "llvm/IR/IRBuilder.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 69 | #include "llvm/IR/InstrTypes.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 70 | #include "llvm/IR/Instructions.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 71 | #include "llvm/IR/Metadata.h" |
| 72 | #include "llvm/IR/Module.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 73 | #include "llvm/IR/PatternMatch.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 74 | #include "llvm/IR/Type.h" |
| 75 | #include "llvm/IR/Use.h" |
| 76 | #include "llvm/IR/User.h" |
| 77 | #include "llvm/IR/Value.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 78 | #include "llvm/Pass.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 79 | #include "llvm/Support/BranchProbability.h" |
| 80 | #include "llvm/Support/Casting.h" |
| 81 | #include "llvm/Support/CommandLine.h" |
| 82 | #include "llvm/Support/Compiler.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 83 | #include "llvm/Support/Debug.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 84 | #include "llvm/Support/ErrorHandling.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 85 | #include "llvm/Support/raw_ostream.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 86 | #include "llvm/Transforms/Scalar.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 87 | #include "llvm/Transforms/Utils/Cloning.h" |
Sanjoy Das | cf18186 | 2016-08-06 00:01:56 +0000 | [diff] [blame] | 88 | #include "llvm/Transforms/Utils/LoopSimplify.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 89 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 90 | #include "llvm/Transforms/Utils/ValueMapper.h" |
| 91 | #include <algorithm> |
| 92 | #include <cassert> |
| 93 | #include <iterator> |
| 94 | #include <limits> |
| 95 | #include <utility> |
| 96 | #include <vector> |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 97 | |
| 98 | using namespace llvm; |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 99 | using namespace llvm::PatternMatch; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 100 | |
Benjamin Kramer | 970eac4 | 2015-02-06 17:51:54 +0000 | [diff] [blame] | 101 | static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden, |
| 102 | cl::init(64)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 103 | |
Benjamin Kramer | 970eac4 | 2015-02-06 17:51:54 +0000 | [diff] [blame] | 104 | static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden, |
| 105 | cl::init(false)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 106 | |
Sanjoy Das | 9c1bfae | 2015-03-17 01:40:22 +0000 | [diff] [blame] | 107 | static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden, |
| 108 | cl::init(false)); |
| 109 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 110 | static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal", |
| 111 | cl::Hidden, cl::init(10)); |
| 112 | |
Sanjoy Das | bb96979 | 2016-07-22 00:40:56 +0000 | [diff] [blame] | 113 | static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks", |
| 114 | cl::Hidden, cl::init(false)); |
| 115 | |
Max Kazantsev | 8aacef6 | 2017-10-04 06:53:22 +0000 | [diff] [blame] | 116 | static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch", |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 117 | cl::Hidden, cl::init(true)); |
Max Kazantsev | 8aacef6 | 2017-10-04 06:53:22 +0000 | [diff] [blame] | 118 | |
Sanjoy Das | 7a18a23 | 2016-08-14 01:04:36 +0000 | [diff] [blame] | 119 | static const char *ClonedLoopTag = "irce.loop.clone"; |
| 120 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 121 | #define DEBUG_TYPE "irce" |
| 122 | |
| 123 | namespace { |
| 124 | |
| 125 | /// An inductive range check is conditional branch in a loop with |
| 126 | /// |
| 127 | /// 1. a very cold successor (i.e. the branch jumps to that successor very |
| 128 | /// rarely) |
| 129 | /// |
| 130 | /// and |
| 131 | /// |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 132 | /// 2. a condition that is provably true for some contiguous range of values |
| 133 | /// taken by the containing loop's induction variable. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 134 | /// |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 135 | class InductiveRangeCheck { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 136 | // Classifies a range check |
Reid Kleckner | 0b16859 | 2015-03-17 16:50:20 +0000 | [diff] [blame] | 137 | enum RangeCheckKind : unsigned { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 138 | // Range check of the form "0 <= I". |
| 139 | RANGE_CHECK_LOWER = 1, |
| 140 | |
| 141 | // Range check of the form "I < L" where L is known positive. |
| 142 | RANGE_CHECK_UPPER = 2, |
| 143 | |
| 144 | // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER |
| 145 | // conditions. |
| 146 | RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER, |
| 147 | |
| 148 | // Unrecognized range check condition. |
| 149 | RANGE_CHECK_UNKNOWN = (unsigned)-1 |
| 150 | }; |
| 151 | |
Sanjoy Das | 2eac48d | 2016-03-09 02:34:19 +0000 | [diff] [blame] | 152 | static StringRef rangeCheckKindToStr(RangeCheckKind); |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 153 | |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 154 | const SCEV *Begin = nullptr; |
| 155 | const SCEV *Step = nullptr; |
| 156 | const SCEV *End = nullptr; |
Sanjoy Das | ee77a48 | 2016-05-26 01:50:18 +0000 | [diff] [blame] | 157 | Use *CheckUse = nullptr; |
| 158 | RangeCheckKind Kind = RANGE_CHECK_UNKNOWN; |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 159 | bool IsSigned = true; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 160 | |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 161 | static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI, |
| 162 | ScalarEvolution &SE, Value *&Index, |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 163 | Value *&Length, bool &IsSigned); |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 164 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 165 | static void |
| 166 | extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse, |
| 167 | SmallVectorImpl<InductiveRangeCheck> &Checks, |
| 168 | SmallPtrSetImpl<Value *> &Visited); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 169 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 170 | public: |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 171 | const SCEV *getBegin() const { return Begin; } |
| 172 | const SCEV *getStep() const { return Step; } |
| 173 | const SCEV *getEnd() const { return End; } |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 174 | bool isSigned() const { return IsSigned; } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 175 | |
| 176 | void print(raw_ostream &OS) const { |
| 177 | OS << "InductiveRangeCheck:\n"; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 178 | OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n"; |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 179 | OS << " Begin: "; |
| 180 | Begin->print(OS); |
| 181 | OS << " Step: "; |
| 182 | Step->print(OS); |
| 183 | OS << " End: "; |
Max Kazantsev | ef05760 | 2018-01-12 10:00:26 +0000 | [diff] [blame] | 184 | End->print(OS); |
Sanjoy Das | aa83c47 | 2016-05-23 22:16:45 +0000 | [diff] [blame] | 185 | OS << "\n CheckUse: "; |
| 186 | getCheckUse()->getUser()->print(OS); |
| 187 | OS << " Operand: " << getCheckUse()->getOperandNo() << "\n"; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 188 | } |
| 189 | |
Davide Italiano | d1279df | 2016-08-18 15:55:49 +0000 | [diff] [blame] | 190 | LLVM_DUMP_METHOD |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 191 | void dump() { |
| 192 | print(dbgs()); |
| 193 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 194 | |
Sanjoy Das | aa83c47 | 2016-05-23 22:16:45 +0000 | [diff] [blame] | 195 | Use *getCheckUse() const { return CheckUse; } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 196 | |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 197 | /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If |
Max Kazantsev | d0fe502 | 2018-01-15 05:44:43 +0000 | [diff] [blame] | 198 | /// R.getEnd() le R.getBegin(), then R denotes the empty range. |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 199 | |
| 200 | class Range { |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 201 | const SCEV *Begin; |
| 202 | const SCEV *End; |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 203 | |
| 204 | public: |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 205 | Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) { |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 206 | assert(Begin->getType() == End->getType() && "ill-typed range!"); |
| 207 | } |
| 208 | |
| 209 | Type *getType() const { return Begin->getType(); } |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 210 | const SCEV *getBegin() const { return Begin; } |
| 211 | const SCEV *getEnd() const { return End; } |
Max Kazantsev | 4332a94 | 2017-10-25 06:10:02 +0000 | [diff] [blame] | 212 | bool isEmpty(ScalarEvolution &SE, bool IsSigned) const { |
| 213 | if (Begin == End) |
| 214 | return true; |
| 215 | if (IsSigned) |
| 216 | return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End); |
| 217 | else |
| 218 | return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End); |
| 219 | } |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 220 | }; |
| 221 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 222 | /// This is the value the condition of the branch needs to evaluate to for the |
| 223 | /// branch to take the hot successor (see (1) above). |
| 224 | bool getPassingDirection() { return true; } |
| 225 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 226 | /// Computes a range for the induction variable (IndVar) in which the range |
| 227 | /// check is redundant and can be constant-folded away. The induction |
| 228 | /// variable is not required to be the canonical {0,+,1} induction variable. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 229 | Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE, |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 230 | const SCEVAddRecExpr *IndVar, |
| 231 | bool IsLatchSigned) const; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 232 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 233 | /// Parse out a set of inductive range checks from \p BI and append them to \p |
| 234 | /// Checks. |
| 235 | /// |
| 236 | /// NB! There may be conditions feeding into \p BI that aren't inductive range |
| 237 | /// checks, and hence don't end up in \p Checks. |
| 238 | static void |
| 239 | extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE, |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 240 | BranchProbabilityInfo *BPI, |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 241 | SmallVectorImpl<InductiveRangeCheck> &Checks); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 242 | }; |
| 243 | |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 244 | class InductiveRangeCheckElimination { |
| 245 | ScalarEvolution &SE; |
| 246 | BranchProbabilityInfo *BPI; |
| 247 | DominatorTree &DT; |
| 248 | LoopInfo &LI; |
| 249 | |
| 250 | public: |
| 251 | InductiveRangeCheckElimination(ScalarEvolution &SE, |
| 252 | BranchProbabilityInfo *BPI, DominatorTree &DT, |
| 253 | LoopInfo &LI) |
| 254 | : SE(SE), BPI(BPI), DT(DT), LI(LI) {} |
| 255 | |
| 256 | bool run(Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop); |
| 257 | }; |
| 258 | |
| 259 | class IRCELegacyPass : public LoopPass { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 260 | public: |
| 261 | static char ID; |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 262 | |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 263 | IRCELegacyPass() : LoopPass(ID) { |
| 264 | initializeIRCELegacyPassPass(*PassRegistry::getPassRegistry()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 265 | } |
| 266 | |
| 267 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 268 | AU.addRequired<BranchProbabilityInfoWrapperPass>(); |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 269 | getLoopAnalysisUsage(AU); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 270 | } |
| 271 | |
| 272 | bool runOnLoop(Loop *L, LPPassManager &LPM) override; |
| 273 | }; |
| 274 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 275 | } // end anonymous namespace |
| 276 | |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 277 | char IRCELegacyPass::ID = 0; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 278 | |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 279 | INITIALIZE_PASS_BEGIN(IRCELegacyPass, "irce", |
Sanjoy Das | da0d79e | 2015-09-09 03:47:18 +0000 | [diff] [blame] | 280 | "Inductive range check elimination", false, false) |
Sanjoy Das | da0d79e | 2015-09-09 03:47:18 +0000 | [diff] [blame] | 281 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 282 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 283 | INITIALIZE_PASS_END(IRCELegacyPass, "irce", "Inductive range check elimination", |
| 284 | false, false) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 285 | |
Sanjoy Das | 2eac48d | 2016-03-09 02:34:19 +0000 | [diff] [blame] | 286 | StringRef InductiveRangeCheck::rangeCheckKindToStr( |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 287 | InductiveRangeCheck::RangeCheckKind RCK) { |
| 288 | switch (RCK) { |
| 289 | case InductiveRangeCheck::RANGE_CHECK_UNKNOWN: |
| 290 | return "RANGE_CHECK_UNKNOWN"; |
| 291 | |
| 292 | case InductiveRangeCheck::RANGE_CHECK_UPPER: |
| 293 | return "RANGE_CHECK_UPPER"; |
| 294 | |
| 295 | case InductiveRangeCheck::RANGE_CHECK_LOWER: |
| 296 | return "RANGE_CHECK_LOWER"; |
| 297 | |
| 298 | case InductiveRangeCheck::RANGE_CHECK_BOTH: |
| 299 | return "RANGE_CHECK_BOTH"; |
| 300 | } |
| 301 | |
| 302 | llvm_unreachable("unknown range check type!"); |
| 303 | } |
| 304 | |
Sanjoy Das | f13900f | 2016-03-09 02:34:15 +0000 | [diff] [blame] | 305 | /// 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] | 306 | /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set |
Sanjoy Das | f13900f | 2016-03-09 02:34:15 +0000 | [diff] [blame] | 307 | /// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 308 | /// range checked, and set `Length` to the upper limit `Index` is being range |
| 309 | /// checked with if (and only if) the range check type is stronger or equal to |
| 310 | /// RANGE_CHECK_UPPER. |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 311 | InductiveRangeCheck::RangeCheckKind |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 312 | InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI, |
| 313 | ScalarEvolution &SE, Value *&Index, |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 314 | Value *&Length, bool &IsSigned) { |
Max Kazantsev | 8624a47 | 2018-04-09 06:01:22 +0000 | [diff] [blame] | 315 | auto IsLoopInvariant = [&SE, L](Value *V) { |
| 316 | return SE.isLoopInvariant(SE.getSCEV(V), L); |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 317 | }; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 318 | |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 319 | ICmpInst::Predicate Pred = ICI->getPredicate(); |
| 320 | Value *LHS = ICI->getOperand(0); |
| 321 | Value *RHS = ICI->getOperand(1); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 322 | |
| 323 | switch (Pred) { |
| 324 | default: |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 325 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 326 | |
| 327 | case ICmpInst::ICMP_SLE: |
| 328 | std::swap(LHS, RHS); |
Justin Bogner | b03fd12 | 2016-08-17 05:10:15 +0000 | [diff] [blame] | 329 | LLVM_FALLTHROUGH; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 330 | case ICmpInst::ICMP_SGE: |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 331 | IsSigned = true; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 332 | if (match(RHS, m_ConstantInt<0>())) { |
| 333 | Index = LHS; |
| 334 | return RANGE_CHECK_LOWER; |
| 335 | } |
| 336 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 337 | |
| 338 | case ICmpInst::ICMP_SLT: |
| 339 | std::swap(LHS, RHS); |
Justin Bogner | b03fd12 | 2016-08-17 05:10:15 +0000 | [diff] [blame] | 340 | LLVM_FALLTHROUGH; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 341 | case ICmpInst::ICMP_SGT: |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 342 | IsSigned = true; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 343 | if (match(RHS, m_ConstantInt<-1>())) { |
| 344 | Index = LHS; |
| 345 | return RANGE_CHECK_LOWER; |
| 346 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 347 | |
Max Kazantsev | 8624a47 | 2018-04-09 06:01:22 +0000 | [diff] [blame] | 348 | if (IsLoopInvariant(LHS)) { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 349 | Index = RHS; |
| 350 | Length = LHS; |
| 351 | return RANGE_CHECK_UPPER; |
| 352 | } |
| 353 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 354 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 355 | case ICmpInst::ICMP_ULT: |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 356 | std::swap(LHS, RHS); |
Justin Bogner | b03fd12 | 2016-08-17 05:10:15 +0000 | [diff] [blame] | 357 | LLVM_FALLTHROUGH; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 358 | case ICmpInst::ICMP_UGT: |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 359 | IsSigned = false; |
Max Kazantsev | 8624a47 | 2018-04-09 06:01:22 +0000 | [diff] [blame] | 360 | if (IsLoopInvariant(LHS)) { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 361 | Index = RHS; |
| 362 | Length = LHS; |
| 363 | return RANGE_CHECK_BOTH; |
| 364 | } |
| 365 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 366 | } |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 367 | |
| 368 | llvm_unreachable("default clause returns!"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 369 | } |
| 370 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 371 | void InductiveRangeCheck::extractRangeChecksFromCond( |
| 372 | Loop *L, ScalarEvolution &SE, Use &ConditionUse, |
| 373 | SmallVectorImpl<InductiveRangeCheck> &Checks, |
| 374 | SmallPtrSetImpl<Value *> &Visited) { |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 375 | Value *Condition = ConditionUse.get(); |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 376 | if (!Visited.insert(Condition).second) |
| 377 | return; |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 378 | |
Max Kazantsev | 1ac6e8a | 2017-11-17 06:49:26 +0000 | [diff] [blame] | 379 | // TODO: Do the same for OR, XOR, NOT etc? |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 380 | if (match(Condition, m_And(m_Value(), m_Value()))) { |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 381 | extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0), |
Max Kazantsev | 1ac6e8a | 2017-11-17 06:49:26 +0000 | [diff] [blame] | 382 | Checks, Visited); |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 383 | extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1), |
Max Kazantsev | 1ac6e8a | 2017-11-17 06:49:26 +0000 | [diff] [blame] | 384 | Checks, Visited); |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 385 | return; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 386 | } |
| 387 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 388 | ICmpInst *ICI = dyn_cast<ICmpInst>(Condition); |
| 389 | if (!ICI) |
| 390 | return; |
| 391 | |
| 392 | Value *Length = nullptr, *Index; |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 393 | bool IsSigned; |
| 394 | auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned); |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 395 | if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN) |
| 396 | return; |
| 397 | |
Sanjoy Das | 5fd7ac4 | 2016-05-24 17:19:56 +0000 | [diff] [blame] | 398 | const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 399 | bool IsAffineIndex = |
| 400 | IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine(); |
| 401 | |
| 402 | if (!IsAffineIndex) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 403 | return; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 404 | |
Max Kazantsev | ef05760 | 2018-01-12 10:00:26 +0000 | [diff] [blame] | 405 | const SCEV *End = nullptr; |
| 406 | // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L". |
| 407 | // We can potentially do much better here. |
| 408 | if (Length) |
| 409 | End = SE.getSCEV(Length); |
| 410 | else { |
| 411 | assert(RCKind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!"); |
| 412 | // So far we can only reach this point for Signed range check. This may |
| 413 | // change in future. In this case we will need to pick Unsigned max for the |
| 414 | // unsigned range check. |
| 415 | unsigned BitWidth = cast<IntegerType>(IndexAddRec->getType())->getBitWidth(); |
| 416 | const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth)); |
| 417 | End = SIntMax; |
| 418 | } |
| 419 | |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 420 | InductiveRangeCheck IRC; |
Max Kazantsev | ef05760 | 2018-01-12 10:00:26 +0000 | [diff] [blame] | 421 | IRC.End = End; |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 422 | IRC.Begin = IndexAddRec->getStart(); |
| 423 | IRC.Step = IndexAddRec->getStepRecurrence(SE); |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 424 | IRC.CheckUse = &ConditionUse; |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 425 | IRC.Kind = RCKind; |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 426 | IRC.IsSigned = IsSigned; |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 427 | Checks.push_back(IRC); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 428 | } |
| 429 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 430 | void InductiveRangeCheck::extractRangeChecksFromBranch( |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 431 | BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI, |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 432 | SmallVectorImpl<InductiveRangeCheck> &Checks) { |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 433 | if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch()) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 434 | return; |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 435 | |
| 436 | BranchProbability LikelyTaken(15, 16); |
| 437 | |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 438 | if (!SkipProfitabilityChecks && BPI && |
| 439 | BPI->getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 440 | return; |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 441 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 442 | SmallPtrSet<Value *, 8> Visited; |
| 443 | InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0), |
| 444 | Checks, Visited); |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 445 | } |
| 446 | |
Anna Thomas | 65ca8e9 | 2016-12-13 21:05:21 +0000 | [diff] [blame] | 447 | // Add metadata to the loop L to disable loop optimizations. Callers need to |
| 448 | // confirm that optimizing loop L is not beneficial. |
| 449 | static void DisableAllLoopOptsOnLoop(Loop &L) { |
| 450 | // We do not care about any existing loopID related metadata for L, since we |
| 451 | // are setting all loop metadata to false. |
| 452 | LLVMContext &Context = L.getHeader()->getContext(); |
| 453 | // Reserve first location for self reference to the LoopID metadata node. |
| 454 | MDNode *Dummy = MDNode::get(Context, {}); |
| 455 | MDNode *DisableUnroll = MDNode::get( |
| 456 | Context, {MDString::get(Context, "llvm.loop.unroll.disable")}); |
| 457 | Metadata *FalseVal = |
| 458 | ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0)); |
| 459 | MDNode *DisableVectorize = MDNode::get( |
| 460 | Context, |
| 461 | {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal}); |
| 462 | MDNode *DisableLICMVersioning = MDNode::get( |
| 463 | Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")}); |
| 464 | MDNode *DisableDistribution= MDNode::get( |
| 465 | Context, |
| 466 | {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal}); |
| 467 | MDNode *NewLoopID = |
| 468 | MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize, |
| 469 | DisableLICMVersioning, DisableDistribution}); |
| 470 | // Set operand 0 to refer to the loop id itself. |
| 471 | NewLoopID->replaceOperandWith(0, NewLoopID); |
| 472 | L.setLoopID(NewLoopID); |
| 473 | } |
| 474 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 475 | namespace { |
| 476 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 477 | // Keeps track of the structure of a loop. This is similar to llvm::Loop, |
| 478 | // except that it is more lightweight and can track the state of a loop through |
| 479 | // changing and potentially invalid IR. This structure also formalizes the |
| 480 | // kinds of loops we can deal with -- ones that have a single latch that is also |
| 481 | // an exiting block *and* have a canonical induction variable. |
| 482 | struct LoopStructure { |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 483 | const char *Tag = ""; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 484 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 485 | BasicBlock *Header = nullptr; |
| 486 | BasicBlock *Latch = nullptr; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 487 | |
| 488 | // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th |
| 489 | // successor is `LatchExit', the exit block of the loop. |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 490 | BranchInst *LatchBr = nullptr; |
| 491 | BasicBlock *LatchExit = nullptr; |
| 492 | unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max(); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 493 | |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 494 | // The loop represented by this instance of LoopStructure is semantically |
| 495 | // equivalent to: |
| 496 | // |
| 497 | // intN_ty inc = IndVarIncreasing ? 1 : -1; |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 498 | // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT; |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 499 | // |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 500 | // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase) |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 501 | // ... body ... |
| 502 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 503 | Value *IndVarBase = nullptr; |
| 504 | Value *IndVarStart = nullptr; |
| 505 | Value *IndVarStep = nullptr; |
| 506 | Value *LoopExitAt = nullptr; |
| 507 | bool IndVarIncreasing = false; |
| 508 | bool IsSignedPredicate = true; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 509 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 510 | LoopStructure() = default; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 511 | |
| 512 | template <typename M> LoopStructure map(M Map) const { |
| 513 | LoopStructure Result; |
| 514 | Result.Tag = Tag; |
| 515 | Result.Header = cast<BasicBlock>(Map(Header)); |
| 516 | Result.Latch = cast<BasicBlock>(Map(Latch)); |
| 517 | Result.LatchBr = cast<BranchInst>(Map(LatchBr)); |
| 518 | Result.LatchExit = cast<BasicBlock>(Map(LatchExit)); |
| 519 | Result.LatchBrExitIdx = LatchBrExitIdx; |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 520 | Result.IndVarBase = Map(IndVarBase); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 521 | Result.IndVarStart = Map(IndVarStart); |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 522 | Result.IndVarStep = Map(IndVarStep); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 523 | Result.LoopExitAt = Map(LoopExitAt); |
| 524 | Result.IndVarIncreasing = IndVarIncreasing; |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 525 | Result.IsSignedPredicate = IsSignedPredicate; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 526 | return Result; |
| 527 | } |
| 528 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 529 | static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &, |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 530 | BranchProbabilityInfo *BPI, |
| 531 | Loop &, const char *&); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 532 | }; |
| 533 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 534 | /// This class is used to constrain loops to run within a given iteration space. |
| 535 | /// The algorithm this class implements is given a Loop and a range [Begin, |
| 536 | /// End). The algorithm then tries to break out a "main loop" out of the loop |
| 537 | /// it is given in a way that the "main loop" runs with the induction variable |
| 538 | /// in a subset of [Begin, End). The algorithm emits appropriate pre and post |
| 539 | /// loops to run any remaining iterations. The pre loop runs any iterations in |
| 540 | /// which the induction variable is < Begin, and the post loop runs any |
| 541 | /// iterations in which the induction variable is >= End. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 542 | class LoopConstrainer { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 543 | // The representation of a clone of the original loop we started out with. |
| 544 | struct ClonedLoop { |
| 545 | // The cloned blocks |
| 546 | std::vector<BasicBlock *> Blocks; |
| 547 | |
| 548 | // `Map` maps values in the clonee into values in the cloned version |
| 549 | ValueToValueMapTy Map; |
| 550 | |
| 551 | // An instance of `LoopStructure` for the cloned loop |
| 552 | LoopStructure Structure; |
| 553 | }; |
| 554 | |
| 555 | // Result of rewriting the range of a loop. See changeIterationSpaceEnd for |
| 556 | // more details on what these fields mean. |
| 557 | struct RewrittenRangeInfo { |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 558 | BasicBlock *PseudoExit = nullptr; |
| 559 | BasicBlock *ExitSelector = nullptr; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 560 | std::vector<PHINode *> PHIValuesAtPseudoExit; |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 561 | PHINode *IndVarEnd = nullptr; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 562 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 563 | RewrittenRangeInfo() = default; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 564 | }; |
| 565 | |
| 566 | // Calculated subranges we restrict the iteration space of the main loop to. |
| 567 | // See the implementation of `calculateSubRanges' for more details on how |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 568 | // these fields are computed. `LowLimit` is None if there is no restriction |
| 569 | // on low end of the restricted iteration space of the main loop. `HighLimit` |
| 570 | // is None if there is no restriction on high end of the restricted iteration |
| 571 | // space of the main loop. |
| 572 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 573 | struct SubRanges { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 574 | Optional<const SCEV *> LowLimit; |
| 575 | Optional<const SCEV *> HighLimit; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 576 | }; |
| 577 | |
| 578 | // A utility function that does a `replaceUsesOfWith' on the incoming block |
| 579 | // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's |
| 580 | // incoming block list with `ReplaceBy'. |
| 581 | static void replacePHIBlock(PHINode *PN, BasicBlock *Block, |
| 582 | BasicBlock *ReplaceBy); |
| 583 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 584 | // Compute a safe set of limits for the main loop to run in -- effectively the |
| 585 | // intersection of `Range' and the iteration space of the original loop. |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 586 | // Return None if unable to compute the set of subranges. |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 587 | Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 588 | |
| 589 | // Clone `OriginalLoop' and return the result in CLResult. The IR after |
| 590 | // running `cloneLoop' is well formed except for the PHI nodes in CLResult -- |
| 591 | // the PHI nodes say that there is an incoming edge from `OriginalPreheader` |
| 592 | // but there is no such edge. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 593 | void cloneLoop(ClonedLoop &CLResult, const char *Tag) const; |
| 594 | |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 595 | // Create the appropriate loop structure needed to describe a cloned copy of |
| 596 | // `Original`. The clone is described by `VM`. |
| 597 | Loop *createClonedLoopStructure(Loop *Original, Loop *Parent, |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 598 | ValueToValueMapTy &VM, bool IsSubloop); |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 599 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 600 | // Rewrite the iteration space of the loop denoted by (LS, Preheader). The |
| 601 | // iteration space of the rewritten loop ends at ExitLoopAt. The start of the |
| 602 | // iteration space is not changed. `ExitLoopAt' is assumed to be slt |
| 603 | // `OriginalHeaderCount'. |
| 604 | // |
| 605 | // If there are iterations left to execute, control is made to jump to |
| 606 | // `ContinuationBlock', otherwise they take the normal loop exit. The |
| 607 | // returned `RewrittenRangeInfo' object is populated as follows: |
| 608 | // |
| 609 | // .PseudoExit is a basic block that unconditionally branches to |
| 610 | // `ContinuationBlock'. |
| 611 | // |
| 612 | // .ExitSelector is a basic block that decides, on exit from the loop, |
| 613 | // whether to branch to the "true" exit or to `PseudoExit'. |
| 614 | // |
| 615 | // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value |
| 616 | // for each PHINode in the loop header on taking the pseudo exit. |
| 617 | // |
| 618 | // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate |
| 619 | // preheader because it is made to branch to the loop header only |
| 620 | // conditionally. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 621 | RewrittenRangeInfo |
| 622 | changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader, |
| 623 | Value *ExitLoopAt, |
| 624 | BasicBlock *ContinuationBlock) const; |
| 625 | |
| 626 | // The loop denoted by `LS' has `OldPreheader' as its preheader. This |
| 627 | // function creates a new preheader for `LS' and returns it. |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 628 | BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader, |
| 629 | const char *Tag) const; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 630 | |
| 631 | // `ContinuationBlockAndPreheader' was the continuation block for some call to |
| 632 | // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'. |
| 633 | // This function rewrites the PHI nodes in `LS.Header' to start with the |
| 634 | // correct value. |
| 635 | void rewriteIncomingValuesForPHIs( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 636 | LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 637 | const LoopConstrainer::RewrittenRangeInfo &RRI) const; |
| 638 | |
| 639 | // Even though we do not preserve any passes at this time, we at least need to |
| 640 | // keep the parent loop structure consistent. The `LPPassManager' seems to |
| 641 | // 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] | 642 | // blocks denoted by BBs to this loops parent loop if required. |
| 643 | void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 644 | |
| 645 | // Some global state. |
| 646 | Function &F; |
| 647 | LLVMContext &Ctx; |
| 648 | ScalarEvolution &SE; |
Sanjoy Das | f45e03e | 2016-08-02 19:31:54 +0000 | [diff] [blame] | 649 | DominatorTree &DT; |
Sanjoy Das | 35459f0 | 2016-08-14 01:04:50 +0000 | [diff] [blame] | 650 | LoopInfo &LI; |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 651 | function_ref<void(Loop *, bool)> LPMAddNewLoop; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 652 | |
| 653 | // Information about the original loop we started out with. |
| 654 | Loop &OriginalLoop; |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 655 | |
| 656 | const SCEV *LatchTakenCount = nullptr; |
| 657 | BasicBlock *OriginalPreheader = nullptr; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 658 | |
| 659 | // The preheader of the main loop. This may or may not be different from |
| 660 | // `OriginalPreheader'. |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 661 | BasicBlock *MainLoopPreheader = nullptr; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 662 | |
| 663 | // The range we need to run the main loop in. |
| 664 | InductiveRangeCheck::Range Range; |
| 665 | |
| 666 | // The structure of the main loop (see comment at the beginning of this class |
| 667 | // for a definition) |
| 668 | LoopStructure MainLoopStructure; |
| 669 | |
| 670 | public: |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 671 | LoopConstrainer(Loop &L, LoopInfo &LI, |
| 672 | function_ref<void(Loop *, bool)> LPMAddNewLoop, |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 673 | const LoopStructure &LS, ScalarEvolution &SE, |
| 674 | DominatorTree &DT, InductiveRangeCheck::Range R) |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 675 | : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 676 | SE(SE), DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L), |
| 677 | Range(R), MainLoopStructure(LS) {} |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 678 | |
| 679 | // Entry point for the algorithm. Returns true on success. |
| 680 | bool run(); |
| 681 | }; |
| 682 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 683 | } // end anonymous namespace |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 684 | |
| 685 | void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block, |
| 686 | BasicBlock *ReplaceBy) { |
| 687 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 688 | if (PN->getIncomingBlock(i) == Block) |
| 689 | PN->setIncomingBlock(i, ReplaceBy); |
| 690 | } |
| 691 | |
Sam Parker | 90b7f4f | 2018-03-27 08:24:53 +0000 | [diff] [blame] | 692 | /// Given a loop with an deccreasing induction variable, is it possible to |
| 693 | /// safely calculate the bounds of a new loop using the given Predicate. |
| 694 | static bool isSafeDecreasingBound(const SCEV *Start, |
| 695 | const SCEV *BoundSCEV, const SCEV *Step, |
| 696 | ICmpInst::Predicate Pred, |
| 697 | unsigned LatchBrExitIdx, |
| 698 | Loop *L, ScalarEvolution &SE) { |
| 699 | if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT && |
| 700 | Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT) |
| 701 | return false; |
| 702 | |
| 703 | if (!SE.isAvailableAtLoopEntry(BoundSCEV, L)) |
| 704 | return false; |
| 705 | |
| 706 | assert(SE.isKnownNegative(Step) && "expecting negative step"); |
| 707 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 708 | LLVM_DEBUG(dbgs() << "irce: isSafeDecreasingBound with:\n"); |
| 709 | LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n"); |
| 710 | LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n"); |
| 711 | LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n"); |
| 712 | LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred) |
| 713 | << "\n"); |
| 714 | LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n"); |
Sam Parker | 90b7f4f | 2018-03-27 08:24:53 +0000 | [diff] [blame] | 715 | |
| 716 | bool IsSigned = ICmpInst::isSigned(Pred); |
| 717 | // The predicate that we need to check that the induction variable lies |
| 718 | // within bounds. |
| 719 | ICmpInst::Predicate BoundPred = |
| 720 | IsSigned ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT; |
| 721 | |
| 722 | if (LatchBrExitIdx == 1) |
| 723 | return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV); |
| 724 | |
| 725 | assert(LatchBrExitIdx == 0 && |
| 726 | "LatchBrExitIdx should be either 0 or 1"); |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 727 | |
Sam Parker | 90b7f4f | 2018-03-27 08:24:53 +0000 | [diff] [blame] | 728 | const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType())); |
| 729 | unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth(); |
| 730 | APInt Min = IsSigned ? APInt::getSignedMinValue(BitWidth) : |
| 731 | APInt::getMinValue(BitWidth); |
| 732 | const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Min), StepPlusOne); |
| 733 | |
| 734 | const SCEV *MinusOne = |
| 735 | SE.getMinusSCEV(BoundSCEV, SE.getOne(BoundSCEV->getType())); |
| 736 | |
| 737 | return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, MinusOne) && |
| 738 | SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit); |
| 739 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 740 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 741 | |
Sam Parker | 53a423a | 2018-03-26 09:29:42 +0000 | [diff] [blame] | 742 | /// Given a loop with an increasing induction variable, is it possible to |
| 743 | /// safely calculate the bounds of a new loop using the given Predicate. |
| 744 | static bool isSafeIncreasingBound(const SCEV *Start, |
| 745 | const SCEV *BoundSCEV, const SCEV *Step, |
| 746 | ICmpInst::Predicate Pred, |
| 747 | unsigned LatchBrExitIdx, |
| 748 | Loop *L, ScalarEvolution &SE) { |
| 749 | if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT && |
| 750 | Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT) |
| 751 | return false; |
| 752 | |
| 753 | if (!SE.isAvailableAtLoopEntry(BoundSCEV, L)) |
| 754 | return false; |
| 755 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 756 | LLVM_DEBUG(dbgs() << "irce: isSafeIncreasingBound with:\n"); |
| 757 | LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n"); |
| 758 | LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n"); |
| 759 | LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n"); |
| 760 | LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred) |
| 761 | << "\n"); |
| 762 | LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n"); |
Sam Parker | 53a423a | 2018-03-26 09:29:42 +0000 | [diff] [blame] | 763 | |
| 764 | bool IsSigned = ICmpInst::isSigned(Pred); |
| 765 | // The predicate that we need to check that the induction variable lies |
| 766 | // within bounds. |
| 767 | ICmpInst::Predicate BoundPred = |
| 768 | IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT; |
| 769 | |
| 770 | if (LatchBrExitIdx == 1) |
| 771 | return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV); |
| 772 | |
| 773 | assert(LatchBrExitIdx == 0 && "LatchBrExitIdx should be 0 or 1"); |
| 774 | |
| 775 | const SCEV *StepMinusOne = |
| 776 | SE.getMinusSCEV(Step, SE.getOne(Step->getType())); |
| 777 | unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth(); |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 778 | APInt Max = IsSigned ? APInt::getSignedMaxValue(BitWidth) : |
Sam Parker | 53a423a | 2018-03-26 09:29:42 +0000 | [diff] [blame] | 779 | APInt::getMaxValue(BitWidth); |
| 780 | const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Max), StepMinusOne); |
| 781 | |
| 782 | return (SE.isLoopEntryGuardedByCond(L, BoundPred, Start, |
| 783 | SE.getAddExpr(BoundSCEV, Step)) && |
| 784 | SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit)); |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 785 | } |
| 786 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 787 | Optional<LoopStructure> |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 788 | LoopStructure::parseLoopStructure(ScalarEvolution &SE, |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 789 | BranchProbabilityInfo *BPI, Loop &L, |
| 790 | const char *&FailureReason) { |
Sanjoy Das | 43fdc54 | 2016-08-14 01:04:31 +0000 | [diff] [blame] | 791 | if (!L.isLoopSimplifyForm()) { |
| 792 | FailureReason = "loop not in LoopSimplify form"; |
Sanjoy Das | 2a2f14d | 2016-08-13 23:36:35 +0000 | [diff] [blame] | 793 | return None; |
Sanjoy Das | 43fdc54 | 2016-08-14 01:04:31 +0000 | [diff] [blame] | 794 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 795 | |
| 796 | BasicBlock *Latch = L.getLoopLatch(); |
Sanjoy Das | 2a2f14d | 2016-08-13 23:36:35 +0000 | [diff] [blame] | 797 | assert(Latch && "Simplified loops only have one latch!"); |
| 798 | |
Sanjoy Das | 7a18a23 | 2016-08-14 01:04:36 +0000 | [diff] [blame] | 799 | if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) { |
| 800 | FailureReason = "loop has already been cloned"; |
| 801 | return None; |
| 802 | } |
| 803 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 804 | if (!L.isLoopExiting(Latch)) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 805 | FailureReason = "no loop latch"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 806 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 807 | } |
| 808 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 809 | BasicBlock *Header = L.getHeader(); |
| 810 | BasicBlock *Preheader = L.getLoopPreheader(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 811 | if (!Preheader) { |
| 812 | FailureReason = "no preheader"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 813 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 814 | } |
| 815 | |
Sanjoy Das | 81c00fe | 2016-06-23 18:03:26 +0000 | [diff] [blame] | 816 | BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 817 | if (!LatchBr || LatchBr->isUnconditional()) { |
| 818 | FailureReason = "latch terminator not conditional branch"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 819 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 820 | } |
| 821 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 822 | unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 823 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 824 | BranchProbability ExitProbability = |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 825 | BPI ? BPI->getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx) |
| 826 | : BranchProbability::getZero(); |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 827 | |
Sanjoy Das | bb96979 | 2016-07-22 00:40:56 +0000 | [diff] [blame] | 828 | if (!SkipProfitabilityChecks && |
| 829 | ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) { |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 830 | FailureReason = "short running loop, not profitable"; |
| 831 | return None; |
| 832 | } |
| 833 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 834 | ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition()); |
| 835 | if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) { |
| 836 | FailureReason = "latch terminator branch not conditional on integral icmp"; |
| 837 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 838 | } |
| 839 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 840 | const SCEV *LatchCount = SE.getExitCount(&L, Latch); |
| 841 | if (isa<SCEVCouldNotCompute>(LatchCount)) { |
| 842 | FailureReason = "could not compute latch count"; |
| 843 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 844 | } |
| 845 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 846 | ICmpInst::Predicate Pred = ICI->getPredicate(); |
| 847 | Value *LeftValue = ICI->getOperand(0); |
| 848 | const SCEV *LeftSCEV = SE.getSCEV(LeftValue); |
| 849 | IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType()); |
| 850 | |
| 851 | Value *RightValue = ICI->getOperand(1); |
| 852 | const SCEV *RightSCEV = SE.getSCEV(RightValue); |
| 853 | |
| 854 | // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence. |
| 855 | if (!isa<SCEVAddRecExpr>(LeftSCEV)) { |
| 856 | if (isa<SCEVAddRecExpr>(RightSCEV)) { |
| 857 | std::swap(LeftSCEV, RightSCEV); |
| 858 | std::swap(LeftValue, RightValue); |
| 859 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 860 | } else { |
| 861 | FailureReason = "no add recurrences in the icmp"; |
| 862 | return None; |
| 863 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 864 | } |
| 865 | |
Sanjoy Das | 45dc94a | 2015-03-24 19:29:22 +0000 | [diff] [blame] | 866 | auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) { |
| 867 | if (AR->getNoWrapFlags(SCEV::FlagNSW)) |
| 868 | return true; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 869 | |
| 870 | IntegerType *Ty = cast<IntegerType>(AR->getType()); |
| 871 | IntegerType *WideTy = |
| 872 | IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2); |
| 873 | |
Sanjoy Das | 45dc94a | 2015-03-24 19:29:22 +0000 | [diff] [blame] | 874 | const SCEVAddRecExpr *ExtendAfterOp = |
| 875 | dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy)); |
| 876 | if (ExtendAfterOp) { |
| 877 | const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy); |
| 878 | const SCEV *ExtendedStep = |
| 879 | SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy); |
| 880 | |
| 881 | bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart && |
| 882 | ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep; |
| 883 | |
| 884 | if (NoSignedWrap) |
| 885 | return true; |
| 886 | } |
| 887 | |
| 888 | // We may have proved this when computing the sign extension above. |
| 889 | return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap; |
| 890 | }; |
| 891 | |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 892 | // `ICI` is interpreted as taking the backedge if the *next* value of the |
| 893 | // induction variable satisfies some constraint. |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 894 | |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 895 | const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV); |
Sam Parker | 3c19051 | 2018-04-18 13:50:28 +0000 | [diff] [blame] | 896 | if (!IndVarBase->isAffine()) { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 897 | FailureReason = "LHS in icmp not induction variable"; |
| 898 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 899 | } |
Sam Parker | 3c19051 | 2018-04-18 13:50:28 +0000 | [diff] [blame] | 900 | const SCEV* StepRec = IndVarBase->getStepRecurrence(SE); |
Max Kazantsev | 786032c | 2018-05-04 07:34:35 +0000 | [diff] [blame] | 901 | if (!isa<SCEVConstant>(StepRec)) { |
Sam Parker | 3c19051 | 2018-04-18 13:50:28 +0000 | [diff] [blame] | 902 | FailureReason = "LHS in icmp not induction variable"; |
| 903 | return None; |
| 904 | } |
Max Kazantsev | 786032c | 2018-05-04 07:34:35 +0000 | [diff] [blame] | 905 | ConstantInt *StepCI = cast<SCEVConstant>(StepRec)->getValue(); |
| 906 | |
Sam Parker | 3c19051 | 2018-04-18 13:50:28 +0000 | [diff] [blame] | 907 | if (ICI->isEquality() && !HasNoSignedWrap(IndVarBase)) { |
| 908 | FailureReason = "LHS in icmp needs nsw for equality predicates"; |
| 909 | return None; |
| 910 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 911 | |
Sam Parker | 3c19051 | 2018-04-18 13:50:28 +0000 | [diff] [blame] | 912 | assert(!StepCI->isZero() && "Zero step?"); |
| 913 | bool IsIncreasing = !StepCI->isNegative(); |
| 914 | bool IsSignedPredicate = ICmpInst::isSigned(Pred); |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 915 | const SCEV *StartNext = IndVarBase->getStart(); |
| 916 | const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE)); |
| 917 | const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend); |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 918 | const SCEV *Step = SE.getSCEV(StepCI); |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 919 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 920 | ConstantInt *One = ConstantInt::get(IndVarTy, 1); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 921 | if (IsIncreasing) { |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 922 | bool DecreasedRightValueByOne = false; |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 923 | if (StepCI->isOne()) { |
| 924 | // Try to turn eq/ne predicates to those we can work with. |
| 925 | if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1) |
| 926 | // while (++i != len) { while (++i < len) { |
| 927 | // ... ---> ... |
| 928 | // } } |
| 929 | // If both parts are known non-negative, it is profitable to use |
| 930 | // unsigned comparison in increasing loop. This allows us to make the |
| 931 | // comparison check against "RightSCEV + 1" more optimistic. |
Sam Parker | 9737535 | 2018-04-12 12:49:40 +0000 | [diff] [blame] | 932 | if (isKnownNonNegativeInLoop(IndVarStart, &L, SE) && |
| 933 | isKnownNonNegativeInLoop(RightSCEV, &L, SE)) |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 934 | Pred = ICmpInst::ICMP_ULT; |
| 935 | else |
| 936 | Pred = ICmpInst::ICMP_SLT; |
Sam Parker | 53a423a | 2018-03-26 09:29:42 +0000 | [diff] [blame] | 937 | else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) { |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 938 | // while (true) { while (true) { |
| 939 | // if (++i == len) ---> if (++i > len - 1) |
| 940 | // break; break; |
| 941 | // ... ... |
| 942 | // } } |
Sam Parker | 53a423a | 2018-03-26 09:29:42 +0000 | [diff] [blame] | 943 | if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) && |
Max Kazantsev | a78dc4d | 2019-01-15 09:51:34 +0000 | [diff] [blame] | 944 | cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/false)) { |
Sam Parker | 53a423a | 2018-03-26 09:29:42 +0000 | [diff] [blame] | 945 | Pred = ICmpInst::ICMP_UGT; |
| 946 | RightSCEV = SE.getMinusSCEV(RightSCEV, |
| 947 | SE.getOne(RightSCEV->getType())); |
| 948 | DecreasedRightValueByOne = true; |
Max Kazantsev | a78dc4d | 2019-01-15 09:51:34 +0000 | [diff] [blame] | 949 | } else if (cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/true)) { |
Sam Parker | 53a423a | 2018-03-26 09:29:42 +0000 | [diff] [blame] | 950 | Pred = ICmpInst::ICMP_SGT; |
| 951 | RightSCEV = SE.getMinusSCEV(RightSCEV, |
| 952 | SE.getOne(RightSCEV->getType())); |
| 953 | DecreasedRightValueByOne = true; |
| 954 | } |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 955 | } |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 956 | } |
| 957 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 958 | bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT); |
| 959 | bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 960 | bool FoundExpectedPred = |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 961 | (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 962 | |
| 963 | if (!FoundExpectedPred) { |
| 964 | FailureReason = "expected icmp slt semantically, found something else"; |
| 965 | return None; |
| 966 | } |
| 967 | |
Sam Parker | 53a423a | 2018-03-26 09:29:42 +0000 | [diff] [blame] | 968 | IsSignedPredicate = ICmpInst::isSigned(Pred); |
Max Kazantsev | 8aacef6 | 2017-10-04 06:53:22 +0000 | [diff] [blame] | 969 | if (!IsSignedPredicate && !AllowUnsignedLatchCondition) { |
| 970 | FailureReason = "unsigned latch conditions are explicitly prohibited"; |
| 971 | return None; |
| 972 | } |
| 973 | |
Sam Parker | 53a423a | 2018-03-26 09:29:42 +0000 | [diff] [blame] | 974 | if (!isSafeIncreasingBound(IndVarStart, RightSCEV, Step, Pred, |
| 975 | LatchBrExitIdx, &L, SE)) { |
| 976 | FailureReason = "Unsafe loop bounds"; |
| 977 | return None; |
| 978 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 979 | if (LatchBrExitIdx == 0) { |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 980 | // We need to increase the right value unless we have already decreased |
| 981 | // it virtually when we replaced EQ with SGT. |
| 982 | if (!DecreasedRightValueByOne) { |
| 983 | IRBuilder<> B(Preheader->getTerminator()); |
| 984 | RightValue = B.CreateAdd(RightValue, One); |
| 985 | } |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 986 | } else { |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 987 | assert(!DecreasedRightValueByOne && |
| 988 | "Right value can be decreased only for LatchBrExitIdx == 0!"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 989 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 990 | } else { |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 991 | bool IncreasedRightValueByOne = false; |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 992 | if (StepCI->isMinusOne()) { |
| 993 | // Try to turn eq/ne predicates to those we can work with. |
| 994 | if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1) |
| 995 | // while (--i != len) { while (--i > len) { |
| 996 | // ... ---> ... |
| 997 | // } } |
| 998 | // We intentionally don't turn the predicate into UGT even if we know |
| 999 | // that both operands are non-negative, because it will only pessimize |
| 1000 | // our check against "RightSCEV - 1". |
| 1001 | Pred = ICmpInst::ICMP_SGT; |
Sam Parker | 90b7f4f | 2018-03-27 08:24:53 +0000 | [diff] [blame] | 1002 | else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) { |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 1003 | // while (true) { while (true) { |
| 1004 | // if (--i == len) ---> if (--i < len + 1) |
| 1005 | // break; break; |
| 1006 | // ... ... |
| 1007 | // } } |
Sam Parker | 90b7f4f | 2018-03-27 08:24:53 +0000 | [diff] [blame] | 1008 | if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) && |
Max Kazantsev | a78dc4d | 2019-01-15 09:51:34 +0000 | [diff] [blame] | 1009 | cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ false)) { |
Sam Parker | 90b7f4f | 2018-03-27 08:24:53 +0000 | [diff] [blame] | 1010 | Pred = ICmpInst::ICMP_ULT; |
| 1011 | RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType())); |
| 1012 | IncreasedRightValueByOne = true; |
Max Kazantsev | a78dc4d | 2019-01-15 09:51:34 +0000 | [diff] [blame] | 1013 | } else if (cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ true)) { |
Sam Parker | 90b7f4f | 2018-03-27 08:24:53 +0000 | [diff] [blame] | 1014 | Pred = ICmpInst::ICMP_SLT; |
| 1015 | RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType())); |
| 1016 | IncreasedRightValueByOne = true; |
| 1017 | } |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 1018 | } |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 1019 | } |
| 1020 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1021 | bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT); |
| 1022 | bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT); |
| 1023 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1024 | bool FoundExpectedPred = |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1025 | (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1026 | |
| 1027 | if (!FoundExpectedPred) { |
| 1028 | FailureReason = "expected icmp sgt semantically, found something else"; |
| 1029 | return None; |
| 1030 | } |
| 1031 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1032 | IsSignedPredicate = |
| 1033 | Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT; |
Max Kazantsev | 8aacef6 | 2017-10-04 06:53:22 +0000 | [diff] [blame] | 1034 | |
Max Kazantsev | 8aacef6 | 2017-10-04 06:53:22 +0000 | [diff] [blame] | 1035 | if (!IsSignedPredicate && !AllowUnsignedLatchCondition) { |
| 1036 | FailureReason = "unsigned latch conditions are explicitly prohibited"; |
| 1037 | return None; |
| 1038 | } |
| 1039 | |
Sam Parker | 90b7f4f | 2018-03-27 08:24:53 +0000 | [diff] [blame] | 1040 | if (!isSafeDecreasingBound(IndVarStart, RightSCEV, Step, Pred, |
| 1041 | LatchBrExitIdx, &L, SE)) { |
| 1042 | FailureReason = "Unsafe bounds"; |
| 1043 | return None; |
| 1044 | } |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1045 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1046 | if (LatchBrExitIdx == 0) { |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 1047 | // We need to decrease the right value unless we have already increased |
| 1048 | // it virtually when we replaced EQ with SLT. |
| 1049 | if (!IncreasedRightValueByOne) { |
| 1050 | IRBuilder<> B(Preheader->getTerminator()); |
| 1051 | RightValue = B.CreateSub(RightValue, One); |
| 1052 | } |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 1053 | } else { |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 1054 | assert(!IncreasedRightValueByOne && |
| 1055 | "Right value can be increased only for LatchBrExitIdx == 0!"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1056 | } |
| 1057 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1058 | BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx); |
| 1059 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1060 | assert(SE.getLoopDisposition(LatchCount, &L) == |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1061 | ScalarEvolution::LoopInvariant && |
| 1062 | "loop variant exit count doesn't make sense!"); |
| 1063 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1064 | assert(!L.contains(LatchExit) && "expected an exit block!"); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1065 | const DataLayout &DL = Preheader->getModule()->getDataLayout(); |
| 1066 | Value *IndVarStartV = |
| 1067 | SCEVExpander(SE, DL, "irce") |
Sanjoy Das | 81c00fe | 2016-06-23 18:03:26 +0000 | [diff] [blame] | 1068 | .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1069 | IndVarStartV->setName("indvar.start"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1070 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1071 | LoopStructure Result; |
| 1072 | |
| 1073 | Result.Tag = "main"; |
| 1074 | Result.Header = Header; |
| 1075 | Result.Latch = Latch; |
| 1076 | Result.LatchBr = LatchBr; |
| 1077 | Result.LatchExit = LatchExit; |
| 1078 | Result.LatchBrExitIdx = LatchBrExitIdx; |
| 1079 | Result.IndVarStart = IndVarStartV; |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 1080 | Result.IndVarStep = StepCI; |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1081 | Result.IndVarBase = LeftValue; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1082 | Result.IndVarIncreasing = IsIncreasing; |
| 1083 | Result.LoopExitAt = RightValue; |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1084 | Result.IsSignedPredicate = IsSignedPredicate; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1085 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1086 | FailureReason = nullptr; |
| 1087 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1088 | return Result; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1089 | } |
| 1090 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1091 | Optional<LoopConstrainer::SubRanges> |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1092 | LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1093 | IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType()); |
| 1094 | |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 1095 | if (Range.getType() != Ty) |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1096 | return None; |
| 1097 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1098 | LoopConstrainer::SubRanges Result; |
| 1099 | |
| 1100 | // I think we can be more aggressive here and make this nuw / nsw if the |
| 1101 | // addition that feeds into the icmp for the latch's terminating branch is nuw |
| 1102 | // / nsw. In any case, a wrapping 2's complement addition is safe. |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1103 | const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart); |
| 1104 | const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1105 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1106 | bool Increasing = MainLoopStructure.IndVarIncreasing; |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1107 | |
Max Kazantsev | f80ffa1 | 2017-07-14 06:35:03 +0000 | [diff] [blame] | 1108 | // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or |
| 1109 | // [Smallest, GreatestSeen] is the range of values the induction variable |
| 1110 | // takes. |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1111 | |
Max Kazantsev | f80ffa1 | 2017-07-14 06:35:03 +0000 | [diff] [blame] | 1112 | const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr; |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1113 | |
Max Kazantsev | f80ffa1 | 2017-07-14 06:35:03 +0000 | [diff] [blame] | 1114 | const SCEV *One = SE.getOne(Ty); |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1115 | if (Increasing) { |
| 1116 | Smallest = Start; |
| 1117 | Greatest = End; |
Max Kazantsev | f80ffa1 | 2017-07-14 06:35:03 +0000 | [diff] [blame] | 1118 | // No overflow, because the range [Smallest, GreatestSeen] is not empty. |
| 1119 | GreatestSeen = SE.getMinusSCEV(End, One); |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1120 | } else { |
| 1121 | // These two computations may sign-overflow. Here is why that is okay: |
| 1122 | // |
| 1123 | // We know that the induction variable does not sign-overflow on any |
| 1124 | // iteration except the last one, and it starts at `Start` and ends at |
| 1125 | // `End`, decrementing by one every time. |
| 1126 | // |
| 1127 | // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the |
| 1128 | // induction variable is decreasing we know that that the smallest value |
| 1129 | // the loop body is actually executed with is `INT_SMIN` == `Smallest`. |
| 1130 | // |
| 1131 | // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In |
| 1132 | // that case, `Clamp` will always return `Smallest` and |
| 1133 | // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`) |
| 1134 | // will be an empty range. Returning an empty range is always safe. |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1135 | |
Max Kazantsev | 6c466a3 | 2017-06-28 04:57:45 +0000 | [diff] [blame] | 1136 | Smallest = SE.getAddExpr(End, One); |
| 1137 | Greatest = SE.getAddExpr(Start, One); |
Max Kazantsev | f80ffa1 | 2017-07-14 06:35:03 +0000 | [diff] [blame] | 1138 | GreatestSeen = Start; |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1139 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1140 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1141 | auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) { |
Max Kazantsev | 6f5229d7 | 2017-11-01 13:21:56 +0000 | [diff] [blame] | 1142 | return IsSignedPredicate |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1143 | ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S)) |
| 1144 | : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S)); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1145 | }; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1146 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1147 | // In some cases we can prove that we don't need a pre or post loop. |
| 1148 | ICmpInst::Predicate PredLE = |
| 1149 | IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; |
| 1150 | ICmpInst::Predicate PredLT = |
| 1151 | IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1152 | |
| 1153 | bool ProvablyNoPreloop = |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1154 | SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1155 | if (!ProvablyNoPreloop) |
| 1156 | Result.LowLimit = Clamp(Range.getBegin()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1157 | |
| 1158 | bool ProvablyNoPostLoop = |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1159 | SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1160 | if (!ProvablyNoPostLoop) |
| 1161 | Result.HighLimit = Clamp(Range.getEnd()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1162 | |
| 1163 | return Result; |
| 1164 | } |
| 1165 | |
| 1166 | void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result, |
| 1167 | const char *Tag) const { |
| 1168 | for (BasicBlock *BB : OriginalLoop.getBlocks()) { |
| 1169 | BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F); |
| 1170 | Result.Blocks.push_back(Clone); |
| 1171 | Result.Map[BB] = Clone; |
| 1172 | } |
| 1173 | |
| 1174 | auto GetClonedValue = [&Result](Value *V) { |
| 1175 | assert(V && "null values not in domain!"); |
| 1176 | auto It = Result.Map.find(V); |
| 1177 | if (It == Result.Map.end()) |
| 1178 | return V; |
| 1179 | return static_cast<Value *>(It->second); |
| 1180 | }; |
| 1181 | |
Sanjoy Das | 7a18a23 | 2016-08-14 01:04:36 +0000 | [diff] [blame] | 1182 | auto *ClonedLatch = |
| 1183 | cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch())); |
| 1184 | ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag, |
| 1185 | MDNode::get(Ctx, {})); |
| 1186 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1187 | Result.Structure = MainLoopStructure.map(GetClonedValue); |
| 1188 | Result.Structure.Tag = Tag; |
| 1189 | |
| 1190 | for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) { |
| 1191 | BasicBlock *ClonedBB = Result.Blocks[i]; |
| 1192 | BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i]; |
| 1193 | |
| 1194 | assert(Result.Map[OriginalBB] == ClonedBB && "invariant!"); |
| 1195 | |
| 1196 | for (Instruction &I : *ClonedBB) |
| 1197 | RemapInstruction(&I, Result.Map, |
Duncan P. N. Exon Smith | da68cbc | 2016-04-07 00:26:43 +0000 | [diff] [blame] | 1198 | RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1199 | |
| 1200 | // Exit blocks will now have one more predecessor and their PHI nodes need |
| 1201 | // to be edited to reflect that. No phi nodes need to be introduced because |
| 1202 | // the loop is in LCSSA. |
| 1203 | |
Sanjoy Das | d1d62a1 | 2016-08-13 22:00:09 +0000 | [diff] [blame] | 1204 | for (auto *SBB : successors(OriginalBB)) { |
| 1205 | if (OriginalLoop.contains(SBB)) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1206 | continue; // not an exit block |
| 1207 | |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 1208 | for (PHINode &PN : SBB->phis()) { |
| 1209 | Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB); |
| 1210 | PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1211 | } |
| 1212 | } |
| 1213 | } |
| 1214 | } |
| 1215 | |
| 1216 | LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1217 | const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1218 | BasicBlock *ContinuationBlock) const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1219 | // We start with a loop with a single latch: |
| 1220 | // |
| 1221 | // +--------------------+ |
| 1222 | // | | |
| 1223 | // | preheader | |
| 1224 | // | | |
| 1225 | // +--------+-----------+ |
| 1226 | // | ----------------\ |
| 1227 | // | / | |
| 1228 | // +--------v----v------+ | |
| 1229 | // | | | |
| 1230 | // | header | | |
| 1231 | // | | | |
| 1232 | // +--------------------+ | |
| 1233 | // | |
| 1234 | // ..... | |
| 1235 | // | |
| 1236 | // +--------------------+ | |
| 1237 | // | | | |
| 1238 | // | latch >----------/ |
| 1239 | // | | |
| 1240 | // +-------v------------+ |
| 1241 | // | |
| 1242 | // | |
| 1243 | // | +--------------------+ |
| 1244 | // | | | |
| 1245 | // +---> original exit | |
| 1246 | // | | |
| 1247 | // +--------------------+ |
| 1248 | // |
| 1249 | // We change the control flow to look like |
| 1250 | // |
| 1251 | // |
| 1252 | // +--------------------+ |
| 1253 | // | | |
| 1254 | // | preheader >-------------------------+ |
| 1255 | // | | | |
| 1256 | // +--------v-----------+ | |
| 1257 | // | /-------------+ | |
| 1258 | // | / | | |
| 1259 | // +--------v--v--------+ | | |
| 1260 | // | | | | |
| 1261 | // | header | | +--------+ | |
| 1262 | // | | | | | | |
| 1263 | // +--------------------+ | | +-----v-----v-----------+ |
| 1264 | // | | | | |
| 1265 | // | | | .pseudo.exit | |
| 1266 | // | | | | |
| 1267 | // | | +-----------v-----------+ |
| 1268 | // | | | |
| 1269 | // ..... | | | |
| 1270 | // | | +--------v-------------+ |
| 1271 | // +--------------------+ | | | | |
| 1272 | // | | | | | ContinuationBlock | |
| 1273 | // | latch >------+ | | | |
| 1274 | // | | | +----------------------+ |
| 1275 | // +---------v----------+ | |
| 1276 | // | | |
| 1277 | // | | |
| 1278 | // | +---------------^-----+ |
| 1279 | // | | | |
| 1280 | // +-----> .exit.selector | |
| 1281 | // | | |
| 1282 | // +----------v----------+ |
| 1283 | // | |
| 1284 | // +--------------------+ | |
| 1285 | // | | | |
| 1286 | // | original exit <----+ |
| 1287 | // | | |
| 1288 | // +--------------------+ |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1289 | |
| 1290 | RewrittenRangeInfo RRI; |
| 1291 | |
Duncan P. N. Exon Smith | 3bcaa81 | 2016-08-17 01:16:17 +0000 | [diff] [blame] | 1292 | BasicBlock *BBInsertLocation = LS.Latch->getNextNode(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1293 | 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] | 1294 | &F, BBInsertLocation); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1295 | 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] | 1296 | BBInsertLocation); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1297 | |
Sanjoy Das | 81c00fe | 2016-06-23 18:03:26 +0000 | [diff] [blame] | 1298 | BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1299 | bool Increasing = LS.IndVarIncreasing; |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1300 | bool IsSignedPredicate = LS.IsSignedPredicate; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1301 | |
| 1302 | IRBuilder<> B(PreheaderJump); |
| 1303 | |
| 1304 | // EnterLoopCond - is it okay to start executing this `LS'? |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1305 | Value *EnterLoopCond = nullptr; |
| 1306 | if (Increasing) |
| 1307 | EnterLoopCond = IsSignedPredicate |
| 1308 | ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt) |
| 1309 | : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt); |
| 1310 | else |
| 1311 | EnterLoopCond = IsSignedPredicate |
| 1312 | ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt) |
| 1313 | : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1314 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1315 | B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit); |
| 1316 | PreheaderJump->eraseFromParent(); |
| 1317 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1318 | LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1319 | B.SetInsertPoint(LS.LatchBr); |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1320 | Value *TakeBackedgeLoopCond = nullptr; |
| 1321 | if (Increasing) |
| 1322 | TakeBackedgeLoopCond = IsSignedPredicate |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1323 | ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt) |
| 1324 | : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt); |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1325 | else |
| 1326 | TakeBackedgeLoopCond = IsSignedPredicate |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1327 | ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt) |
| 1328 | : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1329 | Value *CondForBranch = LS.LatchBrExitIdx == 1 |
| 1330 | ? TakeBackedgeLoopCond |
| 1331 | : B.CreateNot(TakeBackedgeLoopCond); |
| 1332 | |
| 1333 | LS.LatchBr->setCondition(CondForBranch); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1334 | |
| 1335 | B.SetInsertPoint(RRI.ExitSelector); |
| 1336 | |
| 1337 | // IterationsLeft - are there any more iterations left, given the original |
| 1338 | // upper bound on the induction variable? If not, we branch to the "real" |
| 1339 | // exit. |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1340 | Value *IterationsLeft = nullptr; |
| 1341 | if (Increasing) |
| 1342 | IterationsLeft = IsSignedPredicate |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1343 | ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt) |
| 1344 | : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt); |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1345 | else |
| 1346 | IterationsLeft = IsSignedPredicate |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1347 | ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt) |
| 1348 | : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1349 | B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit); |
| 1350 | |
| 1351 | BranchInst *BranchToContinuation = |
| 1352 | BranchInst::Create(ContinuationBlock, RRI.PseudoExit); |
| 1353 | |
| 1354 | // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of |
| 1355 | // each of the PHI nodes in the loop header. This feeds into the initial |
| 1356 | // value of the same PHI nodes if/when we continue execution. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 1357 | for (PHINode &PN : LS.Header->phis()) { |
| 1358 | PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy", |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1359 | BranchToContinuation); |
| 1360 | |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 1361 | NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader); |
| 1362 | NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch), |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 1363 | RRI.ExitSelector); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1364 | RRI.PHIValuesAtPseudoExit.push_back(NewPHI); |
| 1365 | } |
| 1366 | |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1367 | RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end", |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1368 | BranchToContinuation); |
| 1369 | RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader); |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1370 | RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1371 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1372 | // The latch exit now has a branch from `RRI.ExitSelector' instead of |
| 1373 | // `LS.Latch'. The PHI nodes need to be updated to reflect that. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 1374 | for (PHINode &PN : LS.LatchExit->phis()) |
| 1375 | replacePHIBlock(&PN, LS.Latch, RRI.ExitSelector); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1376 | |
| 1377 | return RRI; |
| 1378 | } |
| 1379 | |
| 1380 | void LoopConstrainer::rewriteIncomingValuesForPHIs( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1381 | LoopStructure &LS, BasicBlock *ContinuationBlock, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1382 | const LoopConstrainer::RewrittenRangeInfo &RRI) const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1383 | unsigned PHIIndex = 0; |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 1384 | for (PHINode &PN : LS.Header->phis()) |
| 1385 | for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i) |
| 1386 | if (PN.getIncomingBlock(i) == ContinuationBlock) |
| 1387 | PN.setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1388 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1389 | LS.IndVarStart = RRI.IndVarEnd; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1390 | } |
| 1391 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1392 | BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS, |
| 1393 | BasicBlock *OldPreheader, |
| 1394 | const char *Tag) const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1395 | BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header); |
| 1396 | BranchInst::Create(LS.Header, Preheader); |
| 1397 | |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 1398 | for (PHINode &PN : LS.Header->phis()) |
| 1399 | for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i) |
| 1400 | replacePHIBlock(&PN, OldPreheader, Preheader); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1401 | |
| 1402 | return Preheader; |
| 1403 | } |
| 1404 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1405 | void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1406 | Loop *ParentLoop = OriginalLoop.getParentLoop(); |
| 1407 | if (!ParentLoop) |
| 1408 | return; |
| 1409 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1410 | for (BasicBlock *BB : BBs) |
Sanjoy Das | 83a7285 | 2016-08-02 19:32:01 +0000 | [diff] [blame] | 1411 | ParentLoop->addBasicBlockToLoop(BB, LI); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1412 | } |
| 1413 | |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1414 | Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent, |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 1415 | ValueToValueMapTy &VM, |
| 1416 | bool IsSubloop) { |
Sanjoy Das | def1729 | 2017-09-28 02:45:42 +0000 | [diff] [blame] | 1417 | Loop &New = *LI.AllocateLoop(); |
Chandler Carruth | 29c22d2 | 2017-05-25 03:01:31 +0000 | [diff] [blame] | 1418 | if (Parent) |
| 1419 | Parent->addChildLoop(&New); |
| 1420 | else |
| 1421 | LI.addTopLevelLoop(&New); |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 1422 | LPMAddNewLoop(&New, IsSubloop); |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1423 | |
| 1424 | // Add all of the blocks in Original to the new loop. |
| 1425 | for (auto *BB : Original->blocks()) |
| 1426 | if (LI.getLoopFor(BB) == Original) |
| 1427 | New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI); |
| 1428 | |
| 1429 | // Add all of the subloops to the new loop. |
| 1430 | for (Loop *SubLoop : *Original) |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 1431 | createClonedLoopStructure(SubLoop, &New, VM, /* IsSubloop */ true); |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1432 | |
| 1433 | return &New; |
| 1434 | } |
| 1435 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1436 | bool LoopConstrainer::run() { |
| 1437 | BasicBlock *Preheader = nullptr; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1438 | LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch); |
| 1439 | Preheader = OriginalLoop.getLoopPreheader(); |
| 1440 | assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr && |
| 1441 | "preconditions!"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1442 | |
| 1443 | OriginalPreheader = Preheader; |
| 1444 | MainLoopPreheader = Preheader; |
| 1445 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1446 | bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate; |
| 1447 | Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate); |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1448 | if (!MaybeSR.hasValue()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1449 | LLVM_DEBUG(dbgs() << "irce: could not compute subranges\n"); |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1450 | return false; |
| 1451 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1452 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1453 | SubRanges SR = MaybeSR.getValue(); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1454 | bool Increasing = MainLoopStructure.IndVarIncreasing; |
| 1455 | IntegerType *IVTy = |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1456 | cast<IntegerType>(MainLoopStructure.IndVarBase->getType()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1457 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1458 | SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1459 | Instruction *InsertPt = OriginalPreheader->getTerminator(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1460 | |
| 1461 | // It would have been better to make `PreLoop' and `PostLoop' |
| 1462 | // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy |
| 1463 | // constructor. |
| 1464 | ClonedLoop PreLoop, PostLoop; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1465 | bool NeedsPreLoop = |
| 1466 | Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue(); |
| 1467 | bool NeedsPostLoop = |
| 1468 | Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue(); |
| 1469 | |
| 1470 | Value *ExitPreLoopAt = nullptr; |
| 1471 | Value *ExitMainLoopAt = nullptr; |
| 1472 | const SCEVConstant *MinusOneS = |
| 1473 | cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */)); |
| 1474 | |
| 1475 | if (NeedsPreLoop) { |
| 1476 | const SCEV *ExitPreLoopAtSCEV = nullptr; |
| 1477 | |
| 1478 | if (Increasing) |
| 1479 | ExitPreLoopAtSCEV = *SR.LowLimit; |
Max Kazantsev | 78a5435 | 2019-01-15 10:01:46 +0000 | [diff] [blame^] | 1480 | else if (cannotBeMinInLoop(*SR.HighLimit, &OriginalLoop, SE, |
| 1481 | IsSignedPredicate)) |
| 1482 | ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1483 | else { |
Max Kazantsev | 78a5435 | 2019-01-15 10:01:46 +0000 | [diff] [blame^] | 1484 | LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing " |
| 1485 | << "preloop exit limit. HighLimit = " |
| 1486 | << *(*SR.HighLimit) << "\n"); |
| 1487 | return false; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1488 | } |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 1489 | |
Max Kazantsev | b1b8aff | 2017-11-16 06:06:27 +0000 | [diff] [blame] | 1490 | if (!isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt, SE)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1491 | LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the" |
| 1492 | << " preloop exit limit " << *ExitPreLoopAtSCEV |
| 1493 | << " at block " << InsertPt->getParent()->getName() |
| 1494 | << "\n"); |
Max Kazantsev | b1b8aff | 2017-11-16 06:06:27 +0000 | [diff] [blame] | 1495 | return false; |
| 1496 | } |
| 1497 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1498 | ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt); |
| 1499 | ExitPreLoopAt->setName("exit.preloop.at"); |
| 1500 | } |
| 1501 | |
| 1502 | if (NeedsPostLoop) { |
| 1503 | const SCEV *ExitMainLoopAtSCEV = nullptr; |
| 1504 | |
| 1505 | if (Increasing) |
| 1506 | ExitMainLoopAtSCEV = *SR.HighLimit; |
Max Kazantsev | 78a5435 | 2019-01-15 10:01:46 +0000 | [diff] [blame^] | 1507 | else if (cannotBeMinInLoop(*SR.LowLimit, &OriginalLoop, SE, |
| 1508 | IsSignedPredicate)) |
| 1509 | ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1510 | else { |
Max Kazantsev | 78a5435 | 2019-01-15 10:01:46 +0000 | [diff] [blame^] | 1511 | LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing " |
| 1512 | << "mainloop exit limit. LowLimit = " |
| 1513 | << *(*SR.LowLimit) << "\n"); |
| 1514 | return false; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1515 | } |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 1516 | |
Max Kazantsev | b1b8aff | 2017-11-16 06:06:27 +0000 | [diff] [blame] | 1517 | if (!isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt, SE)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1518 | LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the" |
| 1519 | << " main loop exit limit " << *ExitMainLoopAtSCEV |
| 1520 | << " at block " << InsertPt->getParent()->getName() |
| 1521 | << "\n"); |
Max Kazantsev | b1b8aff | 2017-11-16 06:06:27 +0000 | [diff] [blame] | 1522 | return false; |
| 1523 | } |
| 1524 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1525 | ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt); |
| 1526 | ExitMainLoopAt->setName("exit.mainloop.at"); |
| 1527 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1528 | |
| 1529 | // We clone these ahead of time so that we don't have to deal with changing |
| 1530 | // and temporarily invalid IR as we transform the loops. |
| 1531 | if (NeedsPreLoop) |
| 1532 | cloneLoop(PreLoop, "preloop"); |
| 1533 | if (NeedsPostLoop) |
| 1534 | cloneLoop(PostLoop, "postloop"); |
| 1535 | |
| 1536 | RewrittenRangeInfo PreLoopRRI; |
| 1537 | |
| 1538 | if (NeedsPreLoop) { |
| 1539 | Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header, |
| 1540 | PreLoop.Structure.Header); |
| 1541 | |
| 1542 | MainLoopPreheader = |
| 1543 | createPreheader(MainLoopStructure, Preheader, "mainloop"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1544 | PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader, |
| 1545 | ExitPreLoopAt, MainLoopPreheader); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1546 | rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader, |
| 1547 | PreLoopRRI); |
| 1548 | } |
| 1549 | |
| 1550 | BasicBlock *PostLoopPreheader = nullptr; |
| 1551 | RewrittenRangeInfo PostLoopRRI; |
| 1552 | |
| 1553 | if (NeedsPostLoop) { |
| 1554 | PostLoopPreheader = |
| 1555 | createPreheader(PostLoop.Structure, Preheader, "postloop"); |
| 1556 | PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader, |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1557 | ExitMainLoopAt, PostLoopPreheader); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1558 | rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader, |
| 1559 | PostLoopRRI); |
| 1560 | } |
| 1561 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1562 | BasicBlock *NewMainLoopPreheader = |
| 1563 | MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr; |
| 1564 | BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit, |
| 1565 | PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit, |
| 1566 | PostLoopRRI.ExitSelector, NewMainLoopPreheader}; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1567 | |
| 1568 | // Some of the above may be nullptr, filter them out before passing to |
| 1569 | // addToParentLoopIfNeeded. |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1570 | auto NewBlocksEnd = |
| 1571 | std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1572 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1573 | addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1574 | |
Sanjoy Das | f45e03e | 2016-08-02 19:31:54 +0000 | [diff] [blame] | 1575 | DT.recalculate(F); |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1576 | |
Anna Thomas | 7218032 | 2017-06-06 14:54:01 +0000 | [diff] [blame] | 1577 | // We need to first add all the pre and post loop blocks into the loop |
| 1578 | // structures (as part of createClonedLoopStructure), and then update the |
| 1579 | // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating |
| 1580 | // LI when LoopSimplifyForm is generated. |
| 1581 | Loop *PreL = nullptr, *PostL = nullptr; |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1582 | if (!PreLoop.Blocks.empty()) { |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 1583 | PreL = createClonedLoopStructure(&OriginalLoop, |
| 1584 | OriginalLoop.getParentLoop(), PreLoop.Map, |
| 1585 | /* IsSubLoop */ false); |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1586 | } |
| 1587 | |
| 1588 | if (!PostLoop.Blocks.empty()) { |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 1589 | PostL = |
| 1590 | createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(), |
| 1591 | PostLoop.Map, /* IsSubLoop */ false); |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1592 | } |
| 1593 | |
Anna Thomas | 7218032 | 2017-06-06 14:54:01 +0000 | [diff] [blame] | 1594 | // This function canonicalizes the loop into Loop-Simplify and LCSSA forms. |
| 1595 | auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) { |
| 1596 | formLCSSARecursively(*L, DT, &LI, &SE); |
| 1597 | simplifyLoop(L, &DT, &LI, &SE, nullptr, true); |
| 1598 | // Pre/post loops are slow paths, we do not need to perform any loop |
| 1599 | // optimizations on them. |
| 1600 | if (!IsOriginalLoop) |
| 1601 | DisableAllLoopOptsOnLoop(*L); |
| 1602 | }; |
| 1603 | if (PreL) |
| 1604 | CanonicalizeLoop(PreL, false); |
| 1605 | if (PostL) |
| 1606 | CanonicalizeLoop(PostL, false); |
| 1607 | CanonicalizeLoop(&OriginalLoop, true); |
Sanjoy Das | f45e03e | 2016-08-02 19:31:54 +0000 | [diff] [blame] | 1608 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1609 | return true; |
| 1610 | } |
| 1611 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1612 | /// Computes and returns a range of values for the induction variable (IndVar) |
| 1613 | /// in which the range check can be safely elided. If it cannot compute such a |
| 1614 | /// range, returns None. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1615 | Optional<InductiveRangeCheck::Range> |
Sanjoy Das | 5977673 | 2016-05-21 02:31:51 +0000 | [diff] [blame] | 1616 | InductiveRangeCheck::computeSafeIterationSpace( |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1617 | ScalarEvolution &SE, const SCEVAddRecExpr *IndVar, |
| 1618 | bool IsLatchSigned) const { |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1619 | // IndVar is of the form "A + B * I" (where "I" is the canonical induction |
| 1620 | // variable, that may or may not exist as a real llvm::Value in the loop) and |
| 1621 | // this inductive range check is a range check on the "C + D * I" ("C" is |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 1622 | // getBegin() and "D" is getStep()). We rewrite the value being range |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1623 | // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA". |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1624 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1625 | // The actual inequalities we solve are of the form |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1626 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1627 | // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1) |
| 1628 | // |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1629 | // Here L stands for upper limit of the safe iteration space. |
| 1630 | // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid |
| 1631 | // overflows when calculating (0 - M) and (L - M) we, depending on type of |
| 1632 | // IV's iteration space, limit the calculations by borders of the iteration |
| 1633 | // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0. |
| 1634 | // If we figured out that "anything greater than (-M) is safe", we strengthen |
| 1635 | // this to "everything greater than 0 is safe", assuming that values between |
| 1636 | // -M and 0 just do not exist in unsigned iteration space, and we don't want |
| 1637 | // to deal with overflown values. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1638 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1639 | if (!IndVar->isAffine()) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1640 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1641 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1642 | const SCEV *A = IndVar->getStart(); |
| 1643 | const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE)); |
| 1644 | if (!B) |
| 1645 | return None; |
Max Kazantsev | e4c220e | 2017-08-01 06:49:29 +0000 | [diff] [blame] | 1646 | assert(!B->isZero() && "Recurrence with zero step?"); |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1647 | |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 1648 | const SCEV *C = getBegin(); |
| 1649 | const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep()); |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1650 | if (D != B) |
| 1651 | return None; |
| 1652 | |
Max Kazantsev | 9505470 | 2017-08-04 07:41:24 +0000 | [diff] [blame] | 1653 | assert(!D->getValue()->isZero() && "Recurrence with zero step?"); |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1654 | unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth(); |
| 1655 | const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth)); |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1656 | |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1657 | // Subtract Y from X so that it does not go through border of the IV |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1658 | // iteration space. Mathematically, it is equivalent to: |
| 1659 | // |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1660 | // ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1] |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1661 | // |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1662 | // In [1], 'X - Y' is a mathematical subtraction (result is not bounded to |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1663 | // any width of bit grid). But after we take min/max, the result is |
| 1664 | // guaranteed to be within [INT_MIN, INT_MAX]. |
| 1665 | // |
| 1666 | // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min |
| 1667 | // values, depending on type of latch condition that defines IV iteration |
| 1668 | // space. |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1669 | auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) { |
Max Kazantsev | c0b268f | 2018-05-19 13:06:37 +0000 | [diff] [blame] | 1670 | // FIXME: The current implementation assumes that X is in [0, SINT_MAX]. |
| 1671 | // This is required to ensure that SINT_MAX - X does not overflow signed and |
| 1672 | // that X - Y does not overflow unsigned if Y is negative. Can we lift this |
| 1673 | // restriction and make it work for negative X either? |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1674 | if (IsLatchSigned) { |
| 1675 | // X is a number from signed range, Y is interpreted as signed. |
| 1676 | // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only |
| 1677 | // thing we should care about is that we didn't cross SINT_MAX. |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1678 | // So, if Y is positive, we subtract Y safely. |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1679 | // Rule 1: Y > 0 ---> Y. |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1680 | // If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely. |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1681 | // Rule 2: Y >=s (X - SINT_MAX) ---> Y. |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1682 | // If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX). |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1683 | // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX). |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1684 | // It gives us smax(Y, X - SINT_MAX) to subtract in all cases. |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1685 | const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax); |
Max Kazantsev | 716e647 | 2017-11-23 06:14:39 +0000 | [diff] [blame] | 1686 | return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax), |
| 1687 | SCEV::FlagNSW); |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1688 | } else |
| 1689 | // X is a number from unsigned range, Y is interpreted as signed. |
| 1690 | // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only |
| 1691 | // thing we should care about is that we didn't cross zero. |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1692 | // So, if Y is negative, we subtract Y safely. |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1693 | // Rule 1: Y <s 0 ---> Y. |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1694 | // If 0 <= Y <= X, we subtract Y safely. |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1695 | // Rule 2: Y <=s X ---> Y. |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1696 | // If 0 <= X < Y, we should stop at 0 and can only subtract X. |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1697 | // Rule 3: Y >s X ---> X. |
Max Kazantsev | b57ca09 | 2018-02-12 05:16:28 +0000 | [diff] [blame] | 1698 | // It gives us smin(X, Y) to subtract in all cases. |
Max Kazantsev | 716e647 | 2017-11-23 06:14:39 +0000 | [diff] [blame] | 1699 | return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW); |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1700 | }; |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1701 | const SCEV *M = SE.getMinusSCEV(C, A); |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1702 | const SCEV *Zero = SE.getZero(M->getType()); |
Max Kazantsev | c0b268f | 2018-05-19 13:06:37 +0000 | [diff] [blame] | 1703 | |
| 1704 | // This function returns SCEV equal to 1 if X is non-negative 0 otherwise. |
| 1705 | auto SCEVCheckNonNegative = [&](const SCEV *X) { |
| 1706 | const Loop *L = IndVar->getLoop(); |
| 1707 | const SCEV *One = SE.getOne(X->getType()); |
| 1708 | // Can we trivially prove that X is a non-negative or negative value? |
| 1709 | if (isKnownNonNegativeInLoop(X, L, SE)) |
| 1710 | return One; |
| 1711 | else if (isKnownNegativeInLoop(X, L, SE)) |
| 1712 | return Zero; |
| 1713 | // If not, we will have to figure it out during the execution. |
| 1714 | // Function smax(smin(X, 0), -1) + 1 equals to 1 if X >= 0 and 0 if X < 0. |
| 1715 | const SCEV *NegOne = SE.getNegativeSCEV(One); |
| 1716 | return SE.getAddExpr(SE.getSMaxExpr(SE.getSMinExpr(X, Zero), NegOne), One); |
| 1717 | }; |
| 1718 | // FIXME: Current implementation of ClampedSubtract implicitly assumes that |
| 1719 | // X is non-negative (in sense of a signed value). We need to re-implement |
| 1720 | // this function in a way that it will correctly handle negative X as well. |
| 1721 | // We use it twice: for X = 0 everything is fine, but for X = getEnd() we can |
| 1722 | // end up with a negative X and produce wrong results. So currently we ensure |
| 1723 | // that if getEnd() is negative then both ends of the safe range are zero. |
| 1724 | // Note that this may pessimize elimination of unsigned range checks against |
| 1725 | // negative values. |
| 1726 | const SCEV *REnd = getEnd(); |
| 1727 | const SCEV *EndIsNonNegative = SCEVCheckNonNegative(REnd); |
| 1728 | |
| 1729 | const SCEV *Begin = SE.getMulExpr(ClampedSubtract(Zero, M), EndIsNonNegative); |
| 1730 | const SCEV *End = SE.getMulExpr(ClampedSubtract(REnd, M), EndIsNonNegative); |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 1731 | return InductiveRangeCheck::Range(Begin, End); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1732 | } |
| 1733 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1734 | static Optional<InductiveRangeCheck::Range> |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 1735 | IntersectSignedRange(ScalarEvolution &SE, |
| 1736 | const Optional<InductiveRangeCheck::Range> &R1, |
| 1737 | const InductiveRangeCheck::Range &R2) { |
Max Kazantsev | 4332a94 | 2017-10-25 06:10:02 +0000 | [diff] [blame] | 1738 | if (R2.isEmpty(SE, /* IsSigned */ true)) |
Max Kazantsev | 25d8655 | 2017-10-11 06:53:07 +0000 | [diff] [blame] | 1739 | return None; |
Max Kazantsev | 3612d4b | 2017-10-19 05:33:28 +0000 | [diff] [blame] | 1740 | if (!R1.hasValue()) |
| 1741 | return R2; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1742 | auto &R1Value = R1.getValue(); |
Max Kazantsev | 3612d4b | 2017-10-19 05:33:28 +0000 | [diff] [blame] | 1743 | // We never return empty ranges from this function, and R1 is supposed to be |
| 1744 | // a result of intersection. Thus, R1 is never empty. |
Max Kazantsev | 4332a94 | 2017-10-25 06:10:02 +0000 | [diff] [blame] | 1745 | assert(!R1Value.isEmpty(SE, /* IsSigned */ true) && |
| 1746 | "We should never have empty R1!"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1747 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1748 | // TODO: we could widen the smaller range and have this work; but for now we |
| 1749 | // bail out to keep things simple. |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 1750 | if (R1Value.getType() != R2.getType()) |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1751 | return None; |
| 1752 | |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 1753 | const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin()); |
| 1754 | const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd()); |
| 1755 | |
Max Kazantsev | 25d8655 | 2017-10-11 06:53:07 +0000 | [diff] [blame] | 1756 | // If the resulting range is empty, just return None. |
| 1757 | auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd); |
Max Kazantsev | 4332a94 | 2017-10-25 06:10:02 +0000 | [diff] [blame] | 1758 | if (Ret.isEmpty(SE, /* IsSigned */ true)) |
Max Kazantsev | 25d8655 | 2017-10-11 06:53:07 +0000 | [diff] [blame] | 1759 | return None; |
| 1760 | return Ret; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1761 | } |
| 1762 | |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 1763 | static Optional<InductiveRangeCheck::Range> |
| 1764 | IntersectUnsignedRange(ScalarEvolution &SE, |
| 1765 | const Optional<InductiveRangeCheck::Range> &R1, |
| 1766 | const InductiveRangeCheck::Range &R2) { |
| 1767 | if (R2.isEmpty(SE, /* IsSigned */ false)) |
| 1768 | return None; |
| 1769 | if (!R1.hasValue()) |
| 1770 | return R2; |
| 1771 | auto &R1Value = R1.getValue(); |
| 1772 | // We never return empty ranges from this function, and R1 is supposed to be |
| 1773 | // a result of intersection. Thus, R1 is never empty. |
| 1774 | assert(!R1Value.isEmpty(SE, /* IsSigned */ false) && |
| 1775 | "We should never have empty R1!"); |
| 1776 | |
| 1777 | // TODO: we could widen the smaller range and have this work; but for now we |
| 1778 | // bail out to keep things simple. |
| 1779 | if (R1Value.getType() != R2.getType()) |
| 1780 | return None; |
| 1781 | |
| 1782 | const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin()); |
| 1783 | const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd()); |
| 1784 | |
| 1785 | // If the resulting range is empty, just return None. |
| 1786 | auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd); |
| 1787 | if (Ret.isEmpty(SE, /* IsSigned */ false)) |
| 1788 | return None; |
| 1789 | return Ret; |
| 1790 | } |
| 1791 | |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 1792 | PreservedAnalyses IRCEPass::run(Loop &L, LoopAnalysisManager &AM, |
| 1793 | LoopStandardAnalysisResults &AR, |
| 1794 | LPMUpdater &U) { |
| 1795 | Function *F = L.getHeader()->getParent(); |
| 1796 | const auto &FAM = |
| 1797 | AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); |
| 1798 | auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F); |
| 1799 | InductiveRangeCheckElimination IRCE(AR.SE, BPI, AR.DT, AR.LI); |
| 1800 | auto LPMAddNewLoop = [&U](Loop *NL, bool IsSubloop) { |
| 1801 | if (!IsSubloop) |
| 1802 | U.addSiblingLoops(NL); |
| 1803 | }; |
| 1804 | bool Changed = IRCE.run(&L, LPMAddNewLoop); |
| 1805 | if (!Changed) |
| 1806 | return PreservedAnalyses::all(); |
| 1807 | |
| 1808 | return getLoopPassPreservedAnalyses(); |
| 1809 | } |
| 1810 | |
| 1811 | bool IRCELegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) { |
Andrew Kaylor | 50271f7 | 2016-05-03 22:32:30 +0000 | [diff] [blame] | 1812 | if (skipLoop(L)) |
| 1813 | return false; |
| 1814 | |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 1815 | ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
| 1816 | BranchProbabilityInfo &BPI = |
| 1817 | getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); |
| 1818 | auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 1819 | auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
| 1820 | InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI); |
| 1821 | auto LPMAddNewLoop = [&LPM](Loop *NL, bool /* IsSubLoop */) { |
| 1822 | LPM.addLoop(*NL); |
| 1823 | }; |
| 1824 | return IRCE.run(L, LPMAddNewLoop); |
| 1825 | } |
| 1826 | |
| 1827 | bool InductiveRangeCheckElimination::run( |
| 1828 | Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1829 | if (L->getBlocks().size() >= LoopSizeCutoff) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1830 | LLVM_DEBUG(dbgs() << "irce: giving up constraining loop, too large\n"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1831 | return false; |
| 1832 | } |
| 1833 | |
| 1834 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 1835 | if (!Preheader) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1836 | LLVM_DEBUG(dbgs() << "irce: loop has no preheader, leaving\n"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1837 | return false; |
| 1838 | } |
| 1839 | |
| 1840 | LLVMContext &Context = Preheader->getContext(); |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1841 | SmallVector<InductiveRangeCheck, 16> RangeChecks; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1842 | |
| 1843 | for (auto BBI : L->getBlocks()) |
| 1844 | if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator())) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 1845 | InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI, |
| 1846 | RangeChecks); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1847 | |
| 1848 | if (RangeChecks.empty()) |
| 1849 | return false; |
| 1850 | |
Sanjoy Das | 9c1bfae | 2015-03-17 01:40:22 +0000 | [diff] [blame] | 1851 | auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) { |
| 1852 | OS << "irce: looking at loop "; L->print(OS); |
| 1853 | OS << "irce: loop has " << RangeChecks.size() |
| 1854 | << " inductive range checks: \n"; |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1855 | for (InductiveRangeCheck &IRC : RangeChecks) |
| 1856 | IRC.print(OS); |
Sanjoy Das | 9c1bfae | 2015-03-17 01:40:22 +0000 | [diff] [blame] | 1857 | }; |
| 1858 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1859 | LLVM_DEBUG(PrintRecognizedRangeChecks(dbgs())); |
Sanjoy Das | 9c1bfae | 2015-03-17 01:40:22 +0000 | [diff] [blame] | 1860 | |
| 1861 | if (PrintRangeChecks) |
| 1862 | PrintRecognizedRangeChecks(errs()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1863 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1864 | const char *FailureReason = nullptr; |
| 1865 | Optional<LoopStructure> MaybeLoopStructure = |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 1866 | LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1867 | if (!MaybeLoopStructure.hasValue()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1868 | LLVM_DEBUG(dbgs() << "irce: could not parse loop structure: " |
| 1869 | << FailureReason << "\n";); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1870 | return false; |
| 1871 | } |
| 1872 | LoopStructure LS = MaybeLoopStructure.getValue(); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1873 | const SCEVAddRecExpr *IndVar = |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 1874 | cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep))); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1875 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1876 | Optional<InductiveRangeCheck::Range> SafeIterRange; |
| 1877 | Instruction *ExprInsertPt = Preheader->getTerminator(); |
| 1878 | |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1879 | SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate; |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 1880 | // Basing on the type of latch predicate, we interpret the IV iteration range |
| 1881 | // as signed or unsigned range. We use different min/max functions (signed or |
| 1882 | // unsigned) when intersecting this range with safe iteration ranges implied |
| 1883 | // by range checks. |
| 1884 | auto IntersectRange = |
| 1885 | LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1886 | |
| 1887 | IRBuilder<> B(ExprInsertPt); |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1888 | for (InductiveRangeCheck &IRC : RangeChecks) { |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1889 | auto Result = IRC.computeSafeIterationSpace(SE, IndVar, |
| 1890 | LS.IsSignedPredicate); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1891 | if (Result.hasValue()) { |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1892 | auto MaybeSafeIterRange = |
Sanjoy Das | 5977673 | 2016-05-21 02:31:51 +0000 | [diff] [blame] | 1893 | IntersectRange(SE, SafeIterRange, Result.getValue()); |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1894 | if (MaybeSafeIterRange.hasValue()) { |
Max Kazantsev | 4332a94 | 2017-10-25 06:10:02 +0000 | [diff] [blame] | 1895 | assert( |
| 1896 | !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) && |
| 1897 | "We should never return empty ranges!"); |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1898 | RangeChecksToEliminate.push_back(IRC); |
| 1899 | SafeIterRange = MaybeSafeIterRange.getValue(); |
| 1900 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1901 | } |
| 1902 | } |
| 1903 | |
| 1904 | if (!SafeIterRange.hasValue()) |
| 1905 | return false; |
| 1906 | |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 1907 | LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT, |
| 1908 | SafeIterRange.getValue()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1909 | bool Changed = LC.run(); |
| 1910 | |
| 1911 | if (Changed) { |
| 1912 | auto PrintConstrainedLoopInfo = [L]() { |
| 1913 | dbgs() << "irce: in function "; |
| 1914 | dbgs() << L->getHeader()->getParent()->getName() << ": "; |
| 1915 | dbgs() << "constrained "; |
| 1916 | L->print(dbgs()); |
| 1917 | }; |
| 1918 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1919 | LLVM_DEBUG(PrintConstrainedLoopInfo()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1920 | |
| 1921 | if (PrintChangedLoops) |
| 1922 | PrintConstrainedLoopInfo(); |
| 1923 | |
| 1924 | // Optimize away the now-redundant range checks. |
| 1925 | |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1926 | for (InductiveRangeCheck &IRC : RangeChecksToEliminate) { |
| 1927 | ConstantInt *FoldedRangeCheck = IRC.getPassingDirection() |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1928 | ? ConstantInt::getTrue(Context) |
| 1929 | : ConstantInt::getFalse(Context); |
Sanjoy Das | aa83c47 | 2016-05-23 22:16:45 +0000 | [diff] [blame] | 1930 | IRC.getCheckUse()->set(FoldedRangeCheck); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1931 | } |
| 1932 | } |
| 1933 | |
| 1934 | return Changed; |
| 1935 | } |
| 1936 | |
| 1937 | Pass *llvm::createInductiveRangeCheckEliminationPass() { |
Fedor Sergeev | 194a407 | 2018-03-15 11:01:19 +0000 | [diff] [blame] | 1938 | return new IRCELegacyPass(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1939 | } |