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