Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 1 | //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===// |
| 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 induction variable simplification. It does |
| 11 | // not define any actual pass or policy, but provides a single function to |
| 12 | // simplify a loop's induction variables based on ScalarEvolution. |
| 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 16 | #include "llvm/Transforms/Utils/SimplifyIndVar.h" |
Chandler Carruth | 8a8cd2b | 2014-01-07 11:48:04 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/STLExtras.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/SmallVector.h" |
| 19 | #include "llvm/ADT/Statistic.h" |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/IVUsers.h" |
| 21 | #include "llvm/Analysis/LoopInfo.h" |
| 22 | #include "llvm/Analysis/LoopPass.h" |
| 23 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 24 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 25 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 8a8cd2b | 2014-01-07 11:48:04 +0000 | [diff] [blame] | 26 | #include "llvm/IR/IRBuilder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 27 | #include "llvm/IR/Instructions.h" |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 28 | #include "llvm/IR/IntrinsicInst.h" |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 29 | #include "llvm/Support/CommandLine.h" |
| 30 | #include "llvm/Support/Debug.h" |
| 31 | #include "llvm/Support/raw_ostream.h" |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 32 | |
| 33 | using namespace llvm; |
| 34 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 35 | #define DEBUG_TYPE "indvars" |
| 36 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 37 | STATISTIC(NumElimIdentity, "Number of IV identities eliminated"); |
| 38 | STATISTIC(NumElimOperand, "Number of IV operands folded into a use"); |
| 39 | STATISTIC(NumElimRem , "Number of IV remainder operations eliminated"); |
| 40 | STATISTIC(NumElimCmp , "Number of IV comparisons eliminated"); |
| 41 | |
| 42 | namespace { |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 43 | /// This is a utility for simplifying induction variables |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 44 | /// based on ScalarEvolution. It is the primary instrument of the |
| 45 | /// IndvarSimplify pass, but it may also be directly invoked to cleanup after |
| 46 | /// other loop passes that preserve SCEV. |
| 47 | class SimplifyIndvar { |
| 48 | Loop *L; |
| 49 | LoopInfo *LI; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 50 | ScalarEvolution *SE; |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 51 | const DataLayout *DL; // May be NULL |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 52 | |
| 53 | SmallVectorImpl<WeakVH> &DeadInsts; |
| 54 | |
| 55 | bool Changed; |
| 56 | |
| 57 | public: |
Chandler Carruth | 4f8f307 | 2015-01-17 14:16:18 +0000 | [diff] [blame^] | 58 | SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LoopInfo *LI, |
| 59 | const DataLayout *DL, SmallVectorImpl<WeakVH> &Dead, |
| 60 | IVUsers *IVU = nullptr) |
| 61 | : L(Loop), LI(LI), SE(SE), DL(DL), DeadInsts(Dead), Changed(false) { |
Andrew Trick | e629d00 | 2011-08-10 04:22:26 +0000 | [diff] [blame] | 62 | assert(LI && "IV simplification requires LoopInfo"); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 63 | } |
| 64 | |
| 65 | bool hasChanged() const { return Changed; } |
| 66 | |
| 67 | /// Iteratively perform simplification on a worklist of users of the |
| 68 | /// specified induction variable. This is the top-level driver that applies |
| 69 | /// all simplicitions to users of an IV. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 70 | void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 71 | |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 72 | Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 73 | |
| 74 | bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand); |
| 75 | void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand); |
| 76 | void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand, |
| 77 | bool IsSigned); |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 78 | bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand); |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 79 | |
| 80 | Instruction *splitOverflowIntrinsic(Instruction *IVUser, |
| 81 | const DominatorTree *DT); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 82 | }; |
| 83 | } |
| 84 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 85 | /// Fold an IV operand into its use. This removes increments of an |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 86 | /// aligned IV when used by a instruction that ignores the low bits. |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 87 | /// |
Andrew Trick | 7251e41 | 2011-09-19 17:54:39 +0000 | [diff] [blame] | 88 | /// IVOperand is guaranteed SCEVable, but UseInst may not be. |
| 89 | /// |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 90 | /// Return the operand of IVOperand for this induction variable if IVOperand can |
Andrew Trick | 6dbb060 | 2011-08-10 18:07:05 +0000 | [diff] [blame] | 91 | /// be folded (in case more folding opportunities have been exposed). |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 92 | /// Otherwise return null. |
| 93 | Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 94 | Value *IVSrc = nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 95 | unsigned OperIdx = 0; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 96 | const SCEV *FoldedExpr = nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 97 | switch (UseInst->getOpcode()) { |
| 98 | default: |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 99 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 100 | case Instruction::UDiv: |
| 101 | case Instruction::LShr: |
| 102 | // We're only interested in the case where we know something about |
| 103 | // the numerator and have a constant denominator. |
| 104 | if (IVOperand != UseInst->getOperand(OperIdx) || |
| 105 | !isa<ConstantInt>(UseInst->getOperand(1))) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 106 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 107 | |
| 108 | // Attempt to fold a binary operator with constant operand. |
| 109 | // e.g. ((I + 1) >> 2) => I >> 2 |
Andrew Trick | 9490458 | 2011-11-17 23:36:35 +0000 | [diff] [blame] | 110 | if (!isa<BinaryOperator>(IVOperand) |
| 111 | || !isa<ConstantInt>(IVOperand->getOperand(1))) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 112 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 113 | |
| 114 | IVSrc = IVOperand->getOperand(0); |
| 115 | // IVSrc must be the (SCEVable) IV, since the other operand is const. |
| 116 | assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand"); |
| 117 | |
| 118 | ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1)); |
| 119 | if (UseInst->getOpcode() == Instruction::LShr) { |
| 120 | // Get a constant for the divisor. See createSCEV. |
| 121 | uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth(); |
| 122 | if (D->getValue().uge(BitWidth)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 123 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 124 | |
| 125 | D = ConstantInt::get(UseInst->getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 126 | APInt::getOneBitSet(BitWidth, D->getZExtValue())); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 127 | } |
| 128 | FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D)); |
| 129 | } |
| 130 | // We have something that might fold it's operand. Compare SCEVs. |
| 131 | if (!SE->isSCEVable(UseInst->getType())) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 132 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 133 | |
| 134 | // Bypass the operand if SCEV can prove it has no effect. |
| 135 | if (SE->getSCEV(UseInst) != FoldedExpr) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 136 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 137 | |
| 138 | DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand |
| 139 | << " -> " << *UseInst << '\n'); |
| 140 | |
| 141 | UseInst->setOperand(OperIdx, IVSrc); |
| 142 | assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper"); |
| 143 | |
| 144 | ++NumElimOperand; |
| 145 | Changed = true; |
| 146 | if (IVOperand->use_empty()) |
| 147 | DeadInsts.push_back(IVOperand); |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 148 | return IVSrc; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 149 | } |
| 150 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 151 | /// SimplifyIVUsers helper for eliminating useless |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 152 | /// comparisons against an induction variable. |
| 153 | void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) { |
| 154 | unsigned IVOperIdx = 0; |
| 155 | ICmpInst::Predicate Pred = ICmp->getPredicate(); |
| 156 | if (IVOperand != ICmp->getOperand(0)) { |
| 157 | // Swapped |
| 158 | assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); |
| 159 | IVOperIdx = 1; |
| 160 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 161 | } |
| 162 | |
| 163 | // Get the SCEVs for the ICmp operands. |
| 164 | const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx)); |
| 165 | const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx)); |
| 166 | |
| 167 | // Simplify unnecessary loops away. |
| 168 | const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); |
| 169 | S = SE->getSCEVAtScope(S, ICmpLoop); |
| 170 | X = SE->getSCEVAtScope(X, ICmpLoop); |
| 171 | |
| 172 | // If the condition is always true or always false, replace it with |
| 173 | // a constant value. |
| 174 | if (SE->isKnownPredicate(Pred, S, X)) |
| 175 | ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext())); |
| 176 | else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) |
| 177 | ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext())); |
| 178 | else |
| 179 | return; |
| 180 | |
| 181 | DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); |
| 182 | ++NumElimCmp; |
| 183 | Changed = true; |
| 184 | DeadInsts.push_back(ICmp); |
| 185 | } |
| 186 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 187 | /// SimplifyIVUsers helper for eliminating useless |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 188 | /// remainder operations operating on an induction variable. |
| 189 | void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem, |
| 190 | Value *IVOperand, |
| 191 | bool IsSigned) { |
| 192 | // We're only interested in the case where we know something about |
| 193 | // the numerator. |
| 194 | if (IVOperand != Rem->getOperand(0)) |
| 195 | return; |
| 196 | |
| 197 | // Get the SCEVs for the ICmp operands. |
| 198 | const SCEV *S = SE->getSCEV(Rem->getOperand(0)); |
| 199 | const SCEV *X = SE->getSCEV(Rem->getOperand(1)); |
| 200 | |
| 201 | // Simplify unnecessary loops away. |
| 202 | const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent()); |
| 203 | S = SE->getSCEVAtScope(S, ICmpLoop); |
| 204 | X = SE->getSCEVAtScope(X, ICmpLoop); |
| 205 | |
| 206 | // i % n --> i if i is in [0,n). |
| 207 | if ((!IsSigned || SE->isKnownNonNegative(S)) && |
| 208 | SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, |
| 209 | S, X)) |
| 210 | Rem->replaceAllUsesWith(Rem->getOperand(0)); |
| 211 | else { |
| 212 | // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n). |
| 213 | const SCEV *LessOne = |
| 214 | SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1)); |
| 215 | if (IsSigned && !SE->isKnownNonNegative(LessOne)) |
| 216 | return; |
| 217 | |
| 218 | if (!SE->isKnownPredicate(IsSigned ? |
| 219 | ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, |
| 220 | LessOne, X)) |
| 221 | return; |
| 222 | |
| 223 | ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 224 | Rem->getOperand(0), Rem->getOperand(1)); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 225 | SelectInst *Sel = |
| 226 | SelectInst::Create(ICmp, |
| 227 | ConstantInt::get(Rem->getType(), 0), |
| 228 | Rem->getOperand(0), "tmp", Rem); |
| 229 | Rem->replaceAllUsesWith(Sel); |
| 230 | } |
| 231 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 232 | DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); |
| 233 | ++NumElimRem; |
| 234 | Changed = true; |
| 235 | DeadInsts.push_back(Rem); |
| 236 | } |
| 237 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 238 | /// Eliminate an operation that consumes a simple IV and has |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 239 | /// no observable side-effect given the range of IV values. |
Andrew Trick | 7251e41 | 2011-09-19 17:54:39 +0000 | [diff] [blame] | 240 | /// IVOperand is guaranteed SCEVable, but UseInst may not be. |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 241 | bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst, |
| 242 | Instruction *IVOperand) { |
| 243 | if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) { |
| 244 | eliminateIVComparison(ICmp, IVOperand); |
| 245 | return true; |
| 246 | } |
| 247 | if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) { |
| 248 | bool IsSigned = Rem->getOpcode() == Instruction::SRem; |
| 249 | if (IsSigned || Rem->getOpcode() == Instruction::URem) { |
| 250 | eliminateIVRemainder(Rem, IVOperand, IsSigned); |
| 251 | return true; |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | // Eliminate any operation that SCEV can prove is an identity function. |
| 256 | if (!SE->isSCEVable(UseInst->getType()) || |
| 257 | (UseInst->getType() != IVOperand->getType()) || |
| 258 | (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand))) |
| 259 | return false; |
| 260 | |
| 261 | DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n'); |
| 262 | |
| 263 | UseInst->replaceAllUsesWith(IVOperand); |
| 264 | ++NumElimIdentity; |
| 265 | Changed = true; |
| 266 | DeadInsts.push_back(UseInst); |
| 267 | return true; |
| 268 | } |
| 269 | |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 270 | /// Annotate BO with nsw / nuw if it provably does not signed-overflow / |
| 271 | /// unsigned-overflow. Returns true if anything changed, false otherwise. |
| 272 | bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO, |
| 273 | Value *IVOperand) { |
| 274 | |
| 275 | // Currently we only handle instructions of the form "add <indvar> <value>" |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 276 | unsigned Op = BO->getOpcode(); |
Sanjoy Das | 8c252bd | 2015-01-15 01:46:09 +0000 | [diff] [blame] | 277 | if (Op != Instruction::Add) |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 278 | return false; |
| 279 | |
| 280 | // If BO is already both nuw and nsw then there is nothing left to do |
| 281 | if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap()) |
| 282 | return false; |
| 283 | |
| 284 | IntegerType *IT = cast<IntegerType>(IVOperand->getType()); |
| 285 | Value *OtherOperand = nullptr; |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 286 | if (BO->getOperand(0) == IVOperand) { |
| 287 | OtherOperand = BO->getOperand(1); |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 288 | } else { |
| 289 | assert(BO->getOperand(1) == IVOperand && "only other use!"); |
| 290 | OtherOperand = BO->getOperand(0); |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 291 | } |
| 292 | |
| 293 | bool Changed = false; |
| 294 | const SCEV *OtherOpSCEV = SE->getSCEV(OtherOperand); |
| 295 | if (OtherOpSCEV == SE->getCouldNotCompute()) |
| 296 | return false; |
| 297 | |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 298 | const SCEV *IVOpSCEV = SE->getSCEV(IVOperand); |
| 299 | const SCEV *ZeroSCEV = SE->getConstant(IVOpSCEV->getType(), 0); |
| 300 | |
| 301 | if (!BO->hasNoSignedWrap()) { |
| 302 | // Upgrade the add to an "add nsw" if we can prove that it will never |
| 303 | // sign-overflow or sign-underflow. |
| 304 | |
| 305 | const SCEV *SignedMax = |
| 306 | SE->getConstant(APInt::getSignedMaxValue(IT->getBitWidth())); |
| 307 | const SCEV *SignedMin = |
| 308 | SE->getConstant(APInt::getSignedMinValue(IT->getBitWidth())); |
| 309 | |
| 310 | // The addition "IVOperand + OtherOp" does not sign-overflow if the result |
| 311 | // is sign-representable in 2's complement in the given bit-width. |
| 312 | // |
| 313 | // If OtherOp is SLT 0, then for an IVOperand in [SignedMin - OtherOp, |
| 314 | // SignedMax], "IVOperand + OtherOp" is in [SignedMin, SignedMax + OtherOp]. |
| 315 | // Everything in [SignedMin, SignedMax + OtherOp] is representable since |
| 316 | // SignedMax + OtherOp is at least -1. |
| 317 | // |
| 318 | // If OtherOp is SGE 0, then for an IVOperand in [SignedMin, SignedMax - |
| 319 | // OtherOp], "IVOperand + OtherOp" is in [SignedMin + OtherOp, SignedMax]. |
| 320 | // Everything in [SignedMin + OtherOp, SignedMax] is representable since |
| 321 | // SignedMin + OtherOp is at most -1. |
| 322 | // |
| 323 | // It follows that for all values of IVOperand in [SignedMin - smin(0, |
| 324 | // OtherOp), SignedMax - smax(0, OtherOp)] the result of the add is |
| 325 | // representable (i.e. there is no sign-overflow). |
| 326 | |
| 327 | const SCEV *UpperDelta = SE->getSMaxExpr(ZeroSCEV, OtherOpSCEV); |
| 328 | const SCEV *UpperLimit = SE->getMinusSCEV(SignedMax, UpperDelta); |
| 329 | |
| 330 | bool NeverSignedOverflows = |
| 331 | SE->isKnownPredicate(ICmpInst::ICMP_SLE, IVOpSCEV, UpperLimit); |
| 332 | |
| 333 | if (NeverSignedOverflows) { |
| 334 | const SCEV *LowerDelta = SE->getSMinExpr(ZeroSCEV, OtherOpSCEV); |
| 335 | const SCEV *LowerLimit = SE->getMinusSCEV(SignedMin, LowerDelta); |
| 336 | |
| 337 | bool NeverSignedUnderflows = |
| 338 | SE->isKnownPredicate(ICmpInst::ICMP_SGE, IVOpSCEV, LowerLimit); |
| 339 | if (NeverSignedUnderflows) { |
| 340 | BO->setHasNoSignedWrap(true); |
| 341 | Changed = true; |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | if (!BO->hasNoUnsignedWrap()) { |
| 347 | // Upgrade the add computing "IVOperand + OtherOp" to an "add nuw" if we can |
| 348 | // prove that it will never unsigned-overflow (i.e. the result will always |
| 349 | // be representable in the given bit-width). |
| 350 | // |
| 351 | // "IVOperand + OtherOp" is unsigned-representable in 2's complement iff it |
| 352 | // does not produce a carry. "IVOperand + OtherOp" produces no carry iff |
| 353 | // IVOperand ULE (UnsignedMax - OtherOp). |
| 354 | |
| 355 | const SCEV *UnsignedMax = |
| 356 | SE->getConstant(APInt::getMaxValue(IT->getBitWidth())); |
| 357 | const SCEV *UpperLimit = SE->getMinusSCEV(UnsignedMax, OtherOpSCEV); |
| 358 | |
| 359 | bool NeverUnsignedOverflows = |
| 360 | SE->isKnownPredicate(ICmpInst::ICMP_ULE, IVOpSCEV, UpperLimit); |
| 361 | |
| 362 | if (NeverUnsignedOverflows) { |
| 363 | BO->setHasNoUnsignedWrap(true); |
| 364 | Changed = true; |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | return Changed; |
| 369 | } |
| 370 | |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 371 | /// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow |
| 372 | /// analysis and optimization. |
| 373 | /// |
| 374 | /// \return A new value representing the non-overflowing add if possible, |
| 375 | /// otherwise return the original value. |
| 376 | Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser, |
| 377 | const DominatorTree *DT) { |
| 378 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser); |
| 379 | if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow) |
| 380 | return IVUser; |
| 381 | |
| 382 | // Find a branch guarded by the overflow check. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 383 | BranchInst *Branch = nullptr; |
| 384 | Instruction *AddVal = nullptr; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 385 | for (User *U : II->users()) { |
| 386 | if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(U)) { |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 387 | if (ExtractInst->getNumIndices() != 1) |
| 388 | continue; |
| 389 | if (ExtractInst->getIndices()[0] == 0) |
| 390 | AddVal = ExtractInst; |
| 391 | else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse()) |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 392 | Branch = dyn_cast<BranchInst>(ExtractInst->user_back()); |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 393 | } |
| 394 | } |
| 395 | if (!AddVal || !Branch) |
| 396 | return IVUser; |
| 397 | |
| 398 | BasicBlock *ContinueBB = Branch->getSuccessor(1); |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 399 | if (std::next(pred_begin(ContinueBB)) != pred_end(ContinueBB)) |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 400 | return IVUser; |
| 401 | |
| 402 | // Check if all users of the add are provably NSW. |
| 403 | bool AllNSW = true; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 404 | for (Use &U : AddVal->uses()) { |
| 405 | if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser())) { |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 406 | BasicBlock *UseBB = UseInst->getParent(); |
| 407 | if (PHINode *PHI = dyn_cast<PHINode>(UseInst)) |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 408 | UseBB = PHI->getIncomingBlock(U); |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 409 | if (!DT->dominates(ContinueBB, UseBB)) { |
| 410 | AllNSW = false; |
| 411 | break; |
| 412 | } |
| 413 | } |
| 414 | } |
| 415 | if (!AllNSW) |
| 416 | return IVUser; |
| 417 | |
| 418 | // Go for it... |
| 419 | IRBuilder<> Builder(IVUser); |
| 420 | Instruction *AddInst = dyn_cast<Instruction>( |
| 421 | Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1))); |
| 422 | |
| 423 | // The caller expects the new add to have the same form as the intrinsic. The |
| 424 | // IV operand position must be the same. |
| 425 | assert((AddInst->getOpcode() == Instruction::Add && |
| 426 | AddInst->getOperand(0) == II->getOperand(0)) && |
| 427 | "Bad add instruction created from overflow intrinsic."); |
| 428 | |
| 429 | AddVal->replaceAllUsesWith(AddInst); |
| 430 | DeadInsts.push_back(AddVal); |
| 431 | return AddInst; |
| 432 | } |
| 433 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 434 | /// Add all uses of Def to the current IV's worklist. |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 435 | static void pushIVUsers( |
| 436 | Instruction *Def, |
| 437 | SmallPtrSet<Instruction*,16> &Simplified, |
| 438 | SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) { |
| 439 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 440 | for (User *U : Def->users()) { |
| 441 | Instruction *UI = cast<Instruction>(U); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 442 | |
| 443 | // Avoid infinite or exponential worklist processing. |
| 444 | // Also ensure unique worklist users. |
| 445 | // If Def is a LoopPhi, it may not be in the Simplified set, so check for |
| 446 | // self edges first. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 447 | if (UI != Def && Simplified.insert(UI).second) |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 448 | SimpleIVUsers.push_back(std::make_pair(UI, Def)); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 449 | } |
| 450 | } |
| 451 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 452 | /// Return true if this instruction generates a simple SCEV |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 453 | /// expression in terms of that IV. |
| 454 | /// |
Andrew Trick | 6dbb060 | 2011-08-10 18:07:05 +0000 | [diff] [blame] | 455 | /// This is similar to IVUsers' isInteresting() but processes each instruction |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 456 | /// non-recursively when the operand is already known to be a simpleIVUser. |
| 457 | /// |
| 458 | static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) { |
| 459 | if (!SE->isSCEVable(I->getType())) |
| 460 | return false; |
| 461 | |
| 462 | // Get the symbolic expression for this instruction. |
| 463 | const SCEV *S = SE->getSCEV(I); |
| 464 | |
| 465 | // Only consider affine recurrences. |
| 466 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); |
| 467 | if (AR && AR->getLoop() == L) |
| 468 | return true; |
| 469 | |
| 470 | return false; |
| 471 | } |
| 472 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 473 | /// Iteratively perform simplification on a worklist of users |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 474 | /// of the specified induction variable. Each successive simplification may push |
| 475 | /// more users which may themselves be candidates for simplification. |
| 476 | /// |
| 477 | /// This algorithm does not require IVUsers analysis. Instead, it simplifies |
| 478 | /// instructions in-place during analysis. Rather than rewriting induction |
| 479 | /// variables bottom-up from their users, it transforms a chain of IVUsers |
| 480 | /// top-down, updating the IR only when it encouters a clear optimization |
| 481 | /// opportunitiy. |
| 482 | /// |
| 483 | /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers. |
| 484 | /// |
| 485 | void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) { |
Andrew Trick | 7251e41 | 2011-09-19 17:54:39 +0000 | [diff] [blame] | 486 | if (!SE->isSCEVable(CurrIV->getType())) |
| 487 | return; |
| 488 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 489 | // Instructions processed by SimplifyIndvar for CurrIV. |
| 490 | SmallPtrSet<Instruction*,16> Simplified; |
| 491 | |
| 492 | // Use-def pairs if IV users waiting to be processed for CurrIV. |
| 493 | SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers; |
| 494 | |
| 495 | // Push users of the current LoopPhi. In rare cases, pushIVUsers may be |
| 496 | // called multiple times for the same LoopPhi. This is the proper thing to |
| 497 | // do for loop header phis that use each other. |
| 498 | pushIVUsers(CurrIV, Simplified, SimpleIVUsers); |
| 499 | |
| 500 | while (!SimpleIVUsers.empty()) { |
| 501 | std::pair<Instruction*, Instruction*> UseOper = |
| 502 | SimpleIVUsers.pop_back_val(); |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 503 | Instruction *UseInst = UseOper.first; |
| 504 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 505 | // Bypass back edges to avoid extra work. |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 506 | if (UseInst == CurrIV) continue; |
| 507 | |
| 508 | if (V && V->shouldSplitOverflowInstrinsics()) { |
| 509 | UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree()); |
| 510 | if (!UseInst) |
| 511 | continue; |
| 512 | } |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 513 | |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 514 | Instruction *IVOperand = UseOper.second; |
| 515 | for (unsigned N = 0; IVOperand; ++N) { |
| 516 | assert(N <= Simplified.size() && "runaway iteration"); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 517 | |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 518 | Value *NewOper = foldIVUser(UseOper.first, IVOperand); |
| 519 | if (!NewOper) |
| 520 | break; // done folding |
| 521 | IVOperand = dyn_cast<Instruction>(NewOper); |
| 522 | } |
| 523 | if (!IVOperand) |
| 524 | continue; |
| 525 | |
| 526 | if (eliminateIVUser(UseOper.first, IVOperand)) { |
| 527 | pushIVUsers(IVOperand, Simplified, SimpleIVUsers); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 528 | continue; |
| 529 | } |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 530 | |
| 531 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) { |
| 532 | if (isa<OverflowingBinaryOperator>(BO) && |
| 533 | strengthenOverflowingOperation(BO, IVOperand)) { |
| 534 | // re-queue uses of the now modified binary operator and fall |
| 535 | // through to the checks that remain. |
| 536 | pushIVUsers(IVOperand, Simplified, SimpleIVUsers); |
| 537 | } |
| 538 | } |
| 539 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 540 | CastInst *Cast = dyn_cast<CastInst>(UseOper.first); |
| 541 | if (V && Cast) { |
| 542 | V->visitCast(Cast); |
| 543 | continue; |
| 544 | } |
| 545 | if (isSimpleIVUser(UseOper.first, L, SE)) { |
| 546 | pushIVUsers(UseOper.first, Simplified, SimpleIVUsers); |
| 547 | } |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | namespace llvm { |
| 552 | |
David Blaikie | a379b181 | 2011-12-20 02:50:00 +0000 | [diff] [blame] | 553 | void IVVisitor::anchor() { } |
| 554 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 555 | /// Simplify instructions that use this induction variable |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 556 | /// by using ScalarEvolution to analyze the IV's recurrence. |
Andrew Trick | e629d00 | 2011-08-10 04:22:26 +0000 | [diff] [blame] | 557 | bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM, |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 558 | SmallVectorImpl<WeakVH> &Dead, IVVisitor *V) |
| 559 | { |
Chandler Carruth | 4f8f307 | 2015-01-17 14:16:18 +0000 | [diff] [blame^] | 560 | DataLayoutPass *DLP = LPM->getAnalysisIfAvailable<DataLayoutPass>(); |
| 561 | LoopInfo *LI = &LPM->getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
| 562 | SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LI, |
| 563 | DLP ? &DLP->getDataLayout() : nullptr, Dead); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 564 | SIV.simplifyUsers(CurrIV, V); |
| 565 | return SIV.hasChanged(); |
| 566 | } |
| 567 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 568 | /// Simplify users of induction variables within this |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 569 | /// loop. This does not actually change or add IVs. |
Andrew Trick | e629d00 | 2011-08-10 04:22:26 +0000 | [diff] [blame] | 570 | bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM, |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 571 | SmallVectorImpl<WeakVH> &Dead) { |
| 572 | bool Changed = false; |
| 573 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
Andrew Trick | e629d00 | 2011-08-10 04:22:26 +0000 | [diff] [blame] | 574 | Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 575 | } |
| 576 | return Changed; |
| 577 | } |
| 578 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 579 | } // namespace llvm |