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