Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 1 | //===- GuardWidening.cpp - ---- Guard widening ----------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements the guard widening pass. The semantics of the |
| 11 | // @llvm.experimental.guard intrinsic lets LLVM transform it so that it fails |
| 12 | // more often that it did before the transform. This optimization is called |
| 13 | // "widening" and can be used hoist and common runtime checks in situations like |
| 14 | // these: |
| 15 | // |
| 16 | // %cmp0 = 7 u< Length |
| 17 | // call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ] |
| 18 | // call @unknown_side_effects() |
| 19 | // %cmp1 = 9 u< Length |
| 20 | // call @llvm.experimental.guard(i1 %cmp1) [ "deopt"(...) ] |
| 21 | // ... |
| 22 | // |
| 23 | // => |
| 24 | // |
| 25 | // %cmp0 = 9 u< Length |
| 26 | // call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ] |
| 27 | // call @unknown_side_effects() |
| 28 | // ... |
| 29 | // |
| 30 | // If %cmp0 is false, @llvm.experimental.guard will "deoptimize" back to a |
| 31 | // generic implementation of the same function, which will have the correct |
| 32 | // semantics from that point onward. It is always _legal_ to deoptimize (so |
| 33 | // replacing %cmp0 with false is "correct"), though it may not always be |
| 34 | // profitable to do so. |
| 35 | // |
| 36 | // NB! This pass is a work in progress. It hasn't been tuned to be "production |
| 37 | // ready" yet. It is known to have quadriatic running time and will not scale |
| 38 | // to large numbers of guards |
| 39 | // |
| 40 | //===----------------------------------------------------------------------===// |
| 41 | |
| 42 | #include "llvm/Transforms/Scalar/GuardWidening.h" |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 43 | #include <functional> |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 44 | #include "llvm/ADT/DenseMap.h" |
| 45 | #include "llvm/ADT/DepthFirstIterator.h" |
| 46 | #include "llvm/Analysis/LoopInfo.h" |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 47 | #include "llvm/Analysis/LoopPass.h" |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 48 | #include "llvm/Analysis/PostDominators.h" |
| 49 | #include "llvm/Analysis/ValueTracking.h" |
Peter Collingbourne | ecdd58f | 2016-10-21 19:59:26 +0000 | [diff] [blame] | 50 | #include "llvm/IR/ConstantRange.h" |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 51 | #include "llvm/IR/Dominators.h" |
| 52 | #include "llvm/IR/IntrinsicInst.h" |
| 53 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 54 | #include "llvm/Pass.h" |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 55 | #include "llvm/Support/Debug.h" |
Craig Topper | b45eabc | 2017-04-26 16:39:58 +0000 | [diff] [blame] | 56 | #include "llvm/Support/KnownBits.h" |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 57 | #include "llvm/Transforms/Scalar.h" |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 58 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 59 | |
| 60 | using namespace llvm; |
| 61 | |
| 62 | #define DEBUG_TYPE "guard-widening" |
| 63 | |
| 64 | namespace { |
| 65 | |
| 66 | class GuardWideningImpl { |
| 67 | DominatorTree &DT; |
Philip Reames | 502d4481 | 2018-04-27 23:15:56 +0000 | [diff] [blame] | 68 | PostDominatorTree *PDT; |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 69 | LoopInfo &LI; |
| 70 | |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 71 | /// Together, these describe the region of interest. This might be all of |
| 72 | /// the blocks within a function, or only a given loop's blocks and preheader. |
| 73 | DomTreeNode *Root; |
| 74 | std::function<bool(BasicBlock*)> BlockFilter; |
| 75 | |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 76 | /// The set of guards whose conditions have been widened into dominating |
| 77 | /// guards. |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 78 | SmallVector<Instruction *, 16> EliminatedGuards; |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 79 | |
| 80 | /// The set of guards which have been widened to include conditions to other |
| 81 | /// guards. |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 82 | DenseSet<Instruction *> WidenedGuards; |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 83 | |
| 84 | /// Try to eliminate guard \p Guard by widening it into an earlier dominating |
| 85 | /// guard. \p DFSI is the DFS iterator on the dominator tree that is |
| 86 | /// currently visiting the block containing \p Guard, and \p GuardsPerBlock |
| 87 | /// maps BasicBlocks to the set of guards seen in that block. |
| 88 | bool eliminateGuardViaWidening( |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 89 | Instruction *Guard, const df_iterator<DomTreeNode *> &DFSI, |
| 90 | const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> & |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 91 | GuardsPerBlock); |
| 92 | |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 93 | // Get the condition from \p GuardInst. |
| 94 | Value *getGuardCondition(Instruction *GuardInst); |
| 95 | |
| 96 | // Set the condition for \p GuardInst. |
| 97 | void setGuardCondition(Instruction *GuardInst, Value *NewCond); |
| 98 | |
| 99 | // Whether or not the particular instruction is a guard. |
| 100 | bool isGuard(const Instruction *I); |
| 101 | |
| 102 | // Eliminates the guard instruction properly. |
| 103 | void eliminateGuard(Instruction *GuardInst); |
| 104 | |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 105 | /// Used to keep track of which widening potential is more effective. |
| 106 | enum WideningScore { |
| 107 | /// Don't widen. |
| 108 | WS_IllegalOrNegative, |
| 109 | |
| 110 | /// Widening is performance neutral as far as the cycles spent in check |
| 111 | /// conditions goes (but can still help, e.g., code layout, having less |
| 112 | /// deopt state). |
| 113 | WS_Neutral, |
| 114 | |
| 115 | /// Widening is profitable. |
| 116 | WS_Positive, |
| 117 | |
| 118 | /// Widening is very profitable. Not significantly different from \c |
| 119 | /// WS_Positive, except by the order. |
| 120 | WS_VeryPositive |
| 121 | }; |
| 122 | |
| 123 | static StringRef scoreTypeToString(WideningScore WS); |
| 124 | |
| 125 | /// Compute the score for widening the condition in \p DominatedGuard |
| 126 | /// (contained in \p DominatedGuardLoop) into \p DominatingGuard (contained in |
| 127 | /// \p DominatingGuardLoop). |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 128 | WideningScore computeWideningScore(Instruction *DominatedGuard, |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 129 | Loop *DominatedGuardLoop, |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 130 | Instruction *DominatingGuard, |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 131 | Loop *DominatingGuardLoop); |
| 132 | |
| 133 | /// Helper to check if \p V can be hoisted to \p InsertPos. |
| 134 | bool isAvailableAt(Value *V, Instruction *InsertPos) { |
| 135 | SmallPtrSet<Instruction *, 8> Visited; |
| 136 | return isAvailableAt(V, InsertPos, Visited); |
| 137 | } |
| 138 | |
| 139 | bool isAvailableAt(Value *V, Instruction *InsertPos, |
| 140 | SmallPtrSetImpl<Instruction *> &Visited); |
| 141 | |
| 142 | /// Helper to hoist \p V to \p InsertPos. Guaranteed to succeed if \c |
| 143 | /// isAvailableAt returned true. |
| 144 | void makeAvailableAt(Value *V, Instruction *InsertPos); |
| 145 | |
| 146 | /// Common helper used by \c widenGuard and \c isWideningCondProfitable. Try |
| 147 | /// to generate an expression computing the logical AND of \p Cond0 and \p |
| 148 | /// Cond1. Return true if the expression computing the AND is only as |
| 149 | /// expensive as computing one of the two. If \p InsertPt is true then |
| 150 | /// actually generate the resulting expression, make it available at \p |
| 151 | /// InsertPt and return it in \p Result (else no change to the IR is made). |
| 152 | bool widenCondCommon(Value *Cond0, Value *Cond1, Instruction *InsertPt, |
| 153 | Value *&Result); |
| 154 | |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 155 | /// Represents a range check of the form \c Base + \c Offset u< \c Length, |
| 156 | /// with the constraint that \c Length is not negative. \c CheckInst is the |
| 157 | /// pre-existing instruction in the IR that computes the result of this range |
| 158 | /// check. |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 159 | class RangeCheck { |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 160 | Value *Base; |
| 161 | ConstantInt *Offset; |
| 162 | Value *Length; |
| 163 | ICmpInst *CheckInst; |
| 164 | |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 165 | public: |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 166 | explicit RangeCheck(Value *Base, ConstantInt *Offset, Value *Length, |
| 167 | ICmpInst *CheckInst) |
| 168 | : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {} |
| 169 | |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 170 | void setBase(Value *NewBase) { Base = NewBase; } |
| 171 | void setOffset(ConstantInt *NewOffset) { Offset = NewOffset; } |
| 172 | |
| 173 | Value *getBase() const { return Base; } |
| 174 | ConstantInt *getOffset() const { return Offset; } |
| 175 | const APInt &getOffsetValue() const { return getOffset()->getValue(); } |
| 176 | Value *getLength() const { return Length; }; |
| 177 | ICmpInst *getCheckInst() const { return CheckInst; } |
| 178 | |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 179 | void print(raw_ostream &OS, bool PrintTypes = false) { |
| 180 | OS << "Base: "; |
| 181 | Base->printAsOperand(OS, PrintTypes); |
| 182 | OS << " Offset: "; |
| 183 | Offset->printAsOperand(OS, PrintTypes); |
| 184 | OS << " Length: "; |
| 185 | Length->printAsOperand(OS, PrintTypes); |
| 186 | } |
| 187 | |
| 188 | LLVM_DUMP_METHOD void dump() { |
| 189 | print(dbgs()); |
| 190 | dbgs() << "\n"; |
| 191 | } |
| 192 | }; |
| 193 | |
| 194 | /// Parse \p CheckCond into a conjunction (logical-and) of range checks; and |
| 195 | /// append them to \p Checks. Returns true on success, may clobber \c Checks |
| 196 | /// on failure. |
| 197 | bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks) { |
| 198 | SmallPtrSet<Value *, 8> Visited; |
| 199 | return parseRangeChecks(CheckCond, Checks, Visited); |
| 200 | } |
| 201 | |
| 202 | bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks, |
| 203 | SmallPtrSetImpl<Value *> &Visited); |
| 204 | |
| 205 | /// Combine the checks in \p Checks into a smaller set of checks and append |
| 206 | /// them into \p CombinedChecks. Return true on success (i.e. all of checks |
| 207 | /// in \p Checks were combined into \p CombinedChecks). Clobbers \p Checks |
| 208 | /// and \p CombinedChecks on success and on failure. |
| 209 | bool combineRangeChecks(SmallVectorImpl<RangeCheck> &Checks, |
| 210 | SmallVectorImpl<RangeCheck> &CombinedChecks); |
| 211 | |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 212 | /// Can we compute the logical AND of \p Cond0 and \p Cond1 for the price of |
| 213 | /// computing only one of the two expressions? |
| 214 | bool isWideningCondProfitable(Value *Cond0, Value *Cond1) { |
| 215 | Value *ResultUnused; |
| 216 | return widenCondCommon(Cond0, Cond1, /*InsertPt=*/nullptr, ResultUnused); |
| 217 | } |
| 218 | |
| 219 | /// Widen \p ToWiden to fail if \p NewCondition is false (in addition to |
| 220 | /// whatever it is already checking). |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 221 | void widenGuard(Instruction *ToWiden, Value *NewCondition) { |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 222 | Value *Result; |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 223 | widenCondCommon(ToWiden->getOperand(0), NewCondition, ToWiden, Result); |
| 224 | setGuardCondition(ToWiden, Result); |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 225 | } |
| 226 | |
| 227 | public: |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 228 | |
Philip Reames | 502d4481 | 2018-04-27 23:15:56 +0000 | [diff] [blame] | 229 | explicit GuardWideningImpl(DominatorTree &DT, PostDominatorTree *PDT, |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 230 | LoopInfo &LI, DomTreeNode *Root, |
| 231 | std::function<bool(BasicBlock*)> BlockFilter) |
| 232 | : DT(DT), PDT(PDT), LI(LI), Root(Root), BlockFilter(BlockFilter) {} |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 233 | |
| 234 | /// The entry point for this pass. |
| 235 | bool run(); |
| 236 | }; |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 237 | } |
| 238 | |
| 239 | bool GuardWideningImpl::run() { |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 240 | DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> GuardsInBlock; |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 241 | bool Changed = false; |
| 242 | |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 243 | for (auto DFI = df_begin(Root), DFE = df_end(Root); |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 244 | DFI != DFE; ++DFI) { |
| 245 | auto *BB = (*DFI)->getBlock(); |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 246 | if (!BlockFilter(BB)) |
| 247 | continue; |
| 248 | |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 249 | auto &CurrentList = GuardsInBlock[BB]; |
| 250 | |
| 251 | for (auto &I : *BB) |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 252 | if (isGuard(&I)) |
| 253 | CurrentList.push_back(cast<Instruction>(&I)); |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 254 | |
| 255 | for (auto *II : CurrentList) |
| 256 | Changed |= eliminateGuardViaWidening(II, DFI, GuardsInBlock); |
| 257 | } |
| 258 | |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 259 | assert(EliminatedGuards.empty() || Changed); |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 260 | for (auto *II : EliminatedGuards) |
| 261 | if (!WidenedGuards.count(II)) |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 262 | eliminateGuard(II); |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 263 | |
| 264 | return Changed; |
| 265 | } |
| 266 | |
| 267 | bool GuardWideningImpl::eliminateGuardViaWidening( |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 268 | Instruction *GuardInst, const df_iterator<DomTreeNode *> &DFSI, |
| 269 | const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> & |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 270 | GuardsInBlock) { |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 271 | Instruction *BestSoFar = nullptr; |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 272 | auto BestScoreSoFar = WS_IllegalOrNegative; |
| 273 | auto *GuardInstLoop = LI.getLoopFor(GuardInst->getParent()); |
| 274 | |
| 275 | // In the set of dominating guards, find the one we can merge GuardInst with |
| 276 | // for the most profit. |
| 277 | for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) { |
| 278 | auto *CurBB = DFSI.getPath(i)->getBlock(); |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 279 | if (!BlockFilter(CurBB)) |
| 280 | break; |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 281 | auto *CurLoop = LI.getLoopFor(CurBB); |
| 282 | assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!"); |
| 283 | const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second; |
| 284 | |
| 285 | auto I = GuardsInCurBB.begin(); |
| 286 | auto E = GuardsInCurBB.end(); |
| 287 | |
| 288 | #ifndef NDEBUG |
| 289 | { |
| 290 | unsigned Index = 0; |
| 291 | for (auto &I : *CurBB) { |
| 292 | if (Index == GuardsInCurBB.size()) |
| 293 | break; |
| 294 | if (GuardsInCurBB[Index] == &I) |
| 295 | Index++; |
| 296 | } |
| 297 | assert(Index == GuardsInCurBB.size() && |
| 298 | "Guards expected to be in order!"); |
| 299 | } |
| 300 | #endif |
| 301 | |
| 302 | assert((i == (e - 1)) == (GuardInst->getParent() == CurBB) && "Bad DFS?"); |
| 303 | |
| 304 | if (i == (e - 1)) { |
| 305 | // Corner case: make sure we're only looking at guards strictly dominating |
| 306 | // GuardInst when visiting GuardInst->getParent(). |
| 307 | auto NewEnd = std::find(I, E, GuardInst); |
| 308 | assert(NewEnd != E && "GuardInst not in its own block?"); |
| 309 | E = NewEnd; |
| 310 | } |
| 311 | |
| 312 | for (auto *Candidate : make_range(I, E)) { |
| 313 | auto Score = |
| 314 | computeWideningScore(GuardInst, GuardInstLoop, Candidate, CurLoop); |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 315 | LLVM_DEBUG(dbgs() << "Score between " << *getGuardCondition(GuardInst) |
| 316 | << " and " << *getGuardCondition(Candidate) << " is " |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 317 | << scoreTypeToString(Score) << "\n"); |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 318 | if (Score > BestScoreSoFar) { |
| 319 | BestScoreSoFar = Score; |
| 320 | BestSoFar = Candidate; |
| 321 | } |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | if (BestScoreSoFar == WS_IllegalOrNegative) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 326 | LLVM_DEBUG(dbgs() << "Did not eliminate guard " << *GuardInst << "\n"); |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 327 | return false; |
| 328 | } |
| 329 | |
| 330 | assert(BestSoFar != GuardInst && "Should have never visited same guard!"); |
| 331 | assert(DT.dominates(BestSoFar, GuardInst) && "Should be!"); |
| 332 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 333 | LLVM_DEBUG(dbgs() << "Widening " << *GuardInst << " into " << *BestSoFar |
| 334 | << " with score " << scoreTypeToString(BestScoreSoFar) |
| 335 | << "\n"); |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 336 | widenGuard(BestSoFar, getGuardCondition(GuardInst)); |
| 337 | setGuardCondition(GuardInst, ConstantInt::getTrue(GuardInst->getContext())); |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 338 | EliminatedGuards.push_back(GuardInst); |
| 339 | WidenedGuards.insert(BestSoFar); |
| 340 | return true; |
| 341 | } |
| 342 | |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 343 | Value *GuardWideningImpl::getGuardCondition(Instruction *GuardInst) { |
| 344 | IntrinsicInst *GI = cast<IntrinsicInst>(GuardInst); |
| 345 | assert(GI->getIntrinsicID() == Intrinsic::experimental_guard && |
| 346 | "Bad guard intrinsic?"); |
| 347 | return GI->getArgOperand(0); |
| 348 | } |
| 349 | |
| 350 | void GuardWideningImpl::setGuardCondition(Instruction *GuardInst, |
| 351 | Value *NewCond) { |
| 352 | IntrinsicInst *GI = cast<IntrinsicInst>(GuardInst); |
| 353 | assert(GI->getIntrinsicID() == Intrinsic::experimental_guard && |
| 354 | "Bad guard intrinsic?"); |
| 355 | GI->setArgOperand(0, NewCond); |
| 356 | } |
| 357 | |
| 358 | bool GuardWideningImpl::isGuard(const Instruction* I) { |
| 359 | using namespace llvm::PatternMatch; |
| 360 | return match(I, m_Intrinsic<Intrinsic::experimental_guard>()); |
| 361 | } |
| 362 | |
| 363 | void GuardWideningImpl::eliminateGuard(Instruction *GuardInst) { |
| 364 | GuardInst->eraseFromParent(); |
| 365 | } |
| 366 | |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 367 | GuardWideningImpl::WideningScore GuardWideningImpl::computeWideningScore( |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 368 | Instruction *DominatedGuard, Loop *DominatedGuardLoop, |
| 369 | Instruction *DominatingGuard, Loop *DominatingGuardLoop) { |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 370 | bool HoistingOutOfLoop = false; |
| 371 | |
| 372 | if (DominatingGuardLoop != DominatedGuardLoop) { |
Philip Reames | de5a1da | 2018-04-27 17:41:37 +0000 | [diff] [blame] | 373 | // Be conservative and don't widen into a sibling loop. TODO: If the |
| 374 | // sibling is colder, we should consider allowing this. |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 375 | if (DominatingGuardLoop && |
| 376 | !DominatingGuardLoop->contains(DominatedGuardLoop)) |
| 377 | return WS_IllegalOrNegative; |
| 378 | |
| 379 | HoistingOutOfLoop = true; |
| 380 | } |
| 381 | |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 382 | if (!isAvailableAt(getGuardCondition(DominatedGuard), DominatingGuard)) |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 383 | return WS_IllegalOrNegative; |
| 384 | |
Philip Reames | de5a1da | 2018-04-27 17:41:37 +0000 | [diff] [blame] | 385 | // If the guard was conditional executed, it may never be reached |
| 386 | // dynamically. There are two potential downsides to hoisting it out of the |
| 387 | // conditionally executed region: 1) we may spuriously deopt without need and |
| 388 | // 2) we have the extra cost of computing the guard condition in the common |
| 389 | // case. At the moment, we really only consider the second in our heuristic |
| 390 | // here. TODO: evaluate cost model for spurious deopt |
Philip Reames | 502d4481 | 2018-04-27 23:15:56 +0000 | [diff] [blame] | 391 | // NOTE: As written, this also lets us hoist right over another guard which |
| 392 | // is essentially just another spelling for control flow. |
Max Kazantsev | 3327bca | 2018-07-30 07:07:32 +0000 | [diff] [blame^] | 393 | if (isWideningCondProfitable(getGuardCondition(DominatedGuard), |
| 394 | getGuardCondition(DominatingGuard))) |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 395 | return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive; |
| 396 | |
| 397 | if (HoistingOutOfLoop) |
| 398 | return WS_Positive; |
| 399 | |
Philip Reames | 502d4481 | 2018-04-27 23:15:56 +0000 | [diff] [blame] | 400 | // Returns true if we might be hoisting above explicit control flow. Note |
| 401 | // that this completely ignores implicit control flow (guards, calls which |
| 402 | // throw, etc...). That choice appears arbitrary. |
| 403 | auto MaybeHoistingOutOfIf = [&]() { |
| 404 | auto *DominatingBlock = DominatingGuard->getParent(); |
| 405 | auto *DominatedBlock = DominatedGuard->getParent(); |
| 406 | |
| 407 | // Same Block? |
| 408 | if (DominatedBlock == DominatingBlock) |
| 409 | return false; |
| 410 | // Obvious successor (common loop header/preheader case) |
| 411 | if (DominatedBlock == DominatingBlock->getUniqueSuccessor()) |
| 412 | return false; |
| 413 | // TODO: diamond, triangle cases |
| 414 | if (!PDT) return true; |
| 415 | return !PDT->dominates(DominatedGuard->getParent(), |
| 416 | DominatingGuard->getParent()); |
| 417 | }; |
| 418 | |
| 419 | return MaybeHoistingOutOfIf() ? WS_IllegalOrNegative : WS_Neutral; |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 420 | } |
| 421 | |
| 422 | bool GuardWideningImpl::isAvailableAt(Value *V, Instruction *Loc, |
| 423 | SmallPtrSetImpl<Instruction *> &Visited) { |
| 424 | auto *Inst = dyn_cast<Instruction>(V); |
| 425 | if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst)) |
| 426 | return true; |
| 427 | |
| 428 | if (!isSafeToSpeculativelyExecute(Inst, Loc, &DT) || |
| 429 | Inst->mayReadFromMemory()) |
| 430 | return false; |
| 431 | |
| 432 | Visited.insert(Inst); |
| 433 | |
| 434 | // We only want to go _up_ the dominance chain when recursing. |
| 435 | assert(!isa<PHINode>(Loc) && |
| 436 | "PHIs should return false for isSafeToSpeculativelyExecute"); |
| 437 | assert(DT.isReachableFromEntry(Inst->getParent()) && |
| 438 | "We did a DFS from the block entry!"); |
| 439 | return all_of(Inst->operands(), |
| 440 | [&](Value *Op) { return isAvailableAt(Op, Loc, Visited); }); |
| 441 | } |
| 442 | |
| 443 | void GuardWideningImpl::makeAvailableAt(Value *V, Instruction *Loc) { |
| 444 | auto *Inst = dyn_cast<Instruction>(V); |
| 445 | if (!Inst || DT.dominates(Inst, Loc)) |
| 446 | return; |
| 447 | |
| 448 | assert(isSafeToSpeculativelyExecute(Inst, Loc, &DT) && |
| 449 | !Inst->mayReadFromMemory() && "Should've checked with isAvailableAt!"); |
| 450 | |
| 451 | for (Value *Op : Inst->operands()) |
| 452 | makeAvailableAt(Op, Loc); |
| 453 | |
| 454 | Inst->moveBefore(Loc); |
| 455 | } |
| 456 | |
| 457 | bool GuardWideningImpl::widenCondCommon(Value *Cond0, Value *Cond1, |
| 458 | Instruction *InsertPt, Value *&Result) { |
| 459 | using namespace llvm::PatternMatch; |
| 460 | |
| 461 | { |
| 462 | // L >u C0 && L >u C1 -> L >u max(C0, C1) |
| 463 | ConstantInt *RHS0, *RHS1; |
| 464 | Value *LHS; |
| 465 | ICmpInst::Predicate Pred0, Pred1; |
| 466 | if (match(Cond0, m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) && |
| 467 | match(Cond1, m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) { |
| 468 | |
Sanjoy Das | b784ed3 | 2016-05-19 03:53:17 +0000 | [diff] [blame] | 469 | ConstantRange CR0 = |
| 470 | ConstantRange::makeExactICmpRegion(Pred0, RHS0->getValue()); |
| 471 | ConstantRange CR1 = |
| 472 | ConstantRange::makeExactICmpRegion(Pred1, RHS1->getValue()); |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 473 | |
Sanjoy Das | b784ed3 | 2016-05-19 03:53:17 +0000 | [diff] [blame] | 474 | // SubsetIntersect is a subset of the actual mathematical intersection of |
Sanjay Patel | f8ee0e0 | 2016-06-19 17:20:27 +0000 | [diff] [blame] | 475 | // CR0 and CR1, while SupersetIntersect is a superset of the actual |
Sanjoy Das | b784ed3 | 2016-05-19 03:53:17 +0000 | [diff] [blame] | 476 | // mathematical intersection. If these two ConstantRanges are equal, then |
| 477 | // we know we were able to represent the actual mathematical intersection |
| 478 | // of CR0 and CR1, and can use the same to generate an icmp instruction. |
| 479 | // |
| 480 | // Given what we're doing here and the semantics of guards, it would |
| 481 | // actually be correct to just use SubsetIntersect, but that may be too |
| 482 | // aggressive in cases we care about. |
| 483 | auto SubsetIntersect = CR0.inverse().unionWith(CR1.inverse()).inverse(); |
| 484 | auto SupersetIntersect = CR0.intersectWith(CR1); |
| 485 | |
| 486 | APInt NewRHSAP; |
| 487 | CmpInst::Predicate Pred; |
| 488 | if (SubsetIntersect == SupersetIntersect && |
| 489 | SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) { |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 490 | if (InsertPt) { |
Sanjoy Das | b784ed3 | 2016-05-19 03:53:17 +0000 | [diff] [blame] | 491 | ConstantInt *NewRHS = ConstantInt::get(Cond0->getContext(), NewRHSAP); |
| 492 | Result = new ICmpInst(InsertPt, Pred, LHS, NewRHS, "wide.chk"); |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 493 | } |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 494 | return true; |
| 495 | } |
| 496 | } |
| 497 | } |
| 498 | |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 499 | { |
| 500 | SmallVector<GuardWideningImpl::RangeCheck, 4> Checks, CombinedChecks; |
| 501 | if (parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) && |
| 502 | combineRangeChecks(Checks, CombinedChecks)) { |
| 503 | if (InsertPt) { |
| 504 | Result = nullptr; |
| 505 | for (auto &RC : CombinedChecks) { |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 506 | makeAvailableAt(RC.getCheckInst(), InsertPt); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 507 | if (Result) |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 508 | Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result, "", |
| 509 | InsertPt); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 510 | else |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 511 | Result = RC.getCheckInst(); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 512 | } |
| 513 | |
| 514 | Result->setName("wide.chk"); |
| 515 | } |
| 516 | return true; |
| 517 | } |
| 518 | } |
| 519 | |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 520 | // Base case -- just logical-and the two conditions together. |
| 521 | |
| 522 | if (InsertPt) { |
| 523 | makeAvailableAt(Cond0, InsertPt); |
| 524 | makeAvailableAt(Cond1, InsertPt); |
| 525 | |
| 526 | Result = BinaryOperator::CreateAnd(Cond0, Cond1, "wide.chk", InsertPt); |
| 527 | } |
| 528 | |
| 529 | // We were not able to compute Cond0 AND Cond1 for the price of one. |
| 530 | return false; |
| 531 | } |
| 532 | |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 533 | bool GuardWideningImpl::parseRangeChecks( |
| 534 | Value *CheckCond, SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks, |
| 535 | SmallPtrSetImpl<Value *> &Visited) { |
| 536 | if (!Visited.insert(CheckCond).second) |
| 537 | return true; |
| 538 | |
| 539 | using namespace llvm::PatternMatch; |
| 540 | |
| 541 | { |
| 542 | Value *AndLHS, *AndRHS; |
| 543 | if (match(CheckCond, m_And(m_Value(AndLHS), m_Value(AndRHS)))) |
| 544 | return parseRangeChecks(AndLHS, Checks) && |
| 545 | parseRangeChecks(AndRHS, Checks); |
| 546 | } |
| 547 | |
| 548 | auto *IC = dyn_cast<ICmpInst>(CheckCond); |
| 549 | if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() || |
| 550 | (IC->getPredicate() != ICmpInst::ICMP_ULT && |
| 551 | IC->getPredicate() != ICmpInst::ICMP_UGT)) |
| 552 | return false; |
| 553 | |
| 554 | Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1); |
| 555 | if (IC->getPredicate() == ICmpInst::ICMP_UGT) |
| 556 | std::swap(CmpLHS, CmpRHS); |
| 557 | |
| 558 | auto &DL = IC->getModule()->getDataLayout(); |
| 559 | |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 560 | GuardWideningImpl::RangeCheck Check( |
| 561 | CmpLHS, cast<ConstantInt>(ConstantInt::getNullValue(CmpRHS->getType())), |
| 562 | CmpRHS, IC); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 563 | |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 564 | if (!isKnownNonNegative(Check.getLength(), DL)) |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 565 | return false; |
| 566 | |
| 567 | // What we have in \c Check now is a correct interpretation of \p CheckCond. |
| 568 | // Try to see if we can move some constant offsets into the \c Offset field. |
| 569 | |
| 570 | bool Changed; |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 571 | auto &Ctx = CheckCond->getContext(); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 572 | |
| 573 | do { |
| 574 | Value *OpLHS; |
| 575 | ConstantInt *OpRHS; |
| 576 | Changed = false; |
| 577 | |
| 578 | #ifndef NDEBUG |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 579 | auto *BaseInst = dyn_cast<Instruction>(Check.getBase()); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 580 | assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) && |
| 581 | "Unreachable instruction?"); |
| 582 | #endif |
| 583 | |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 584 | if (match(Check.getBase(), m_Add(m_Value(OpLHS), m_ConstantInt(OpRHS)))) { |
| 585 | Check.setBase(OpLHS); |
| 586 | APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue(); |
| 587 | Check.setOffset(ConstantInt::get(Ctx, NewOffset)); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 588 | Changed = true; |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 589 | } else if (match(Check.getBase(), |
| 590 | m_Or(m_Value(OpLHS), m_ConstantInt(OpRHS)))) { |
Craig Topper | 8205a1a | 2017-05-24 16:53:07 +0000 | [diff] [blame] | 591 | KnownBits Known = computeKnownBits(OpLHS, DL); |
Craig Topper | b45eabc | 2017-04-26 16:39:58 +0000 | [diff] [blame] | 592 | if ((OpRHS->getValue() & Known.Zero) == OpRHS->getValue()) { |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 593 | Check.setBase(OpLHS); |
| 594 | APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue(); |
| 595 | Check.setOffset(ConstantInt::get(Ctx, NewOffset)); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 596 | Changed = true; |
| 597 | } |
| 598 | } |
| 599 | } while (Changed); |
| 600 | |
| 601 | Checks.push_back(Check); |
| 602 | return true; |
| 603 | } |
| 604 | |
| 605 | bool GuardWideningImpl::combineRangeChecks( |
| 606 | SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks, |
| 607 | SmallVectorImpl<GuardWideningImpl::RangeCheck> &RangeChecksOut) { |
| 608 | unsigned OldCount = Checks.size(); |
| 609 | while (!Checks.empty()) { |
Sanjoy Das | be6c7a1 | 2016-05-21 02:24:44 +0000 | [diff] [blame] | 610 | // Pick all of the range checks with a specific base and length, and try to |
| 611 | // merge them. |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 612 | Value *CurrentBase = Checks.front().getBase(); |
| 613 | Value *CurrentLength = Checks.front().getLength(); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 614 | |
Sanjoy Das | be6c7a1 | 2016-05-21 02:24:44 +0000 | [diff] [blame] | 615 | SmallVector<GuardWideningImpl::RangeCheck, 3> CurrentChecks; |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 616 | |
Sanjoy Das | be6c7a1 | 2016-05-21 02:24:44 +0000 | [diff] [blame] | 617 | auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) { |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 618 | return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength; |
Sanjoy Das | be6c7a1 | 2016-05-21 02:24:44 +0000 | [diff] [blame] | 619 | }; |
| 620 | |
Sanjoy Das | 9020872 | 2017-02-21 00:38:44 +0000 | [diff] [blame] | 621 | copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck); |
Sanjoy Das | be6c7a1 | 2016-05-21 02:24:44 +0000 | [diff] [blame] | 622 | Checks.erase(remove_if(Checks, IsCurrentCheck), Checks.end()); |
| 623 | |
| 624 | assert(CurrentChecks.size() != 0 && "We know we have at least one!"); |
| 625 | |
| 626 | if (CurrentChecks.size() < 3) { |
| 627 | RangeChecksOut.insert(RangeChecksOut.end(), CurrentChecks.begin(), |
| 628 | CurrentChecks.end()); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 629 | continue; |
| 630 | } |
| 631 | |
Sanjoy Das | be6c7a1 | 2016-05-21 02:24:44 +0000 | [diff] [blame] | 632 | // CurrentChecks.size() will typically be 3 here, but so far there has been |
| 633 | // no need to hard-code that fact. |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 634 | |
Mandeep Singh Grang | 636d94d | 2018-04-13 19:47:57 +0000 | [diff] [blame] | 635 | llvm::sort(CurrentChecks.begin(), CurrentChecks.end(), |
| 636 | [&](const GuardWideningImpl::RangeCheck &LHS, |
| 637 | const GuardWideningImpl::RangeCheck &RHS) { |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 638 | return LHS.getOffsetValue().slt(RHS.getOffsetValue()); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 639 | }); |
| 640 | |
| 641 | // Note: std::sort should not invalidate the ChecksStart iterator. |
| 642 | |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 643 | ConstantInt *MinOffset = CurrentChecks.front().getOffset(), |
| 644 | *MaxOffset = CurrentChecks.back().getOffset(); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 645 | |
| 646 | unsigned BitWidth = MaxOffset->getValue().getBitWidth(); |
| 647 | if ((MaxOffset->getValue() - MinOffset->getValue()) |
| 648 | .ugt(APInt::getSignedMinValue(BitWidth))) |
| 649 | return false; |
| 650 | |
| 651 | APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue(); |
Benjamin Kramer | 46e38f3 | 2016-06-08 10:01:20 +0000 | [diff] [blame] | 652 | const APInt &HighOffset = MaxOffset->getValue(); |
Sanjoy Das | 2351975 | 2016-05-19 23:15:59 +0000 | [diff] [blame] | 653 | auto OffsetOK = [&](const GuardWideningImpl::RangeCheck &RC) { |
Sanjoy Das | be99153 | 2016-05-24 20:54:45 +0000 | [diff] [blame] | 654 | return (HighOffset - RC.getOffsetValue()).ult(MaxDiff); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 655 | }; |
| 656 | |
| 657 | if (MaxDiff.isMinValue() || |
Sanjoy Das | be6c7a1 | 2016-05-21 02:24:44 +0000 | [diff] [blame] | 658 | !std::all_of(std::next(CurrentChecks.begin()), CurrentChecks.end(), |
| 659 | OffsetOK)) |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 660 | return false; |
| 661 | |
| 662 | // We have a series of f+1 checks as: |
| 663 | // |
| 664 | // I+k_0 u< L ... Chk_0 |
Sanjoy Das | 23f314d | 2017-05-03 18:29:34 +0000 | [diff] [blame] | 665 | // I+k_1 u< L ... Chk_1 |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 666 | // ... |
Sanjoy Das | 23f314d | 2017-05-03 18:29:34 +0000 | [diff] [blame] | 667 | // I+k_f u< L ... Chk_f |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 668 | // |
Sanjoy Das | 23f314d | 2017-05-03 18:29:34 +0000 | [diff] [blame] | 669 | // with forall i in [0,f]: k_f-k_i u< k_f-k_0 ... Precond_0 |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 670 | // k_f-k_0 u< INT_MIN+k_f ... Precond_1 |
| 671 | // k_f != k_0 ... Precond_2 |
| 672 | // |
| 673 | // Claim: |
Sanjoy Das | 23f314d | 2017-05-03 18:29:34 +0000 | [diff] [blame] | 674 | // Chk_0 AND Chk_f implies all the other checks |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 675 | // |
| 676 | // Informal proof sketch: |
| 677 | // |
| 678 | // We will show that the integer range [I+k_0,I+k_f] does not unsigned-wrap |
| 679 | // (i.e. going from I+k_0 to I+k_f does not cross the -1,0 boundary) and |
| 680 | // thus I+k_f is the greatest unsigned value in that range. |
| 681 | // |
| 682 | // This combined with Ckh_(f+1) shows that everything in that range is u< L. |
| 683 | // Via Precond_0 we know that all of the indices in Chk_0 through Chk_(f+1) |
| 684 | // lie in [I+k_0,I+k_f], this proving our claim. |
| 685 | // |
| 686 | // To see that [I+k_0,I+k_f] is not a wrapping range, note that there are |
| 687 | // two possibilities: I+k_0 u< I+k_f or I+k_0 >u I+k_f (they can't be equal |
| 688 | // since k_0 != k_f). In the former case, [I+k_0,I+k_f] is not a wrapping |
| 689 | // range by definition, and the latter case is impossible: |
| 690 | // |
| 691 | // 0-----I+k_f---I+k_0----L---INT_MAX,INT_MIN------------------(-1) |
| 692 | // xxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
| 693 | // |
| 694 | // For Chk_0 to succeed, we'd have to have k_f-k_0 (the range highlighted |
| 695 | // with 'x' above) to be at least >u INT_MIN. |
| 696 | |
Sanjoy Das | be6c7a1 | 2016-05-21 02:24:44 +0000 | [diff] [blame] | 697 | RangeChecksOut.emplace_back(CurrentChecks.front()); |
| 698 | RangeChecksOut.emplace_back(CurrentChecks.back()); |
Sanjoy Das | f5f0331 | 2016-05-19 22:55:46 +0000 | [diff] [blame] | 699 | } |
| 700 | |
| 701 | assert(RangeChecksOut.size() <= OldCount && "We pessimized!"); |
| 702 | return RangeChecksOut.size() != OldCount; |
| 703 | } |
| 704 | |
Florian Hahn | 6b3216a | 2017-07-31 10:07:49 +0000 | [diff] [blame] | 705 | #ifndef NDEBUG |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 706 | StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) { |
| 707 | switch (WS) { |
| 708 | case WS_IllegalOrNegative: |
| 709 | return "IllegalOrNegative"; |
| 710 | case WS_Neutral: |
| 711 | return "Neutral"; |
| 712 | case WS_Positive: |
| 713 | return "Positive"; |
| 714 | case WS_VeryPositive: |
| 715 | return "VeryPositive"; |
| 716 | } |
| 717 | |
| 718 | llvm_unreachable("Fully covered switch above!"); |
| 719 | } |
Florian Hahn | 6b3216a | 2017-07-31 10:07:49 +0000 | [diff] [blame] | 720 | #endif |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 721 | |
Philip Reames | 6a1f344 | 2018-03-23 23:41:47 +0000 | [diff] [blame] | 722 | PreservedAnalyses GuardWideningPass::run(Function &F, |
| 723 | FunctionAnalysisManager &AM) { |
| 724 | auto &DT = AM.getResult<DominatorTreeAnalysis>(F); |
| 725 | auto &LI = AM.getResult<LoopAnalysis>(F); |
| 726 | auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F); |
Philip Reames | 502d4481 | 2018-04-27 23:15:56 +0000 | [diff] [blame] | 727 | if (!GuardWideningImpl(DT, &PDT, LI, DT.getRootNode(), |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 728 | [](BasicBlock*) { return true; } ).run()) |
Philip Reames | 6a1f344 | 2018-03-23 23:41:47 +0000 | [diff] [blame] | 729 | return PreservedAnalyses::all(); |
| 730 | |
| 731 | PreservedAnalyses PA; |
| 732 | PA.preserveSet<CFGAnalyses>(); |
| 733 | return PA; |
| 734 | } |
| 735 | |
| 736 | namespace { |
| 737 | struct GuardWideningLegacyPass : public FunctionPass { |
| 738 | static char ID; |
Philip Reames | 6a1f344 | 2018-03-23 23:41:47 +0000 | [diff] [blame] | 739 | |
| 740 | GuardWideningLegacyPass() : FunctionPass(ID) { |
| 741 | initializeGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry()); |
| 742 | } |
| 743 | |
| 744 | bool runOnFunction(Function &F) override { |
| 745 | if (skipFunction(F)) |
| 746 | return false; |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 747 | auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 748 | auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
| 749 | auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); |
Philip Reames | 502d4481 | 2018-04-27 23:15:56 +0000 | [diff] [blame] | 750 | return GuardWideningImpl(DT, &PDT, LI, DT.getRootNode(), |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 751 | [](BasicBlock*) { return true; } ).run(); |
Philip Reames | 6a1f344 | 2018-03-23 23:41:47 +0000 | [diff] [blame] | 752 | } |
| 753 | |
| 754 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 755 | AU.setPreservesCFG(); |
| 756 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 757 | AU.addRequired<PostDominatorTreeWrapperPass>(); |
| 758 | AU.addRequired<LoopInfoWrapperPass>(); |
| 759 | } |
| 760 | }; |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 761 | |
| 762 | /// Same as above, but restricted to a single loop at a time. Can be |
| 763 | /// scheduled with other loop passes w/o breaking out of LPM |
| 764 | struct LoopGuardWideningLegacyPass : public LoopPass { |
| 765 | static char ID; |
| 766 | |
| 767 | LoopGuardWideningLegacyPass() : LoopPass(ID) { |
| 768 | initializeLoopGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry()); |
| 769 | } |
| 770 | |
| 771 | bool runOnLoop(Loop *L, LPPassManager &LPM) override { |
| 772 | if (skipLoop(L)) |
| 773 | return false; |
| 774 | auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 775 | auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Philip Reames | 502d4481 | 2018-04-27 23:15:56 +0000 | [diff] [blame] | 776 | auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>(); |
| 777 | auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr; |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 778 | BasicBlock *RootBB = L->getLoopPredecessor(); |
| 779 | if (!RootBB) |
| 780 | RootBB = L->getHeader(); |
| 781 | auto BlockFilter = [&](BasicBlock *BB) { |
| 782 | return BB == RootBB || L->contains(BB); |
| 783 | }; |
| 784 | return GuardWideningImpl(DT, PDT, LI, |
| 785 | DT.getNode(RootBB), BlockFilter).run(); |
| 786 | } |
| 787 | |
| 788 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 789 | AU.setPreservesCFG(); |
| 790 | getLoopAnalysisUsage(AU); |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 791 | AU.addPreserved<PostDominatorTreeWrapperPass>(); |
| 792 | } |
| 793 | }; |
Philip Reames | 6a1f344 | 2018-03-23 23:41:47 +0000 | [diff] [blame] | 794 | } |
| 795 | |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 796 | char GuardWideningLegacyPass::ID = 0; |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 797 | char LoopGuardWideningLegacyPass::ID = 0; |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 798 | |
| 799 | INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards", |
| 800 | false, false) |
| 801 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 802 | INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) |
| 803 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 804 | INITIALIZE_PASS_END(GuardWideningLegacyPass, "guard-widening", "Widen guards", |
| 805 | false, false) |
| 806 | |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 807 | INITIALIZE_PASS_BEGIN(LoopGuardWideningLegacyPass, "loop-guard-widening", |
| 808 | "Widen guards (within a single loop, as a loop pass)", |
| 809 | false, false) |
| 810 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 811 | INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) |
| 812 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 813 | INITIALIZE_PASS_END(LoopGuardWideningLegacyPass, "loop-guard-widening", |
| 814 | "Widen guards (within a single loop, as a loop pass)", |
| 815 | false, false) |
| 816 | |
Sanjoy Das | 083f389 | 2016-05-18 22:55:34 +0000 | [diff] [blame] | 817 | FunctionPass *llvm::createGuardWideningPass() { |
| 818 | return new GuardWideningLegacyPass(); |
| 819 | } |
Philip Reames | 9258e9d | 2018-04-27 17:29:10 +0000 | [diff] [blame] | 820 | |
| 821 | Pass *llvm::createLoopGuardWideningPass() { |
| 822 | return new LoopGuardWideningLegacyPass(); |
| 823 | } |