blob: ed227918055db50da6de4e77abf4bcce7fddb0b0 [file] [log] [blame]
Andrew Trick3ec331e2011-08-10 03:46:27 +00001//===-- 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 Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000020#include "llvm/Analysis/LoopInfo.h"
Hongbin Zhengd36f20302017-10-12 02:54:11 +000021#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Dominators.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000024#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Instructions.h"
David Greenb26a0a42017-07-05 13:25:58 +000026#include "llvm/IR/PatternMatch.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/raw_ostream.h"
Max Kazantsev0ed79622018-06-13 02:25:32 +000029#include "llvm/Transforms/Utils/Local.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000030
31using namespace llvm;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "indvars"
34
Andrew Trick3ec331e2011-08-10 03:46:27 +000035STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
36STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +000037STATISTIC(NumFoldedUser, "Number of IV users folded into a constant");
Andrew Trick3ec331e2011-08-10 03:46:27 +000038STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000039STATISTIC(
40 NumSimplifiedSDiv,
41 "Number of IV signed division operations converted to unsigned division");
Hongbin Zhengf0093e42017-09-25 17:39:40 +000042STATISTIC(
43 NumSimplifiedSRem,
44 "Number of IV signed remainder operations converted to unsigned remainder");
Andrew Trick3ec331e2011-08-10 03:46:27 +000045STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
46
47namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000048 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000049 /// based on ScalarEvolution. It is the primary instrument of the
50 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
51 /// other loop passes that preserve SCEV.
52 class SimplifyIndvar {
53 Loop *L;
54 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000055 ScalarEvolution *SE;
Sanjoy Das5c8bead2015-10-06 21:44:49 +000056 DominatorTree *DT;
Hongbin Zhengd36f20302017-10-12 02:54:11 +000057 SCEVExpander &Rewriter;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000058 SmallVectorImpl<WeakTrackingVH> &DeadInsts;
Andrew Trick3ec331e2011-08-10 03:46:27 +000059
60 bool Changed;
61
62 public:
Sanjoy Das5c8bead2015-10-06 21:44:49 +000063 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
Hongbin Zhengd36f20302017-10-12 02:54:11 +000064 LoopInfo *LI, SCEVExpander &Rewriter,
65 SmallVectorImpl<WeakTrackingVH> &Dead)
66 : L(Loop), LI(LI), SE(SE), DT(DT), Rewriter(Rewriter), DeadInsts(Dead),
67 Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000068 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000069 }
70
71 bool hasChanged() const { return Changed; }
72
73 /// Iteratively perform simplification on a worklist of users of the
74 /// specified induction variable. This is the top-level driver that applies
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000075 /// all simplifications to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000076 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000077
Andrew Trick74664d52011-08-10 04:01:31 +000078 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000079
Sanjoy Das088bb0e2015-10-06 21:44:39 +000080 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
Hongbin Zhengd36f20302017-10-12 02:54:11 +000081 bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
Sanjoy Das088bb0e2015-10-06 21:44:39 +000082
Sanjoy Dasae09b3c2016-05-29 00:36:25 +000083 bool eliminateOverflowIntrinsic(CallInst *CI);
Max Kazantsev37da4332018-06-19 04:48:34 +000084 bool eliminateTrunc(TruncInst *TI);
Andrew Trick3ec331e2011-08-10 03:46:27 +000085 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
Philip Reames7b861f02017-11-01 19:49:20 +000086 bool makeIVComparisonInvariant(ICmpInst *ICmp, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000087 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
Hongbin Zhengf0093e42017-09-25 17:39:40 +000088 void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
89 bool IsSigned);
90 void replaceRemWithNumerator(BinaryOperator *Rem);
91 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
92 void replaceSRemWithURem(BinaryOperator *Rem);
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000093 bool eliminateSDiv(BinaryOperator *SDiv);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000094 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
David Greenb26a0a42017-07-05 13:25:58 +000095 bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000096 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000097}
Andrew Trick3ec331e2011-08-10 03:46:27 +000098
Sanjay Patel7777b502014-11-12 18:07:42 +000099/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +0000100/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +0000101///
Andrew Trick7251e412011-09-19 17:54:39 +0000102/// IVOperand is guaranteed SCEVable, but UseInst may not be.
103///
Andrew Trick74664d52011-08-10 04:01:31 +0000104/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +0000105/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +0000106/// Otherwise return null.
107Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +0000108 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000109 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000110 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000111 switch (UseInst->getOpcode()) {
112 default:
Craig Topperf40110f2014-04-25 05:29:35 +0000113 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000114 case Instruction::UDiv:
115 case Instruction::LShr:
116 // We're only interested in the case where we know something about
117 // the numerator and have a constant denominator.
118 if (IVOperand != UseInst->getOperand(OperIdx) ||
119 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000120 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000121
122 // Attempt to fold a binary operator with constant operand.
123 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000124 if (!isa<BinaryOperator>(IVOperand)
125 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000126 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000127
128 IVSrc = IVOperand->getOperand(0);
129 // IVSrc must be the (SCEVable) IV, since the other operand is const.
130 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
131
132 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
133 if (UseInst->getOpcode() == Instruction::LShr) {
134 // Get a constant for the divisor. See createSCEV.
135 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
136 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000137 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000138
139 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000140 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000141 }
142 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
143 }
144 // We have something that might fold it's operand. Compare SCEVs.
145 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000146 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000147
148 // Bypass the operand if SCEV can prove it has no effect.
149 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000150 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000151
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000152 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
153 << " -> " << *UseInst << '\n');
Andrew Trick3ec331e2011-08-10 03:46:27 +0000154
155 UseInst->setOperand(OperIdx, IVSrc);
156 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
157
158 ++NumElimOperand;
159 Changed = true;
160 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000161 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000162 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000163}
164
Philip Reames7b861f02017-11-01 19:49:20 +0000165bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
166 Value *IVOperand) {
167 unsigned IVOperIdx = 0;
168 ICmpInst::Predicate Pred = ICmp->getPredicate();
169 if (IVOperand != ICmp->getOperand(0)) {
170 // Swapped
171 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
172 IVOperIdx = 1;
173 Pred = ICmpInst::getSwappedPredicate(Pred);
174 }
Philip Reamesdc417a92017-10-31 18:04:57 +0000175
Philip Reames7b861f02017-11-01 19:49:20 +0000176 // Get the SCEVs for the ICmp operands (in the specific context of the
177 // current loop)
178 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
179 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
180 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
181
182 ICmpInst::Predicate InvariantPredicate;
Philip Reamesdc417a92017-10-31 18:04:57 +0000183 const SCEV *InvariantLHS, *InvariantRHS;
Philip Reames7b861f02017-11-01 19:49:20 +0000184
185 auto *PN = dyn_cast<PHINode>(IVOperand);
186 if (!PN)
187 return false;
188 if (!SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
Philip Reamesdc417a92017-10-31 18:04:57 +0000189 InvariantLHS, InvariantRHS))
190 return false;
191
192 // Rewrite the comparison to a loop invariant comparison if it can be done
193 // cheaply, where cheaply means "we don't need to emit any new
194 // instructions".
Philip Reamesdc417a92017-10-31 18:04:57 +0000195
Philip Reames7b861f02017-11-01 19:49:20 +0000196 SmallDenseMap<const SCEV*, Value*> CheapExpansions;
197 CheapExpansions[S] = ICmp->getOperand(IVOperIdx);
198 CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx);
199
200 // TODO: Support multiple entry loops? (We currently bail out of these in
201 // the IndVarSimplify pass)
202 if (auto *BB = L->getLoopPredecessor()) {
Philip Reames6260cf72017-12-01 20:57:19 +0000203 const int Idx = PN->getBasicBlockIndex(BB);
204 if (Idx >= 0) {
205 Value *Incoming = PN->getIncomingValue(Idx);
206 const SCEV *IncomingS = SE->getSCEV(Incoming);
207 CheapExpansions[IncomingS] = Incoming;
208 }
Philip Reames7b861f02017-11-01 19:49:20 +0000209 }
210 Value *NewLHS = CheapExpansions[InvariantLHS];
211 Value *NewRHS = CheapExpansions[InvariantRHS];
212
Philip Reames6260cf72017-12-01 20:57:19 +0000213 if (!NewLHS)
214 if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS))
215 NewLHS = ConstLHS->getValue();
216 if (!NewRHS)
217 if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS))
218 NewRHS = ConstRHS->getValue();
219
Philip Reames7b861f02017-11-01 19:49:20 +0000220 if (!NewLHS || !NewRHS)
221 // We could not find an existing value to replace either LHS or RHS.
222 // Generating new instructions has subtler tradeoffs, so avoid doing that
223 // for now.
224 return false;
225
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000226 LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
Philip Reames7b861f02017-11-01 19:49:20 +0000227 ICmp->setPredicate(InvariantPredicate);
228 ICmp->setOperand(0, NewLHS);
229 ICmp->setOperand(1, NewRHS);
230 return true;
Philip Reamesdc417a92017-10-31 18:04:57 +0000231}
232
Sanjay Patel7777b502014-11-12 18:07:42 +0000233/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000234/// comparisons against an induction variable.
235void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
236 unsigned IVOperIdx = 0;
237 ICmpInst::Predicate Pred = ICmp->getPredicate();
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000238 ICmpInst::Predicate OriginalPred = Pred;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000239 if (IVOperand != ICmp->getOperand(0)) {
240 // Swapped
241 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
242 IVOperIdx = 1;
243 Pred = ICmpInst::getSwappedPredicate(Pred);
244 }
245
Philip Reames29dd40b2017-10-26 22:02:16 +0000246 // Get the SCEVs for the ICmp operands (in the specific context of the
247 // current loop)
Andrew Trick3ec331e2011-08-10 03:46:27 +0000248 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
Philip Reames29dd40b2017-10-26 22:02:16 +0000249 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
250 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000251
252 // If the condition is always true or always false, replace it with
253 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000254 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000255 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000256 DeadInsts.emplace_back(ICmp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000257 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000258 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000259 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000260 DeadInsts.emplace_back(ICmp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000261 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Philip Reames7b861f02017-11-01 19:49:20 +0000262 } else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
263 // fallthrough to end of function
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000264 } else if (ICmpInst::isSigned(OriginalPred) &&
265 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
266 // If we were unable to make anything above, all we can is to canonicalize
267 // the comparison hoping that it will open the doors for other
268 // optimizations. If we find out that we compare two non-negative values,
269 // we turn the instruction's predicate to its unsigned version. Note that
270 // we cannot rely on Pred here unless we check if we have swapped it.
271 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000272 LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp
273 << '\n');
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000274 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000275 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000276 return;
277
Andrew Trick3ec331e2011-08-10 03:46:27 +0000278 ++NumElimCmp;
279 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000280}
281
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000282bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
283 // Get the SCEVs for the ICmp operands.
284 auto *N = SE->getSCEV(SDiv->getOperand(0));
285 auto *D = SE->getSCEV(SDiv->getOperand(1));
286
287 // Simplify unnecessary loops away.
288 const Loop *L = LI->getLoopFor(SDiv->getParent());
289 N = SE->getSCEVAtScope(N, L);
290 D = SE->getSCEVAtScope(D, L);
291
292 // Replace sdiv by udiv if both of the operands are non-negative
293 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
294 auto *UDiv = BinaryOperator::Create(
295 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
296 SDiv->getName() + ".udiv", SDiv);
297 UDiv->setIsExact(SDiv->isExact());
298 SDiv->replaceAllUsesWith(UDiv);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000299 LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000300 ++NumSimplifiedSDiv;
301 Changed = true;
302 DeadInsts.push_back(SDiv);
303 return true;
304 }
305
306 return false;
307}
308
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000309// i %s n -> i %u n if i >= 0 and n >= 0
310void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
311 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
312 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
313 Rem->getName() + ".urem", Rem);
314 Rem->replaceAllUsesWith(URem);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000315 LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000316 ++NumSimplifiedSRem;
Hongbin Zhengbbe448a2017-09-25 18:10:36 +0000317 Changed = true;
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000318 DeadInsts.emplace_back(Rem);
319}
Andrew Trick3ec331e2011-08-10 03:46:27 +0000320
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000321// i % n --> i if i is in [0,n).
322void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
323 Rem->replaceAllUsesWith(Rem->getOperand(0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000324 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick3ec331e2011-08-10 03:46:27 +0000325 ++NumElimRem;
326 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000327 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000328}
329
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000330// (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
331void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
332 auto *T = Rem->getType();
333 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
334 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
335 SelectInst *Sel =
336 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
337 Rem->replaceAllUsesWith(Sel);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000338 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000339 ++NumElimRem;
340 Changed = true;
341 DeadInsts.emplace_back(Rem);
342}
343
344/// SimplifyIVUsers helper for eliminating useless remainder operations
345/// operating on an induction variable or replacing srem by urem.
346void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
347 bool IsSigned) {
348 auto *NValue = Rem->getOperand(0);
349 auto *DValue = Rem->getOperand(1);
350 // We're only interested in the case where we know something about
351 // the numerator, unless it is a srem, because we want to replace srem by urem
352 // in general.
353 bool UsedAsNumerator = IVOperand == NValue;
354 if (!UsedAsNumerator && !IsSigned)
355 return;
356
357 const SCEV *N = SE->getSCEV(NValue);
358
359 // Simplify unnecessary loops away.
360 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
361 N = SE->getSCEVAtScope(N, ICmpLoop);
362
363 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
364
365 // Do not proceed if the Numerator may be negative
366 if (!IsNumeratorNonNegative)
367 return;
368
369 const SCEV *D = SE->getSCEV(DValue);
370 D = SE->getSCEVAtScope(D, ICmpLoop);
371
372 if (UsedAsNumerator) {
373 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
374 if (SE->isKnownPredicate(LT, N, D)) {
375 replaceRemWithNumerator(Rem);
376 return;
377 }
378
379 auto *T = Rem->getType();
380 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
381 if (SE->isKnownPredicate(LT, NLessOne, D)) {
382 replaceRemWithNumeratorOrZero(Rem);
383 return;
384 }
385 }
386
387 // Try to replace SRem with URem, if both N and D are known non-negative.
388 // Since we had already check N, we only need to check D now
389 if (!IsSigned || !SE->isKnownNonNegative(D))
390 return;
391
392 replaceSRemWithURem(Rem);
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000393}
394
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000395bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
396 auto *F = CI->getCalledFunction();
397 if (!F)
398 return false;
399
400 typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
Max Kazantsevdc803662017-06-15 11:48:21 +0000401 const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000402 typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000403 const SCEV *, Type *, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000404
405 OperationFunctionTy Operation;
406 ExtensionFunctionTy Extension;
407
408 Instruction::BinaryOps RawOp;
409
410 // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we
411 // have nuw.
412 bool NoSignedOverflow;
413
414 switch (F->getIntrinsicID()) {
415 default:
416 return false;
417
418 case Intrinsic::sadd_with_overflow:
419 Operation = &ScalarEvolution::getAddExpr;
420 Extension = &ScalarEvolution::getSignExtendExpr;
421 RawOp = Instruction::Add;
422 NoSignedOverflow = true;
423 break;
424
425 case Intrinsic::uadd_with_overflow:
426 Operation = &ScalarEvolution::getAddExpr;
427 Extension = &ScalarEvolution::getZeroExtendExpr;
428 RawOp = Instruction::Add;
429 NoSignedOverflow = false;
430 break;
431
432 case Intrinsic::ssub_with_overflow:
433 Operation = &ScalarEvolution::getMinusSCEV;
434 Extension = &ScalarEvolution::getSignExtendExpr;
435 RawOp = Instruction::Sub;
436 NoSignedOverflow = true;
437 break;
438
439 case Intrinsic::usub_with_overflow:
440 Operation = &ScalarEvolution::getMinusSCEV;
441 Extension = &ScalarEvolution::getZeroExtendExpr;
442 RawOp = Instruction::Sub;
443 NoSignedOverflow = false;
444 break;
445 }
446
447 const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
448 const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
449
450 auto *NarrowTy = cast<IntegerType>(LHS->getType());
451 auto *WideTy =
452 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
453
454 const SCEV *A =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000455 (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
456 WideTy, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000457 const SCEV *B =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000458 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
459 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000460
461 if (A != B)
462 return false;
463
464 // Proved no overflow, nuke the overflow check and, if possible, the overflow
465 // intrinsic as well.
466
467 BinaryOperator *NewResult = BinaryOperator::Create(
468 RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
469
470 if (NoSignedOverflow)
471 NewResult->setHasNoSignedWrap(true);
472 else
473 NewResult->setHasNoUnsignedWrap(true);
474
475 SmallVector<ExtractValueInst *, 4> ToDelete;
476
477 for (auto *U : CI->users()) {
478 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
479 if (EVI->getIndices()[0] == 1)
480 EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
481 else {
482 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
483 EVI->replaceAllUsesWith(NewResult);
484 }
485 ToDelete.push_back(EVI);
486 }
487 }
488
489 for (auto *EVI : ToDelete)
490 EVI->eraseFromParent();
491
492 if (CI->use_empty())
493 CI->eraseFromParent();
494
495 return true;
496}
497
Max Kazantsev37da4332018-06-19 04:48:34 +0000498bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) {
499 // It is always legal to replace
500 // icmp <pred> i32 trunc(iv), n
501 // with
502 // icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate.
503 // Or with
504 // icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate.
505 // Or with either of these if pred is an equality predicate.
506 //
507 // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for
508 // every comparison which uses trunc, it means that we can replace each of
509 // them with comparison of iv against sext/zext(n). We no longer need trunc
510 // after that.
511 //
512 // TODO: Should we do this if we can widen *some* comparisons, but not all
513 // of them? Sometimes it is enough to enable other optimizations, but the
514 // trunc instruction will stay in the loop.
515 Value *IV = TI->getOperand(0);
516 Type *IVTy = IV->getType();
517 const SCEV *IVSCEV = SE->getSCEV(IV);
518 const SCEV *TISCEV = SE->getSCEV(TI);
519
520 // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can
521 // get rid of trunc
522 bool DoesSExtCollapse = false;
523 bool DoesZExtCollapse = false;
524 if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy))
525 DoesSExtCollapse = true;
526 if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy))
527 DoesZExtCollapse = true;
528
529 // If neither sext nor zext does collapse, it is not profitable to do any
530 // transform. Bail.
531 if (!DoesSExtCollapse && !DoesZExtCollapse)
532 return false;
533
534 // Collect users of the trunc that look like comparisons against invariants.
535 // Bail if we find something different.
536 SmallVector<ICmpInst *, 4> ICmpUsers;
537 for (auto *U : TI->users()) {
538 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) {
539 if (ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) {
540 assert(L->contains(ICI->getParent()) && "LCSSA form broken?");
541 // If we cannot get rid of trunc, bail.
542 if (ICI->isSigned() && !DoesSExtCollapse)
543 return false;
544 if (ICI->isUnsigned() && !DoesZExtCollapse)
545 return false;
546 // For equality, either signed or unsigned works.
547 ICmpUsers.push_back(ICI);
548 } else
549 return false;
550 } else
551 return false;
552 }
553
554 // Replace all comparisons against trunc with comparisons against IV.
555 for (auto *ICI : ICmpUsers) {
556 auto *Op1 = ICI->getOperand(1);
557 Instruction *Ext = nullptr;
558 // For signed/unsigned predicate, replace the old comparison with comparison
559 // of immediate IV against sext/zext of the invariant argument. If we can
560 // use either sext or zext (i.e. we are dealing with equality predicate),
561 // then prefer zext as a more canonical form.
562 // TODO: If we see a signed comparison which can be turned into unsigned,
563 // we can do it here for canonicalization purposes.
564 if (ICI->isUnsigned() || (ICI->isEquality() && DoesZExtCollapse)) {
565 assert(DoesZExtCollapse && "Unprofitable zext?");
566 Ext = new ZExtInst(Op1, IVTy, "zext", ICI);
567 } else {
568 assert(DoesSExtCollapse && "Unprofitable sext?");
569 Ext = new SExtInst(Op1, IVTy, "sext", ICI);
570 }
571 bool Changed;
572 L->makeLoopInvariant(Ext, Changed);
573 (void)Changed;
574 ICmpInst *NewICI = new ICmpInst(ICI, ICI->getPredicate(), IV, Ext);
575 ICI->replaceAllUsesWith(NewICI);
576 DeadInsts.emplace_back(ICI);
577 }
578
579 // Trunc no longer needed.
580 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
581 DeadInsts.emplace_back(TI);
582 return true;
583}
584
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000585/// Eliminate an operation that consumes a simple IV and has no observable
586/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
587/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000588bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
589 Instruction *IVOperand) {
590 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
591 eliminateIVComparison(ICmp, IVOperand);
592 return true;
593 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000594 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
595 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
596 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000597 simplifyIVRemainder(Bin, IVOperand, IsSRem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000598 return true;
599 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000600
601 if (Bin->getOpcode() == Instruction::SDiv)
602 return eliminateSDiv(Bin);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000603 }
604
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000605 if (auto *CI = dyn_cast<CallInst>(UseInst))
606 if (eliminateOverflowIntrinsic(CI))
607 return true;
608
Max Kazantsev37da4332018-06-19 04:48:34 +0000609 if (auto *TI = dyn_cast<TruncInst>(UseInst))
610 if (eliminateTrunc(TI))
611 return true;
612
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000613 if (eliminateIdentitySCEV(UseInst, IVOperand))
614 return true;
615
616 return false;
617}
618
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000619static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
620 if (auto *BB = L->getLoopPreheader())
621 return BB->getTerminator();
622
623 return Hint;
624}
625
626/// Replace the UseInst with a constant if possible.
627bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000628 if (!SE->isSCEVable(I->getType()))
629 return false;
630
631 // Get the symbolic expression for this instruction.
632 const SCEV *S = SE->getSCEV(I);
633
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000634 if (!SE->isLoopInvariant(S, L))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000635 return false;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000636
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000637 // Do not generate something ridiculous even if S is loop invariant.
638 if (Rewriter.isHighCostExpansion(S, L, I))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000639 return false;
640
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000641 auto *IP = GetLoopInvariantInsertPosition(L, I);
642 auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
643
644 I->replaceAllUsesWith(Invariant);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000645 LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
646 << " with loop invariant: " << *S << '\n');
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000647 ++NumFoldedUser;
648 Changed = true;
649 DeadInsts.emplace_back(I);
650 return true;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000651}
652
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000653/// Eliminate any operation that SCEV can prove is an identity function.
654bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
655 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000656 if (!SE->isSCEVable(UseInst->getType()) ||
657 (UseInst->getType() != IVOperand->getType()) ||
658 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
659 return false;
660
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000661 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
662 // dominator tree, even if X is an operand to Y. For instance, in
663 //
664 // %iv = phi i32 {0,+,1}
665 // br %cond, label %left, label %merge
666 //
667 // left:
668 // %X = add i32 %iv, 0
669 // br label %merge
670 //
671 // merge:
672 // %M = phi (%X, %iv)
673 //
674 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
675 // %M.replaceAllUsesWith(%X) would be incorrect.
676
677 if (isa<PHINode>(UseInst))
678 // If UseInst is not a PHI node then we know that IVOperand dominates
679 // UseInst directly from the legality of SSA.
680 if (!DT || !DT->dominates(IVOperand, UseInst))
681 return false;
682
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000683 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
684 return false;
685
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000686 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
Andrew Trick3ec331e2011-08-10 03:46:27 +0000687
688 UseInst->replaceAllUsesWith(IVOperand);
689 ++NumElimIdentity;
690 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000691 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000692 return true;
693}
694
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000695/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
696/// unsigned-overflow. Returns true if anything changed, false otherwise.
697bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
698 Value *IVOperand) {
699
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000700 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000701 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
702 return false;
703
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000704 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
Max Kazantsevdc803662017-06-15 11:48:21 +0000705 SCEV::NoWrapFlags, unsigned);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000706 switch (BO->getOpcode()) {
707 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000708 return false;
709
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000710 case Instruction::Add:
711 GetExprForBO = &ScalarEvolution::getAddExpr;
712 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000713
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000714 case Instruction::Sub:
715 GetExprForBO = &ScalarEvolution::getMinusSCEV;
716 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000717
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000718 case Instruction::Mul:
719 GetExprForBO = &ScalarEvolution::getMulExpr;
720 break;
721 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000722
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000723 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
724 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
725 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
726 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000727
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000728 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000729
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000730 if (!BO->hasNoUnsignedWrap()) {
731 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
732 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
733 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000734 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000735 if (ExtendAfterOp == OpAfterExtend) {
736 BO->setHasNoUnsignedWrap();
737 SE->forgetValue(BO);
738 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000739 }
740 }
741
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000742 if (!BO->hasNoSignedWrap()) {
743 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
744 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
745 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000746 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000747 if (ExtendAfterOp == OpAfterExtend) {
748 BO->setHasNoSignedWrap();
749 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000750 Changed = true;
751 }
752 }
753
754 return Changed;
755}
756
David Greenb26a0a42017-07-05 13:25:58 +0000757/// Annotate the Shr in (X << IVOperand) >> C as exact using the
758/// information from the IV's range. Returns true if anything changed, false
759/// otherwise.
760bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
761 Value *IVOperand) {
762 using namespace llvm::PatternMatch;
763
764 if (BO->getOpcode() == Instruction::Shl) {
765 bool Changed = false;
766 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
767 for (auto *U : BO->users()) {
768 const APInt *C;
769 if (match(U,
770 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
771 match(U,
772 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
773 BinaryOperator *Shr = cast<BinaryOperator>(U);
774 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
775 Shr->setIsExact(true);
776 Changed = true;
777 }
778 }
779 }
780 return Changed;
781 }
782
783 return false;
784}
785
Sanjay Patel7777b502014-11-12 18:07:42 +0000786/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000787static void pushIVUsers(
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000788 Instruction *Def, Loop *L,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000789 SmallPtrSet<Instruction*,16> &Simplified,
790 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
791
Chandler Carruthcdf47882014-03-09 03:16:01 +0000792 for (User *U : Def->users()) {
793 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000794
795 // Avoid infinite or exponential worklist processing.
796 // Also ensure unique worklist users.
797 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
798 // self edges first.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000799 if (UI == Def)
800 continue;
801
802 // Only change the current Loop, do not change the other parts (e.g. other
803 // Loops).
804 if (!L->contains(UI))
805 continue;
806
807 // Do not push the same instruction more than once.
808 if (!Simplified.insert(UI).second)
809 continue;
810
811 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000812 }
813}
814
Sanjay Patel7777b502014-11-12 18:07:42 +0000815/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000816/// expression in terms of that IV.
817///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000818/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000819/// non-recursively when the operand is already known to be a simpleIVUser.
820///
821static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
822 if (!SE->isSCEVable(I->getType()))
823 return false;
824
825 // Get the symbolic expression for this instruction.
826 const SCEV *S = SE->getSCEV(I);
827
828 // Only consider affine recurrences.
829 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
830 if (AR && AR->getLoop() == L)
831 return true;
832
833 return false;
834}
835
Sanjay Patel7777b502014-11-12 18:07:42 +0000836/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000837/// of the specified induction variable. Each successive simplification may push
838/// more users which may themselves be candidates for simplification.
839///
840/// This algorithm does not require IVUsers analysis. Instead, it simplifies
841/// instructions in-place during analysis. Rather than rewriting induction
842/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000843/// top-down, updating the IR only when it encounters a clear optimization
844/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000845///
846/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
847///
848void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000849 if (!SE->isSCEVable(CurrIV->getType()))
850 return;
851
Andrew Trick3ec331e2011-08-10 03:46:27 +0000852 // Instructions processed by SimplifyIndvar for CurrIV.
853 SmallPtrSet<Instruction*,16> Simplified;
854
855 // Use-def pairs if IV users waiting to be processed for CurrIV.
856 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
857
858 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
859 // called multiple times for the same LoopPhi. This is the proper thing to
860 // do for loop header phis that use each other.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000861 pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000862
863 while (!SimpleIVUsers.empty()) {
864 std::pair<Instruction*, Instruction*> UseOper =
865 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000866 Instruction *UseInst = UseOper.first;
867
Max Kazantsev0ed79622018-06-13 02:25:32 +0000868 // If a user of the IndVar is trivially dead, we prefer just to mark it dead
869 // rather than try to do some complex analysis or transformation (such as
870 // widening) basing on it.
871 // TODO: Propagate TLI and pass it here to handle more cases.
872 if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) {
873 DeadInsts.emplace_back(UseInst);
874 continue;
875 }
876
Andrew Trick3ec331e2011-08-10 03:46:27 +0000877 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000878 if (UseInst == CurrIV) continue;
879
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000880 // Try to replace UseInst with a loop invariant before any other
881 // simplifications.
882 if (replaceIVUserWithLoopInvariant(UseInst))
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000883 continue;
884
Andrew Trick74664d52011-08-10 04:01:31 +0000885 Instruction *IVOperand = UseOper.second;
886 for (unsigned N = 0; IVOperand; ++N) {
887 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000888
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000889 Value *NewOper = foldIVUser(UseInst, IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000890 if (!NewOper)
891 break; // done folding
892 IVOperand = dyn_cast<Instruction>(NewOper);
893 }
894 if (!IVOperand)
895 continue;
896
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000897 if (eliminateIVUser(UseInst, IVOperand)) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000898 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000899 continue;
900 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000901
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000902 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) {
David Greenb26a0a42017-07-05 13:25:58 +0000903 if ((isa<OverflowingBinaryOperator>(BO) &&
904 strengthenOverflowingOperation(BO, IVOperand)) ||
905 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000906 // re-queue uses of the now modified binary operator and fall
907 // through to the checks that remain.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000908 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000909 }
910 }
911
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000912 CastInst *Cast = dyn_cast<CastInst>(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000913 if (V && Cast) {
914 V->visitCast(Cast);
915 continue;
916 }
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000917 if (isSimpleIVUser(UseInst, L, SE)) {
918 pushIVUsers(UseInst, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000919 }
920 }
921}
922
923namespace llvm {
924
David Blaikiea379b1812011-12-20 02:50:00 +0000925void IVVisitor::anchor() { }
926
Sanjay Patel7777b502014-11-12 18:07:42 +0000927/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000928/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000929bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000930 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000931 SCEVExpander &Rewriter, IVVisitor *V) {
932 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Rewriter,
933 Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000934 SIV.simplifyUsers(CurrIV, V);
935 return SIV.hasChanged();
936}
937
Sanjay Patel7777b502014-11-12 18:07:42 +0000938/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000939/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000940bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000941 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000942 SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
943#ifndef NDEBUG
944 Rewriter.setDebugType(DEBUG_TYPE);
945#endif
Andrew Trick3ec331e2011-08-10 03:46:27 +0000946 bool Changed = false;
947 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000948 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead, Rewriter);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000949 }
950 return Changed;
951}
952
Andrew Trick3ec331e2011-08-10 03:46:27 +0000953} // namespace llvm