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/LoopInfo.h" |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 22 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 23 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 8a8cd2b | 2014-01-07 11:48:04 +0000 | [diff] [blame] | 24 | #include "llvm/IR/IRBuilder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 25 | #include "llvm/IR/Instructions.h" |
David Green | b26a0a4 | 2017-07-05 13:25:58 +0000 | [diff] [blame] | 26 | #include "llvm/IR/PatternMatch.h" |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 27 | #include "llvm/Support/Debug.h" |
| 28 | #include "llvm/Support/raw_ostream.h" |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 29 | |
| 30 | using namespace llvm; |
| 31 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 32 | #define DEBUG_TYPE "indvars" |
| 33 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 34 | STATISTIC(NumElimIdentity, "Number of IV identities eliminated"); |
| 35 | STATISTIC(NumElimOperand, "Number of IV operands folded into a use"); |
Hongbin Zheng | d1b7b2e | 2017-09-27 03:11:46 +0000 | [diff] [blame] | 36 | STATISTIC(NumFoldedUser, "Number of IV users folded into a constant"); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 37 | STATISTIC(NumElimRem , "Number of IV remainder operations eliminated"); |
Hongbin Zheng | bfd7c38 | 2017-03-30 21:56:56 +0000 | [diff] [blame] | 38 | STATISTIC( |
| 39 | NumSimplifiedSDiv, |
| 40 | "Number of IV signed division operations converted to unsigned division"); |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 41 | STATISTIC( |
| 42 | NumSimplifiedSRem, |
| 43 | "Number of IV signed remainder operations converted to unsigned remainder"); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 44 | STATISTIC(NumElimCmp , "Number of IV comparisons eliminated"); |
| 45 | |
| 46 | namespace { |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 47 | /// This is a utility for simplifying induction variables |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 48 | /// based on ScalarEvolution. It is the primary instrument of the |
| 49 | /// IndvarSimplify pass, but it may also be directly invoked to cleanup after |
| 50 | /// other loop passes that preserve SCEV. |
| 51 | class SimplifyIndvar { |
| 52 | Loop *L; |
| 53 | LoopInfo *LI; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 54 | ScalarEvolution *SE; |
Sanjoy Das | 5c8bead | 2015-10-06 21:44:49 +0000 | [diff] [blame] | 55 | DominatorTree *DT; |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 56 | SCEVExpander &Rewriter; |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 57 | SmallVectorImpl<WeakTrackingVH> &DeadInsts; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 58 | |
| 59 | bool Changed; |
| 60 | |
| 61 | public: |
Sanjoy Das | 5c8bead | 2015-10-06 21:44:49 +0000 | [diff] [blame] | 62 | SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT, |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 63 | LoopInfo *LI, SCEVExpander &Rewriter, |
| 64 | SmallVectorImpl<WeakTrackingVH> &Dead) |
| 65 | : L(Loop), LI(LI), SE(SE), DT(DT), Rewriter(Rewriter), DeadInsts(Dead), |
| 66 | Changed(false) { |
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 |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 74 | /// all simplifications 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 | |
Sanjoy Das | 088bb0e | 2015-10-06 21:44:39 +0000 | [diff] [blame] | 79 | bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand); |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 80 | bool replaceIVUserWithLoopInvariant(Instruction *UseInst); |
Sanjoy Das | 088bb0e | 2015-10-06 21:44:39 +0000 | [diff] [blame] | 81 | |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 82 | bool eliminateOverflowIntrinsic(CallInst *CI); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 83 | bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand); |
Philip Reames | 7b861f0 | 2017-11-01 19:49:20 +0000 | [diff] [blame] | 84 | bool makeIVComparisonInvariant(ICmpInst *ICmp, Value *IVOperand); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 85 | void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand); |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 86 | void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand, |
| 87 | bool IsSigned); |
| 88 | void replaceRemWithNumerator(BinaryOperator *Rem); |
| 89 | void replaceRemWithNumeratorOrZero(BinaryOperator *Rem); |
| 90 | void replaceSRemWithURem(BinaryOperator *Rem); |
Hongbin Zheng | bfd7c38 | 2017-03-30 21:56:56 +0000 | [diff] [blame] | 91 | bool eliminateSDiv(BinaryOperator *SDiv); |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 92 | bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand); |
David Green | b26a0a4 | 2017-07-05 13:25:58 +0000 | [diff] [blame] | 93 | bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 94 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 95 | } |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 96 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 97 | /// Fold an IV operand into its use. This removes increments of an |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 98 | /// aligned IV when used by a instruction that ignores the low bits. |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 99 | /// |
Andrew Trick | 7251e41 | 2011-09-19 17:54:39 +0000 | [diff] [blame] | 100 | /// IVOperand is guaranteed SCEVable, but UseInst may not be. |
| 101 | /// |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 102 | /// Return the operand of IVOperand for this induction variable if IVOperand can |
Andrew Trick | 6dbb060 | 2011-08-10 18:07:05 +0000 | [diff] [blame] | 103 | /// be folded (in case more folding opportunities have been exposed). |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 104 | /// Otherwise return null. |
| 105 | Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 106 | Value *IVSrc = nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 107 | unsigned OperIdx = 0; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 108 | const SCEV *FoldedExpr = nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 109 | switch (UseInst->getOpcode()) { |
| 110 | default: |
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 | case Instruction::UDiv: |
| 113 | case Instruction::LShr: |
| 114 | // We're only interested in the case where we know something about |
| 115 | // the numerator and have a constant denominator. |
| 116 | if (IVOperand != UseInst->getOperand(OperIdx) || |
| 117 | !isa<ConstantInt>(UseInst->getOperand(1))) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 118 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 119 | |
| 120 | // Attempt to fold a binary operator with constant operand. |
| 121 | // e.g. ((I + 1) >> 2) => I >> 2 |
Andrew Trick | 9490458 | 2011-11-17 23:36:35 +0000 | [diff] [blame] | 122 | if (!isa<BinaryOperator>(IVOperand) |
| 123 | || !isa<ConstantInt>(IVOperand->getOperand(1))) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 124 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 125 | |
| 126 | IVSrc = IVOperand->getOperand(0); |
| 127 | // IVSrc must be the (SCEVable) IV, since the other operand is const. |
| 128 | assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand"); |
| 129 | |
| 130 | ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1)); |
| 131 | if (UseInst->getOpcode() == Instruction::LShr) { |
| 132 | // Get a constant for the divisor. See createSCEV. |
| 133 | uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth(); |
| 134 | if (D->getValue().uge(BitWidth)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 135 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 136 | |
| 137 | D = ConstantInt::get(UseInst->getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 138 | APInt::getOneBitSet(BitWidth, D->getZExtValue())); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 139 | } |
| 140 | FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D)); |
| 141 | } |
| 142 | // We have something that might fold it's operand. Compare SCEVs. |
| 143 | if (!SE->isSCEVable(UseInst->getType())) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 144 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 145 | |
| 146 | // Bypass the operand if SCEV can prove it has no effect. |
| 147 | if (SE->getSCEV(UseInst) != FoldedExpr) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 148 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 149 | |
| 150 | DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand |
| 151 | << " -> " << *UseInst << '\n'); |
| 152 | |
| 153 | UseInst->setOperand(OperIdx, IVSrc); |
| 154 | assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper"); |
| 155 | |
| 156 | ++NumElimOperand; |
| 157 | Changed = true; |
| 158 | if (IVOperand->use_empty()) |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 159 | DeadInsts.emplace_back(IVOperand); |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 160 | return IVSrc; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 161 | } |
| 162 | |
Philip Reames | 7b861f0 | 2017-11-01 19:49:20 +0000 | [diff] [blame] | 163 | bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp, |
| 164 | Value *IVOperand) { |
| 165 | unsigned IVOperIdx = 0; |
| 166 | ICmpInst::Predicate Pred = ICmp->getPredicate(); |
| 167 | if (IVOperand != ICmp->getOperand(0)) { |
| 168 | // Swapped |
| 169 | assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); |
| 170 | IVOperIdx = 1; |
| 171 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 172 | } |
Philip Reames | dc417a9 | 2017-10-31 18:04:57 +0000 | [diff] [blame] | 173 | |
Philip Reames | 7b861f0 | 2017-11-01 19:49:20 +0000 | [diff] [blame] | 174 | // Get the SCEVs for the ICmp operands (in the specific context of the |
| 175 | // current loop) |
| 176 | const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); |
| 177 | const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop); |
| 178 | const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop); |
| 179 | |
| 180 | ICmpInst::Predicate InvariantPredicate; |
Philip Reames | dc417a9 | 2017-10-31 18:04:57 +0000 | [diff] [blame] | 181 | const SCEV *InvariantLHS, *InvariantRHS; |
Philip Reames | 7b861f0 | 2017-11-01 19:49:20 +0000 | [diff] [blame] | 182 | |
| 183 | auto *PN = dyn_cast<PHINode>(IVOperand); |
| 184 | if (!PN) |
| 185 | return false; |
| 186 | if (!SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate, |
Philip Reames | dc417a9 | 2017-10-31 18:04:57 +0000 | [diff] [blame] | 187 | InvariantLHS, InvariantRHS)) |
| 188 | return false; |
| 189 | |
| 190 | // Rewrite the comparison to a loop invariant comparison if it can be done |
| 191 | // cheaply, where cheaply means "we don't need to emit any new |
| 192 | // instructions". |
Philip Reames | dc417a9 | 2017-10-31 18:04:57 +0000 | [diff] [blame] | 193 | |
Philip Reames | 7b861f0 | 2017-11-01 19:49:20 +0000 | [diff] [blame] | 194 | SmallDenseMap<const SCEV*, Value*> CheapExpansions; |
| 195 | CheapExpansions[S] = ICmp->getOperand(IVOperIdx); |
| 196 | CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx); |
| 197 | |
| 198 | // TODO: Support multiple entry loops? (We currently bail out of these in |
| 199 | // the IndVarSimplify pass) |
| 200 | if (auto *BB = L->getLoopPredecessor()) { |
Philip Reames | 6260cf7 | 2017-12-01 20:57:19 +0000 | [diff] [blame] | 201 | const int Idx = PN->getBasicBlockIndex(BB); |
| 202 | if (Idx >= 0) { |
| 203 | Value *Incoming = PN->getIncomingValue(Idx); |
| 204 | const SCEV *IncomingS = SE->getSCEV(Incoming); |
| 205 | CheapExpansions[IncomingS] = Incoming; |
| 206 | } |
Philip Reames | 7b861f0 | 2017-11-01 19:49:20 +0000 | [diff] [blame] | 207 | } |
| 208 | Value *NewLHS = CheapExpansions[InvariantLHS]; |
| 209 | Value *NewRHS = CheapExpansions[InvariantRHS]; |
| 210 | |
Philip Reames | 6260cf7 | 2017-12-01 20:57:19 +0000 | [diff] [blame] | 211 | if (!NewLHS) |
| 212 | if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS)) |
| 213 | NewLHS = ConstLHS->getValue(); |
| 214 | if (!NewRHS) |
| 215 | if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS)) |
| 216 | NewRHS = ConstRHS->getValue(); |
| 217 | |
Philip Reames | 7b861f0 | 2017-11-01 19:49:20 +0000 | [diff] [blame] | 218 | if (!NewLHS || !NewRHS) |
| 219 | // We could not find an existing value to replace either LHS or RHS. |
| 220 | // Generating new instructions has subtler tradeoffs, so avoid doing that |
| 221 | // for now. |
| 222 | return false; |
| 223 | |
| 224 | DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n'); |
| 225 | ICmp->setPredicate(InvariantPredicate); |
| 226 | ICmp->setOperand(0, NewLHS); |
| 227 | ICmp->setOperand(1, NewRHS); |
| 228 | return true; |
Philip Reames | dc417a9 | 2017-10-31 18:04:57 +0000 | [diff] [blame] | 229 | } |
| 230 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 231 | /// SimplifyIVUsers helper for eliminating useless |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 232 | /// comparisons against an induction variable. |
| 233 | void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) { |
| 234 | unsigned IVOperIdx = 0; |
| 235 | ICmpInst::Predicate Pred = ICmp->getPredicate(); |
Max Kazantsev | b9edcbc | 2017-07-08 17:17:30 +0000 | [diff] [blame] | 236 | ICmpInst::Predicate OriginalPred = Pred; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 237 | if (IVOperand != ICmp->getOperand(0)) { |
| 238 | // Swapped |
| 239 | assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); |
| 240 | IVOperIdx = 1; |
| 241 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 242 | } |
| 243 | |
Philip Reames | 29dd40b | 2017-10-26 22:02:16 +0000 | [diff] [blame] | 244 | // Get the SCEVs for the ICmp operands (in the specific context of the |
| 245 | // current loop) |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 246 | const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); |
Philip Reames | 29dd40b | 2017-10-26 22:02:16 +0000 | [diff] [blame] | 247 | const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop); |
| 248 | const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 249 | |
| 250 | // If the condition is always true or always false, replace it with |
| 251 | // a constant value. |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 252 | if (SE->isKnownPredicate(Pred, S, X)) { |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 253 | ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext())); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 254 | DeadInsts.emplace_back(ICmp); |
Sanjoy Das | c18115d | 2015-08-06 20:43:28 +0000 | [diff] [blame] | 255 | DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 256 | } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) { |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 257 | ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext())); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 258 | DeadInsts.emplace_back(ICmp); |
Sanjoy Das | c18115d | 2015-08-06 20:43:28 +0000 | [diff] [blame] | 259 | DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); |
Philip Reames | 7b861f0 | 2017-11-01 19:49:20 +0000 | [diff] [blame] | 260 | } else if (makeIVComparisonInvariant(ICmp, IVOperand)) { |
| 261 | // fallthrough to end of function |
Max Kazantsev | b9edcbc | 2017-07-08 17:17:30 +0000 | [diff] [blame] | 262 | } else if (ICmpInst::isSigned(OriginalPred) && |
| 263 | SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) { |
| 264 | // If we were unable to make anything above, all we can is to canonicalize |
| 265 | // the comparison hoping that it will open the doors for other |
| 266 | // optimizations. If we find out that we compare two non-negative values, |
| 267 | // we turn the instruction's predicate to its unsigned version. Note that |
| 268 | // we cannot rely on Pred here unless we check if we have swapped it. |
| 269 | assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?"); |
| 270 | DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp << '\n'); |
| 271 | ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred)); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 272 | } else |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 273 | return; |
| 274 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 275 | ++NumElimCmp; |
| 276 | Changed = true; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 277 | } |
| 278 | |
Hongbin Zheng | bfd7c38 | 2017-03-30 21:56:56 +0000 | [diff] [blame] | 279 | bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) { |
| 280 | // Get the SCEVs for the ICmp operands. |
| 281 | auto *N = SE->getSCEV(SDiv->getOperand(0)); |
| 282 | auto *D = SE->getSCEV(SDiv->getOperand(1)); |
| 283 | |
| 284 | // Simplify unnecessary loops away. |
| 285 | const Loop *L = LI->getLoopFor(SDiv->getParent()); |
| 286 | N = SE->getSCEVAtScope(N, L); |
| 287 | D = SE->getSCEVAtScope(D, L); |
| 288 | |
| 289 | // Replace sdiv by udiv if both of the operands are non-negative |
| 290 | if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) { |
| 291 | auto *UDiv = BinaryOperator::Create( |
| 292 | BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1), |
| 293 | SDiv->getName() + ".udiv", SDiv); |
| 294 | UDiv->setIsExact(SDiv->isExact()); |
| 295 | SDiv->replaceAllUsesWith(UDiv); |
| 296 | DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n'); |
| 297 | ++NumSimplifiedSDiv; |
| 298 | Changed = true; |
| 299 | DeadInsts.push_back(SDiv); |
| 300 | return true; |
| 301 | } |
| 302 | |
| 303 | return false; |
| 304 | } |
| 305 | |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 306 | // i %s n -> i %u n if i >= 0 and n >= 0 |
| 307 | void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) { |
| 308 | auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); |
| 309 | auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D, |
| 310 | Rem->getName() + ".urem", Rem); |
| 311 | Rem->replaceAllUsesWith(URem); |
| 312 | DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n'); |
| 313 | ++NumSimplifiedSRem; |
Hongbin Zheng | bbe448a | 2017-09-25 18:10:36 +0000 | [diff] [blame] | 314 | Changed = true; |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 315 | DeadInsts.emplace_back(Rem); |
| 316 | } |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 317 | |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 318 | // i % n --> i if i is in [0,n). |
| 319 | void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) { |
| 320 | Rem->replaceAllUsesWith(Rem->getOperand(0)); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 321 | DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); |
| 322 | ++NumElimRem; |
| 323 | Changed = true; |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 324 | DeadInsts.emplace_back(Rem); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 325 | } |
| 326 | |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 327 | // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n). |
| 328 | void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) { |
| 329 | auto *T = Rem->getType(); |
| 330 | auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); |
| 331 | ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D); |
| 332 | SelectInst *Sel = |
| 333 | SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem); |
| 334 | Rem->replaceAllUsesWith(Sel); |
| 335 | DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); |
| 336 | ++NumElimRem; |
| 337 | Changed = true; |
| 338 | DeadInsts.emplace_back(Rem); |
| 339 | } |
| 340 | |
| 341 | /// SimplifyIVUsers helper for eliminating useless remainder operations |
| 342 | /// operating on an induction variable or replacing srem by urem. |
| 343 | void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand, |
| 344 | bool IsSigned) { |
| 345 | auto *NValue = Rem->getOperand(0); |
| 346 | auto *DValue = Rem->getOperand(1); |
| 347 | // We're only interested in the case where we know something about |
| 348 | // the numerator, unless it is a srem, because we want to replace srem by urem |
| 349 | // in general. |
| 350 | bool UsedAsNumerator = IVOperand == NValue; |
| 351 | if (!UsedAsNumerator && !IsSigned) |
| 352 | return; |
| 353 | |
| 354 | const SCEV *N = SE->getSCEV(NValue); |
| 355 | |
| 356 | // Simplify unnecessary loops away. |
| 357 | const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent()); |
| 358 | N = SE->getSCEVAtScope(N, ICmpLoop); |
| 359 | |
| 360 | bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N); |
| 361 | |
| 362 | // Do not proceed if the Numerator may be negative |
| 363 | if (!IsNumeratorNonNegative) |
| 364 | return; |
| 365 | |
| 366 | const SCEV *D = SE->getSCEV(DValue); |
| 367 | D = SE->getSCEVAtScope(D, ICmpLoop); |
| 368 | |
| 369 | if (UsedAsNumerator) { |
| 370 | auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; |
| 371 | if (SE->isKnownPredicate(LT, N, D)) { |
| 372 | replaceRemWithNumerator(Rem); |
| 373 | return; |
| 374 | } |
| 375 | |
| 376 | auto *T = Rem->getType(); |
| 377 | const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T)); |
| 378 | if (SE->isKnownPredicate(LT, NLessOne, D)) { |
| 379 | replaceRemWithNumeratorOrZero(Rem); |
| 380 | return; |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | // Try to replace SRem with URem, if both N and D are known non-negative. |
| 385 | // Since we had already check N, we only need to check D now |
| 386 | if (!IsSigned || !SE->isKnownNonNegative(D)) |
| 387 | return; |
| 388 | |
| 389 | replaceSRemWithURem(Rem); |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 390 | } |
| 391 | |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 392 | bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) { |
| 393 | auto *F = CI->getCalledFunction(); |
| 394 | if (!F) |
| 395 | return false; |
| 396 | |
| 397 | typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)( |
Max Kazantsev | dc80366 | 2017-06-15 11:48:21 +0000 | [diff] [blame] | 398 | const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned); |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 399 | typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)( |
Max Kazantsev | 8d0322e | 2017-06-30 05:04:09 +0000 | [diff] [blame] | 400 | const SCEV *, Type *, unsigned); |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 401 | |
| 402 | OperationFunctionTy Operation; |
| 403 | ExtensionFunctionTy Extension; |
| 404 | |
| 405 | Instruction::BinaryOps RawOp; |
| 406 | |
| 407 | // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we |
| 408 | // have nuw. |
| 409 | bool NoSignedOverflow; |
| 410 | |
| 411 | switch (F->getIntrinsicID()) { |
| 412 | default: |
| 413 | return false; |
| 414 | |
| 415 | case Intrinsic::sadd_with_overflow: |
| 416 | Operation = &ScalarEvolution::getAddExpr; |
| 417 | Extension = &ScalarEvolution::getSignExtendExpr; |
| 418 | RawOp = Instruction::Add; |
| 419 | NoSignedOverflow = true; |
| 420 | break; |
| 421 | |
| 422 | case Intrinsic::uadd_with_overflow: |
| 423 | Operation = &ScalarEvolution::getAddExpr; |
| 424 | Extension = &ScalarEvolution::getZeroExtendExpr; |
| 425 | RawOp = Instruction::Add; |
| 426 | NoSignedOverflow = false; |
| 427 | break; |
| 428 | |
| 429 | case Intrinsic::ssub_with_overflow: |
| 430 | Operation = &ScalarEvolution::getMinusSCEV; |
| 431 | Extension = &ScalarEvolution::getSignExtendExpr; |
| 432 | RawOp = Instruction::Sub; |
| 433 | NoSignedOverflow = true; |
| 434 | break; |
| 435 | |
| 436 | case Intrinsic::usub_with_overflow: |
| 437 | Operation = &ScalarEvolution::getMinusSCEV; |
| 438 | Extension = &ScalarEvolution::getZeroExtendExpr; |
| 439 | RawOp = Instruction::Sub; |
| 440 | NoSignedOverflow = false; |
| 441 | break; |
| 442 | } |
| 443 | |
| 444 | const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0)); |
| 445 | const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1)); |
| 446 | |
| 447 | auto *NarrowTy = cast<IntegerType>(LHS->getType()); |
| 448 | auto *WideTy = |
| 449 | IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); |
| 450 | |
| 451 | const SCEV *A = |
Max Kazantsev | 8d0322e | 2017-06-30 05:04:09 +0000 | [diff] [blame] | 452 | (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), |
| 453 | WideTy, 0); |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 454 | const SCEV *B = |
Max Kazantsev | 8d0322e | 2017-06-30 05:04:09 +0000 | [diff] [blame] | 455 | (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0), |
| 456 | (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0); |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 457 | |
| 458 | if (A != B) |
| 459 | return false; |
| 460 | |
| 461 | // Proved no overflow, nuke the overflow check and, if possible, the overflow |
| 462 | // intrinsic as well. |
| 463 | |
| 464 | BinaryOperator *NewResult = BinaryOperator::Create( |
| 465 | RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI); |
| 466 | |
| 467 | if (NoSignedOverflow) |
| 468 | NewResult->setHasNoSignedWrap(true); |
| 469 | else |
| 470 | NewResult->setHasNoUnsignedWrap(true); |
| 471 | |
| 472 | SmallVector<ExtractValueInst *, 4> ToDelete; |
| 473 | |
| 474 | for (auto *U : CI->users()) { |
| 475 | if (auto *EVI = dyn_cast<ExtractValueInst>(U)) { |
| 476 | if (EVI->getIndices()[0] == 1) |
| 477 | EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext())); |
| 478 | else { |
| 479 | assert(EVI->getIndices()[0] == 0 && "Only two possibilities!"); |
| 480 | EVI->replaceAllUsesWith(NewResult); |
| 481 | } |
| 482 | ToDelete.push_back(EVI); |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | for (auto *EVI : ToDelete) |
| 487 | EVI->eraseFromParent(); |
| 488 | |
| 489 | if (CI->use_empty()) |
| 490 | CI->eraseFromParent(); |
| 491 | |
| 492 | return true; |
| 493 | } |
| 494 | |
Sanjoy Das | 088bb0e | 2015-10-06 21:44:39 +0000 | [diff] [blame] | 495 | /// Eliminate an operation that consumes a simple IV and has no observable |
| 496 | /// side-effect given the range of IV values. IVOperand is guaranteed SCEVable, |
| 497 | /// but UseInst may not be. |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 498 | bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst, |
| 499 | Instruction *IVOperand) { |
| 500 | if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) { |
| 501 | eliminateIVComparison(ICmp, IVOperand); |
| 502 | return true; |
| 503 | } |
Hongbin Zheng | bfd7c38 | 2017-03-30 21:56:56 +0000 | [diff] [blame] | 504 | if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) { |
| 505 | bool IsSRem = Bin->getOpcode() == Instruction::SRem; |
| 506 | if (IsSRem || Bin->getOpcode() == Instruction::URem) { |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 507 | simplifyIVRemainder(Bin, IVOperand, IsSRem); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 508 | return true; |
| 509 | } |
Hongbin Zheng | bfd7c38 | 2017-03-30 21:56:56 +0000 | [diff] [blame] | 510 | |
| 511 | if (Bin->getOpcode() == Instruction::SDiv) |
| 512 | return eliminateSDiv(Bin); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 513 | } |
| 514 | |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 515 | if (auto *CI = dyn_cast<CallInst>(UseInst)) |
| 516 | if (eliminateOverflowIntrinsic(CI)) |
| 517 | return true; |
| 518 | |
Sanjoy Das | 088bb0e | 2015-10-06 21:44:39 +0000 | [diff] [blame] | 519 | if (eliminateIdentitySCEV(UseInst, IVOperand)) |
| 520 | return true; |
| 521 | |
| 522 | return false; |
| 523 | } |
| 524 | |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 525 | static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) { |
| 526 | if (auto *BB = L->getLoopPreheader()) |
| 527 | return BB->getTerminator(); |
| 528 | |
| 529 | return Hint; |
| 530 | } |
| 531 | |
| 532 | /// Replace the UseInst with a constant if possible. |
| 533 | bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) { |
Hongbin Zheng | d1b7b2e | 2017-09-27 03:11:46 +0000 | [diff] [blame] | 534 | if (!SE->isSCEVable(I->getType())) |
| 535 | return false; |
| 536 | |
| 537 | // Get the symbolic expression for this instruction. |
| 538 | const SCEV *S = SE->getSCEV(I); |
| 539 | |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 540 | if (!SE->isLoopInvariant(S, L)) |
Hongbin Zheng | c8abdf5 | 2017-09-29 16:32:12 +0000 | [diff] [blame] | 541 | return false; |
Hongbin Zheng | d1b7b2e | 2017-09-27 03:11:46 +0000 | [diff] [blame] | 542 | |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 543 | // Do not generate something ridiculous even if S is loop invariant. |
| 544 | if (Rewriter.isHighCostExpansion(S, L, I)) |
Hongbin Zheng | c8abdf5 | 2017-09-29 16:32:12 +0000 | [diff] [blame] | 545 | return false; |
| 546 | |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 547 | auto *IP = GetLoopInvariantInsertPosition(L, I); |
| 548 | auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP); |
| 549 | |
| 550 | I->replaceAllUsesWith(Invariant); |
| 551 | DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I |
| 552 | << " with loop invariant: " << *S << '\n'); |
Hongbin Zheng | c8abdf5 | 2017-09-29 16:32:12 +0000 | [diff] [blame] | 553 | ++NumFoldedUser; |
| 554 | Changed = true; |
| 555 | DeadInsts.emplace_back(I); |
| 556 | return true; |
Hongbin Zheng | d1b7b2e | 2017-09-27 03:11:46 +0000 | [diff] [blame] | 557 | } |
| 558 | |
Sanjoy Das | 088bb0e | 2015-10-06 21:44:39 +0000 | [diff] [blame] | 559 | /// Eliminate any operation that SCEV can prove is an identity function. |
| 560 | bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst, |
| 561 | Instruction *IVOperand) { |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 562 | if (!SE->isSCEVable(UseInst->getType()) || |
| 563 | (UseInst->getType() != IVOperand->getType()) || |
| 564 | (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand))) |
| 565 | return false; |
| 566 | |
Sanjoy Das | 5c8bead | 2015-10-06 21:44:49 +0000 | [diff] [blame] | 567 | // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the |
| 568 | // dominator tree, even if X is an operand to Y. For instance, in |
| 569 | // |
| 570 | // %iv = phi i32 {0,+,1} |
| 571 | // br %cond, label %left, label %merge |
| 572 | // |
| 573 | // left: |
| 574 | // %X = add i32 %iv, 0 |
| 575 | // br label %merge |
| 576 | // |
| 577 | // merge: |
| 578 | // %M = phi (%X, %iv) |
| 579 | // |
| 580 | // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and |
| 581 | // %M.replaceAllUsesWith(%X) would be incorrect. |
| 582 | |
| 583 | if (isa<PHINode>(UseInst)) |
| 584 | // If UseInst is not a PHI node then we know that IVOperand dominates |
| 585 | // UseInst directly from the legality of SSA. |
| 586 | if (!DT || !DT->dominates(IVOperand, UseInst)) |
| 587 | return false; |
| 588 | |
Sanjoy Das | 0015e5a | 2015-10-07 17:38:31 +0000 | [diff] [blame] | 589 | if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand)) |
| 590 | return false; |
| 591 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 592 | DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n'); |
| 593 | |
| 594 | UseInst->replaceAllUsesWith(IVOperand); |
| 595 | ++NumElimIdentity; |
| 596 | Changed = true; |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 597 | DeadInsts.emplace_back(UseInst); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 598 | return true; |
| 599 | } |
| 600 | |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 601 | /// Annotate BO with nsw / nuw if it provably does not signed-overflow / |
| 602 | /// unsigned-overflow. Returns true if anything changed, false otherwise. |
| 603 | bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO, |
| 604 | Value *IVOperand) { |
| 605 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 606 | // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`. |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 607 | if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap()) |
| 608 | return false; |
| 609 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 610 | const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *, |
Max Kazantsev | dc80366 | 2017-06-15 11:48:21 +0000 | [diff] [blame] | 611 | SCEV::NoWrapFlags, unsigned); |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 612 | switch (BO->getOpcode()) { |
| 613 | default: |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 614 | return false; |
| 615 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 616 | case Instruction::Add: |
| 617 | GetExprForBO = &ScalarEvolution::getAddExpr; |
| 618 | break; |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 619 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 620 | case Instruction::Sub: |
| 621 | GetExprForBO = &ScalarEvolution::getMinusSCEV; |
| 622 | break; |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 623 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 624 | case Instruction::Mul: |
| 625 | GetExprForBO = &ScalarEvolution::getMulExpr; |
| 626 | break; |
| 627 | } |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 628 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 629 | unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth(); |
| 630 | Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2); |
| 631 | const SCEV *LHS = SE->getSCEV(BO->getOperand(0)); |
| 632 | const SCEV *RHS = SE->getSCEV(BO->getOperand(1)); |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 633 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 634 | bool Changed = false; |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 635 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 636 | if (!BO->hasNoUnsignedWrap()) { |
| 637 | const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy); |
| 638 | const SCEV *OpAfterExtend = (SE->*GetExprForBO)( |
| 639 | SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy), |
Max Kazantsev | dc80366 | 2017-06-15 11:48:21 +0000 | [diff] [blame] | 640 | SCEV::FlagAnyWrap, 0u); |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 641 | if (ExtendAfterOp == OpAfterExtend) { |
| 642 | BO->setHasNoUnsignedWrap(); |
| 643 | SE->forgetValue(BO); |
| 644 | Changed = true; |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 645 | } |
| 646 | } |
| 647 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 648 | if (!BO->hasNoSignedWrap()) { |
| 649 | const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy); |
| 650 | const SCEV *OpAfterExtend = (SE->*GetExprForBO)( |
| 651 | SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy), |
Max Kazantsev | dc80366 | 2017-06-15 11:48:21 +0000 | [diff] [blame] | 652 | SCEV::FlagAnyWrap, 0u); |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 653 | if (ExtendAfterOp == OpAfterExtend) { |
| 654 | BO->setHasNoSignedWrap(); |
| 655 | SE->forgetValue(BO); |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 656 | Changed = true; |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | return Changed; |
| 661 | } |
| 662 | |
David Green | b26a0a4 | 2017-07-05 13:25:58 +0000 | [diff] [blame] | 663 | /// Annotate the Shr in (X << IVOperand) >> C as exact using the |
| 664 | /// information from the IV's range. Returns true if anything changed, false |
| 665 | /// otherwise. |
| 666 | bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO, |
| 667 | Value *IVOperand) { |
| 668 | using namespace llvm::PatternMatch; |
| 669 | |
| 670 | if (BO->getOpcode() == Instruction::Shl) { |
| 671 | bool Changed = false; |
| 672 | ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand)); |
| 673 | for (auto *U : BO->users()) { |
| 674 | const APInt *C; |
| 675 | if (match(U, |
| 676 | m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) || |
| 677 | match(U, |
| 678 | m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) { |
| 679 | BinaryOperator *Shr = cast<BinaryOperator>(U); |
| 680 | if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) { |
| 681 | Shr->setIsExact(true); |
| 682 | Changed = true; |
| 683 | } |
| 684 | } |
| 685 | } |
| 686 | return Changed; |
| 687 | } |
| 688 | |
| 689 | return false; |
| 690 | } |
| 691 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 692 | /// Add all uses of Def to the current IV's worklist. |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 693 | static void pushIVUsers( |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 694 | Instruction *Def, Loop *L, |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 695 | SmallPtrSet<Instruction*,16> &Simplified, |
| 696 | SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) { |
| 697 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 698 | for (User *U : Def->users()) { |
| 699 | Instruction *UI = cast<Instruction>(U); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 700 | |
| 701 | // Avoid infinite or exponential worklist processing. |
| 702 | // Also ensure unique worklist users. |
| 703 | // If Def is a LoopPhi, it may not be in the Simplified set, so check for |
| 704 | // self edges first. |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 705 | if (UI == Def) |
| 706 | continue; |
| 707 | |
| 708 | // Only change the current Loop, do not change the other parts (e.g. other |
| 709 | // Loops). |
| 710 | if (!L->contains(UI)) |
| 711 | continue; |
| 712 | |
| 713 | // Do not push the same instruction more than once. |
| 714 | if (!Simplified.insert(UI).second) |
| 715 | continue; |
| 716 | |
| 717 | SimpleIVUsers.push_back(std::make_pair(UI, Def)); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 718 | } |
| 719 | } |
| 720 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 721 | /// Return true if this instruction generates a simple SCEV |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 722 | /// expression in terms of that IV. |
| 723 | /// |
Andrew Trick | 6dbb060 | 2011-08-10 18:07:05 +0000 | [diff] [blame] | 724 | /// This is similar to IVUsers' isInteresting() but processes each instruction |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 725 | /// non-recursively when the operand is already known to be a simpleIVUser. |
| 726 | /// |
| 727 | static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) { |
| 728 | if (!SE->isSCEVable(I->getType())) |
| 729 | return false; |
| 730 | |
| 731 | // Get the symbolic expression for this instruction. |
| 732 | const SCEV *S = SE->getSCEV(I); |
| 733 | |
| 734 | // Only consider affine recurrences. |
| 735 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); |
| 736 | if (AR && AR->getLoop() == L) |
| 737 | return true; |
| 738 | |
| 739 | return false; |
| 740 | } |
| 741 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 742 | /// Iteratively perform simplification on a worklist of users |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 743 | /// of the specified induction variable. Each successive simplification may push |
| 744 | /// more users which may themselves be candidates for simplification. |
| 745 | /// |
| 746 | /// This algorithm does not require IVUsers analysis. Instead, it simplifies |
| 747 | /// instructions in-place during analysis. Rather than rewriting induction |
| 748 | /// variables bottom-up from their users, it transforms a chain of IVUsers |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 749 | /// top-down, updating the IR only when it encounters a clear optimization |
| 750 | /// opportunity. |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 751 | /// |
| 752 | /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers. |
| 753 | /// |
| 754 | void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) { |
Andrew Trick | 7251e41 | 2011-09-19 17:54:39 +0000 | [diff] [blame] | 755 | if (!SE->isSCEVable(CurrIV->getType())) |
| 756 | return; |
| 757 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 758 | // Instructions processed by SimplifyIndvar for CurrIV. |
| 759 | SmallPtrSet<Instruction*,16> Simplified; |
| 760 | |
| 761 | // Use-def pairs if IV users waiting to be processed for CurrIV. |
| 762 | SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers; |
| 763 | |
| 764 | // Push users of the current LoopPhi. In rare cases, pushIVUsers may be |
| 765 | // called multiple times for the same LoopPhi. This is the proper thing to |
| 766 | // do for loop header phis that use each other. |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 767 | pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 768 | |
| 769 | while (!SimpleIVUsers.empty()) { |
| 770 | std::pair<Instruction*, Instruction*> UseOper = |
| 771 | SimpleIVUsers.pop_back_val(); |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 772 | Instruction *UseInst = UseOper.first; |
| 773 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 774 | // Bypass back edges to avoid extra work. |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 775 | if (UseInst == CurrIV) continue; |
| 776 | |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 777 | // Try to replace UseInst with a loop invariant before any other |
| 778 | // simplifications. |
| 779 | if (replaceIVUserWithLoopInvariant(UseInst)) |
Hongbin Zheng | d1b7b2e | 2017-09-27 03:11:46 +0000 | [diff] [blame] | 780 | continue; |
| 781 | |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 782 | Instruction *IVOperand = UseOper.second; |
| 783 | for (unsigned N = 0; IVOperand; ++N) { |
| 784 | assert(N <= Simplified.size() && "runaway iteration"); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 785 | |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 786 | Value *NewOper = foldIVUser(UseOper.first, IVOperand); |
| 787 | if (!NewOper) |
| 788 | break; // done folding |
| 789 | IVOperand = dyn_cast<Instruction>(NewOper); |
| 790 | } |
| 791 | if (!IVOperand) |
| 792 | continue; |
| 793 | |
| 794 | if (eliminateIVUser(UseOper.first, IVOperand)) { |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 795 | pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 796 | continue; |
| 797 | } |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 798 | |
| 799 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) { |
David Green | b26a0a4 | 2017-07-05 13:25:58 +0000 | [diff] [blame] | 800 | if ((isa<OverflowingBinaryOperator>(BO) && |
| 801 | strengthenOverflowingOperation(BO, IVOperand)) || |
| 802 | (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) { |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 803 | // re-queue uses of the now modified binary operator and fall |
| 804 | // through to the checks that remain. |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 805 | pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers); |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 806 | } |
| 807 | } |
| 808 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 809 | CastInst *Cast = dyn_cast<CastInst>(UseOper.first); |
| 810 | if (V && Cast) { |
| 811 | V->visitCast(Cast); |
| 812 | continue; |
| 813 | } |
| 814 | if (isSimpleIVUser(UseOper.first, L, SE)) { |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 815 | pushIVUsers(UseOper.first, L, Simplified, SimpleIVUsers); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 816 | } |
| 817 | } |
| 818 | } |
| 819 | |
| 820 | namespace llvm { |
| 821 | |
David Blaikie | a379b181 | 2011-12-20 02:50:00 +0000 | [diff] [blame] | 822 | void IVVisitor::anchor() { } |
| 823 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 824 | /// Simplify instructions that use this induction variable |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 825 | /// by using ScalarEvolution to analyze the IV's recurrence. |
Sanjoy Das | 5c8bead | 2015-10-06 21:44:49 +0000 | [diff] [blame] | 826 | bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 827 | LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead, |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 828 | SCEVExpander &Rewriter, IVVisitor *V) { |
| 829 | SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Rewriter, |
| 830 | Dead); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 831 | SIV.simplifyUsers(CurrIV, V); |
| 832 | return SIV.hasChanged(); |
| 833 | } |
| 834 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 835 | /// Simplify users of induction variables within this |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 836 | /// loop. This does not actually change or add IVs. |
Sanjoy Das | 5c8bead | 2015-10-06 21:44:49 +0000 | [diff] [blame] | 837 | bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 838 | LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) { |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 839 | SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars"); |
| 840 | #ifndef NDEBUG |
| 841 | Rewriter.setDebugType(DEBUG_TYPE); |
| 842 | #endif |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 843 | bool Changed = false; |
| 844 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 845 | Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead, Rewriter); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 846 | } |
| 847 | return Changed; |
| 848 | } |
| 849 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 850 | } // namespace llvm |