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