1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into simpler forms suitable for subsequent
12 // analysis and transformation.
14 // This transformation makes the following changes to each loop with an
15 // identifiable induction variable:
16 // 1. All loops are transformed to have a SINGLE canonical induction variable
17 // which starts at zero and steps by one.
18 // 2. The canonical induction variable is guaranteed to be the first PHI node
19 // in the loop header block.
20 // 3. The canonical induction variable is guaranteed to be in a wide enough
21 // type so that IV expressions need not be (directly) zero-extended or
23 // 4. Any pointer arithmetic recurrences are raised to use array subscripts.
25 // If the trip count of a loop is computable, this pass also makes the following
27 // 1. The exit condition for the loop is canonicalized to compare the
28 // induction value against the exit value. This turns loops like:
29 // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30 // 2. Any use outside of the loop of an expression derived from the indvar
31 // is changed to compute the derived value outside of the loop, eliminating
32 // the dependence on the exit value of the induction variable. If the only
33 // purpose of the loop is to compute the exit value of some derived
34 // expression, this transformation will make the loop dead.
36 // This transformation should be followed by strength reduction after all of the
37 // desired loop transformations have been performed.
39 //===----------------------------------------------------------------------===//
41 #define DEBUG_TYPE "indvars"
42 #include "llvm/Transforms/Scalar.h"
43 #include "llvm/BasicBlock.h"
44 #include "llvm/Constants.h"
45 #include "llvm/Instructions.h"
46 #include "llvm/IntrinsicInst.h"
47 #include "llvm/LLVMContext.h"
48 #include "llvm/Type.h"
49 #include "llvm/Analysis/Dominators.h"
50 #include "llvm/Analysis/IVUsers.h"
51 #include "llvm/Analysis/ScalarEvolutionExpander.h"
52 #include "llvm/Analysis/LoopInfo.h"
53 #include "llvm/Analysis/LoopPass.h"
54 #include "llvm/Support/CFG.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Utils/Local.h"
59 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
60 #include "llvm/Target/TargetData.h"
61 #include "llvm/ADT/DenseMap.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/ADT/Statistic.h"
64 #include "llvm/ADT/STLExtras.h"
67 STATISTIC(NumRemoved , "Number of aux indvars removed");
68 STATISTIC(NumWidened , "Number of indvars widened");
69 STATISTIC(NumInserted , "Number of canonical indvars added");
70 STATISTIC(NumReplaced , "Number of exit values replaced");
71 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
72 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
73 STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
74 STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
75 STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
76 STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
78 static cl::opt<bool> DisableIVRewrite(
79 "disable-iv-rewrite", cl::Hidden,
80 cl::desc("Disable canonical induction variable rewriting"));
82 // Temporary flag for use with -disable-iv-rewrite to force a canonical IV for
84 static cl::opt<bool> ForceLFTR(
85 "force-lftr", cl::Hidden,
86 cl::desc("Enable forced linear function test replacement"));
89 class IndVarSimplify : public LoopPass {
96 SmallVector<WeakVH, 16> DeadInsts;
100 static char ID; // Pass identification, replacement for typeid
101 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
103 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
106 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.addRequired<DominatorTree>();
110 AU.addRequired<LoopInfo>();
111 AU.addRequired<ScalarEvolution>();
112 AU.addRequiredID(LoopSimplifyID);
113 AU.addRequiredID(LCSSAID);
114 if (!DisableIVRewrite)
115 AU.addRequired<IVUsers>();
116 AU.addPreserved<ScalarEvolution>();
117 AU.addPreservedID(LoopSimplifyID);
118 AU.addPreservedID(LCSSAID);
119 if (!DisableIVRewrite)
120 AU.addPreserved<IVUsers>();
121 AU.setPreservesCFG();
125 virtual void releaseMemory() {
129 bool isValidRewrite(Value *FromVal, Value *ToVal);
131 void HandleFloatingPointIV(Loop *L, PHINode *PH);
132 void RewriteNonIntegerIVs(Loop *L);
134 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
136 void SimplifyIVUsers(SCEVExpander &Rewriter);
137 void SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter);
139 bool EliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
140 void EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
141 void EliminateIVRemainder(BinaryOperator *Rem,
145 void SimplifyCongruentIVs(Loop *L);
147 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
149 Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
150 PHINode *IndVar, SCEVExpander &Rewriter);
152 void SinkUnusedInvariants(Loop *L);
156 char IndVarSimplify::ID = 0;
157 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
158 "Induction Variable Simplification", false, false)
159 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
160 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
161 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
162 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
163 INITIALIZE_PASS_DEPENDENCY(LCSSA)
164 INITIALIZE_PASS_DEPENDENCY(IVUsers)
165 INITIALIZE_PASS_END(IndVarSimplify, "indvars",
166 "Induction Variable Simplification", false, false)
168 Pass *llvm::createIndVarSimplifyPass() {
169 return new IndVarSimplify();
172 /// isValidRewrite - Return true if the SCEV expansion generated by the
173 /// rewriter can replace the original value. SCEV guarantees that it
174 /// produces the same value, but the way it is produced may be illegal IR.
175 /// Ideally, this function will only be called for verification.
176 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
177 // If an SCEV expression subsumed multiple pointers, its expansion could
178 // reassociate the GEP changing the base pointer. This is illegal because the
179 // final address produced by a GEP chain must be inbounds relative to its
180 // underlying object. Otherwise basic alias analysis, among other things,
181 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
182 // producing an expression involving multiple pointers. Until then, we must
185 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
186 // because it understands lcssa phis while SCEV does not.
187 Value *FromPtr = FromVal;
188 Value *ToPtr = ToVal;
189 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
190 FromPtr = GEP->getPointerOperand();
192 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
193 ToPtr = GEP->getPointerOperand();
195 if (FromPtr != FromVal || ToPtr != ToVal) {
196 // Quickly check the common case
197 if (FromPtr == ToPtr)
200 // SCEV may have rewritten an expression that produces the GEP's pointer
201 // operand. That's ok as long as the pointer operand has the same base
202 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
203 // base of a recurrence. This handles the case in which SCEV expansion
204 // converts a pointer type recurrence into a nonrecurrent pointer base
205 // indexed by an integer recurrence.
206 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
207 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
208 if (FromBase == ToBase)
211 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
212 << *FromBase << " != " << *ToBase << "\n");
219 //===----------------------------------------------------------------------===//
220 // RewriteNonIntegerIVs and helpers. Prefer integer IVs.
221 //===----------------------------------------------------------------------===//
223 /// ConvertToSInt - Convert APF to an integer, if possible.
224 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
225 bool isExact = false;
226 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
228 // See if we can convert this to an int64_t
230 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
231 &isExact) != APFloat::opOK || !isExact)
237 /// HandleFloatingPointIV - If the loop has floating induction variable
238 /// then insert corresponding integer induction variable if possible.
240 /// for(double i = 0; i < 10000; ++i)
242 /// is converted into
243 /// for(int i = 0; i < 10000; ++i)
246 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
247 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
248 unsigned BackEdge = IncomingEdge^1;
250 // Check incoming value.
251 ConstantFP *InitValueVal =
252 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
255 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
258 // Check IV increment. Reject this PN if increment operation is not
259 // an add or increment value can not be represented by an integer.
260 BinaryOperator *Incr =
261 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
262 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
264 // If this is not an add of the PHI with a constantfp, or if the constant fp
265 // is not an integer, bail out.
266 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
268 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
269 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
272 // Check Incr uses. One user is PN and the other user is an exit condition
273 // used by the conditional terminator.
274 Value::use_iterator IncrUse = Incr->use_begin();
275 Instruction *U1 = cast<Instruction>(*IncrUse++);
276 if (IncrUse == Incr->use_end()) return;
277 Instruction *U2 = cast<Instruction>(*IncrUse++);
278 if (IncrUse != Incr->use_end()) return;
280 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
281 // only used by a branch, we can't transform it.
282 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
284 Compare = dyn_cast<FCmpInst>(U2);
285 if (Compare == 0 || !Compare->hasOneUse() ||
286 !isa<BranchInst>(Compare->use_back()))
289 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
291 // We need to verify that the branch actually controls the iteration count
292 // of the loop. If not, the new IV can overflow and no one will notice.
293 // The branch block must be in the loop and one of the successors must be out
295 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
296 if (!L->contains(TheBr->getParent()) ||
297 (L->contains(TheBr->getSuccessor(0)) &&
298 L->contains(TheBr->getSuccessor(1))))
302 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
304 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
306 if (ExitValueVal == 0 ||
307 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
310 // Find new predicate for integer comparison.
311 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
312 switch (Compare->getPredicate()) {
313 default: return; // Unknown comparison.
314 case CmpInst::FCMP_OEQ:
315 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
316 case CmpInst::FCMP_ONE:
317 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
318 case CmpInst::FCMP_OGT:
319 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
320 case CmpInst::FCMP_OGE:
321 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
322 case CmpInst::FCMP_OLT:
323 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
324 case CmpInst::FCMP_OLE:
325 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
328 // We convert the floating point induction variable to a signed i32 value if
329 // we can. This is only safe if the comparison will not overflow in a way
330 // that won't be trapped by the integer equivalent operations. Check for this
332 // TODO: We could use i64 if it is native and the range requires it.
334 // The start/stride/exit values must all fit in signed i32.
335 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
338 // If not actually striding (add x, 0.0), avoid touching the code.
342 // Positive and negative strides have different safety conditions.
344 // If we have a positive stride, we require the init to be less than the
345 // exit value and an equality or less than comparison.
346 if (InitValue >= ExitValue ||
347 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
350 uint32_t Range = uint32_t(ExitValue-InitValue);
351 if (NewPred == CmpInst::ICMP_SLE) {
352 // Normalize SLE -> SLT, check for infinite loop.
353 if (++Range == 0) return; // Range overflows.
356 unsigned Leftover = Range % uint32_t(IncValue);
358 // If this is an equality comparison, we require that the strided value
359 // exactly land on the exit value, otherwise the IV condition will wrap
360 // around and do things the fp IV wouldn't.
361 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
365 // If the stride would wrap around the i32 before exiting, we can't
367 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
371 // If we have a negative stride, we require the init to be greater than the
372 // exit value and an equality or greater than comparison.
373 if (InitValue >= ExitValue ||
374 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
377 uint32_t Range = uint32_t(InitValue-ExitValue);
378 if (NewPred == CmpInst::ICMP_SGE) {
379 // Normalize SGE -> SGT, check for infinite loop.
380 if (++Range == 0) return; // Range overflows.
383 unsigned Leftover = Range % uint32_t(-IncValue);
385 // If this is an equality comparison, we require that the strided value
386 // exactly land on the exit value, otherwise the IV condition will wrap
387 // around and do things the fp IV wouldn't.
388 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
392 // If the stride would wrap around the i32 before exiting, we can't
394 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
398 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
400 // Insert new integer induction variable.
401 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
402 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
403 PN->getIncomingBlock(IncomingEdge));
406 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
407 Incr->getName()+".int", Incr);
408 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
410 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
411 ConstantInt::get(Int32Ty, ExitValue),
414 // In the following deletions, PN may become dead and may be deleted.
415 // Use a WeakVH to observe whether this happens.
418 // Delete the old floating point exit comparison. The branch starts using the
420 NewCompare->takeName(Compare);
421 Compare->replaceAllUsesWith(NewCompare);
422 RecursivelyDeleteTriviallyDeadInstructions(Compare);
424 // Delete the old floating point increment.
425 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
426 RecursivelyDeleteTriviallyDeadInstructions(Incr);
428 // If the FP induction variable still has uses, this is because something else
429 // in the loop uses its value. In order to canonicalize the induction
430 // variable, we chose to eliminate the IV and rewrite it in terms of an
433 // We give preference to sitofp over uitofp because it is faster on most
436 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
437 PN->getParent()->getFirstNonPHI());
438 PN->replaceAllUsesWith(Conv);
439 RecursivelyDeleteTriviallyDeadInstructions(PN);
442 // Add a new IVUsers entry for the newly-created integer PHI.
444 IU->AddUsersIfInteresting(NewPHI);
447 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
448 // First step. Check to see if there are any floating-point recurrences.
449 // If there are, change them into integer recurrences, permitting analysis by
450 // the SCEV routines.
452 BasicBlock *Header = L->getHeader();
454 SmallVector<WeakVH, 8> PHIs;
455 for (BasicBlock::iterator I = Header->begin();
456 PHINode *PN = dyn_cast<PHINode>(I); ++I)
459 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
460 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
461 HandleFloatingPointIV(L, PN);
463 // If the loop previously had floating-point IV, ScalarEvolution
464 // may not have been able to compute a trip count. Now that we've done some
465 // re-writing, the trip count may be computable.
470 //===----------------------------------------------------------------------===//
471 // RewriteLoopExitValues - Optimize IV users outside the loop.
472 // As a side effect, reduces the amount of IV processing within the loop.
473 //===----------------------------------------------------------------------===//
475 /// RewriteLoopExitValues - Check to see if this loop has a computable
476 /// loop-invariant execution count. If so, this means that we can compute the
477 /// final value of any expressions that are recurrent in the loop, and
478 /// substitute the exit values from the loop into any instructions outside of
479 /// the loop that use the final values of the current expressions.
481 /// This is mostly redundant with the regular IndVarSimplify activities that
482 /// happen later, except that it's more powerful in some cases, because it's
483 /// able to brute-force evaluate arbitrary instructions as long as they have
484 /// constant operands at the beginning of the loop.
485 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
486 // Verify the input to the pass in already in LCSSA form.
487 assert(L->isLCSSAForm(*DT));
489 SmallVector<BasicBlock*, 8> ExitBlocks;
490 L->getUniqueExitBlocks(ExitBlocks);
492 // Find all values that are computed inside the loop, but used outside of it.
493 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
494 // the exit blocks of the loop to find them.
495 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
496 BasicBlock *ExitBB = ExitBlocks[i];
498 // If there are no PHI nodes in this exit block, then no values defined
499 // inside the loop are used on this path, skip it.
500 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
503 unsigned NumPreds = PN->getNumIncomingValues();
505 // Iterate over all of the PHI nodes.
506 BasicBlock::iterator BBI = ExitBB->begin();
507 while ((PN = dyn_cast<PHINode>(BBI++))) {
509 continue; // dead use, don't replace it
511 // SCEV only supports integer expressions for now.
512 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
515 // It's necessary to tell ScalarEvolution about this explicitly so that
516 // it can walk the def-use list and forget all SCEVs, as it may not be
517 // watching the PHI itself. Once the new exit value is in place, there
518 // may not be a def-use connection between the loop and every instruction
519 // which got a SCEVAddRecExpr for that loop.
522 // Iterate over all of the values in all the PHI nodes.
523 for (unsigned i = 0; i != NumPreds; ++i) {
524 // If the value being merged in is not integer or is not defined
525 // in the loop, skip it.
526 Value *InVal = PN->getIncomingValue(i);
527 if (!isa<Instruction>(InVal))
530 // If this pred is for a subloop, not L itself, skip it.
531 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
532 continue; // The Block is in a subloop, skip it.
534 // Check that InVal is defined in the loop.
535 Instruction *Inst = cast<Instruction>(InVal);
536 if (!L->contains(Inst))
539 // Okay, this instruction has a user outside of the current loop
540 // and varies predictably *inside* the loop. Evaluate the value it
541 // contains when the loop exits, if possible.
542 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
543 if (!SE->isLoopInvariant(ExitValue, L))
546 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
548 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
549 << " LoopVal = " << *Inst << "\n");
551 if (!isValidRewrite(Inst, ExitVal)) {
552 DeadInsts.push_back(ExitVal);
558 PN->setIncomingValue(i, ExitVal);
560 // If this instruction is dead now, delete it.
561 RecursivelyDeleteTriviallyDeadInstructions(Inst);
564 // Completely replace a single-pred PHI. This is safe, because the
565 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
567 PN->replaceAllUsesWith(ExitVal);
568 RecursivelyDeleteTriviallyDeadInstructions(PN);
572 // Clone the PHI and delete the original one. This lets IVUsers and
573 // any other maps purge the original user from their records.
574 PHINode *NewPN = cast<PHINode>(PN->clone());
576 NewPN->insertBefore(PN);
577 PN->replaceAllUsesWith(NewPN);
578 PN->eraseFromParent();
583 // The insertion point instruction may have been deleted; clear it out
584 // so that the rewriter doesn't trip over it later.
585 Rewriter.clearInsertPoint();
588 //===----------------------------------------------------------------------===//
589 // Rewrite IV users based on a canonical IV.
590 // To be replaced by -disable-iv-rewrite.
591 //===----------------------------------------------------------------------===//
593 /// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this
594 /// loop. IVUsers is treated as a worklist. Each successive simplification may
595 /// push more users which may themselves be candidates for simplification.
597 /// This is the old approach to IV simplification to be replaced by
598 /// SimplifyIVUsersNoRewrite.
600 void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) {
601 // Each round of simplification involves a round of eliminating operations
602 // followed by a round of widening IVs. A single IVUsers worklist is used
603 // across all rounds. The inner loop advances the user. If widening exposes
604 // more uses, then another pass through the outer loop is triggered.
605 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) {
606 Instruction *UseInst = I->getUser();
607 Value *IVOperand = I->getOperandValToReplace();
609 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
610 EliminateIVComparison(ICmp, IVOperand);
613 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
614 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
615 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
616 EliminateIVRemainder(Rem, IVOperand, IsSigned);
623 // FIXME: It is an extremely bad idea to indvar substitute anything more
624 // complex than affine induction variables. Doing so will put expensive
625 // polynomial evaluations inside of the loop, and the str reduction pass
626 // currently can only reduce affine polynomials. For now just disable
627 // indvar subst on anything more complex than an affine addrec, unless
628 // it can be expanded to a trivial value.
629 static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
630 // Loop-invariant values are safe.
631 if (SE->isLoopInvariant(S, L)) return true;
633 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
634 // to transform them into efficient code.
635 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
636 return AR->isAffine();
638 // An add is safe it all its operands are safe.
639 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
640 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
641 E = Commutative->op_end(); I != E; ++I)
642 if (!isSafe(*I, L, SE)) return false;
646 // A cast is safe if its operand is.
647 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
648 return isSafe(C->getOperand(), L, SE);
650 // A udiv is safe if its operands are.
651 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
652 return isSafe(UD->getLHS(), L, SE) &&
653 isSafe(UD->getRHS(), L, SE);
655 // SCEVUnknown is always safe.
656 if (isa<SCEVUnknown>(S))
659 // Nothing else is safe.
663 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
664 // Rewrite all induction variable expressions in terms of the canonical
665 // induction variable.
667 // If there were induction variables of other sizes or offsets, manually
668 // add the offsets to the primary induction variable and cast, avoiding
669 // the need for the code evaluation methods to insert induction variables
670 // of different sizes.
671 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
672 Value *Op = UI->getOperandValToReplace();
673 Type *UseTy = Op->getType();
674 Instruction *User = UI->getUser();
676 // Compute the final addrec to expand into code.
677 const SCEV *AR = IU->getReplacementExpr(*UI);
679 // Evaluate the expression out of the loop, if possible.
680 if (!L->contains(UI->getUser())) {
681 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
682 if (SE->isLoopInvariant(ExitVal, L))
686 // FIXME: It is an extremely bad idea to indvar substitute anything more
687 // complex than affine induction variables. Doing so will put expensive
688 // polynomial evaluations inside of the loop, and the str reduction pass
689 // currently can only reduce affine polynomials. For now just disable
690 // indvar subst on anything more complex than an affine addrec, unless
691 // it can be expanded to a trivial value.
692 if (!isSafe(AR, L, SE))
695 // Determine the insertion point for this user. By default, insert
696 // immediately before the user. The SCEVExpander class will automatically
697 // hoist loop invariants out of the loop. For PHI nodes, there may be
698 // multiple uses, so compute the nearest common dominator for the
700 Instruction *InsertPt = User;
701 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
702 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
703 if (PHI->getIncomingValue(i) == Op) {
704 if (InsertPt == User)
705 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
708 DT->findNearestCommonDominator(InsertPt->getParent(),
709 PHI->getIncomingBlock(i))
713 // Now expand it into actual Instructions and patch it into place.
714 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
716 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
717 << " into = " << *NewVal << "\n");
719 if (!isValidRewrite(Op, NewVal)) {
720 DeadInsts.push_back(NewVal);
723 // Inform ScalarEvolution that this value is changing. The change doesn't
724 // affect its value, but it does potentially affect which use lists the
725 // value will be on after the replacement, which affects ScalarEvolution's
726 // ability to walk use lists and drop dangling pointers when a value is
728 SE->forgetValue(User);
730 // Patch the new value into place.
732 NewVal->takeName(Op);
733 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
734 NewValI->setDebugLoc(User->getDebugLoc());
735 User->replaceUsesOfWith(Op, NewVal);
736 UI->setOperandValToReplace(NewVal);
741 // The old value may be dead now.
742 DeadInsts.push_back(Op);
746 //===----------------------------------------------------------------------===//
747 // IV Widening - Extend the width of an IV to cover its widest uses.
748 //===----------------------------------------------------------------------===//
751 // Collect information about induction variables that are used by sign/zero
752 // extend operations. This information is recorded by CollectExtend and
753 // provides the input to WidenIV.
755 Type *WidestNativeType; // Widest integer type created [sz]ext
756 bool IsSigned; // Was an sext user seen before a zext?
758 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
762 /// CollectExtend - Update information about the induction variable that is
763 /// extended by this sign or zero extend operation. This is used to determine
764 /// the final width of the IV before actually widening it.
765 static void CollectExtend(CastInst *Cast, bool IsSigned, WideIVInfo &WI,
766 ScalarEvolution *SE, const TargetData *TD) {
767 Type *Ty = Cast->getType();
768 uint64_t Width = SE->getTypeSizeInBits(Ty);
769 if (TD && !TD->isLegalInteger(Width))
772 if (!WI.WidestNativeType) {
773 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
774 WI.IsSigned = IsSigned;
778 // We extend the IV to satisfy the sign of its first user, arbitrarily.
779 if (WI.IsSigned != IsSigned)
782 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
783 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
788 /// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
789 /// WideIV that computes the same value as the Narrow IV def. This avoids
790 /// caching Use* pointers.
791 struct NarrowIVDefUse {
792 Instruction *NarrowDef;
793 Instruction *NarrowUse;
794 Instruction *WideDef;
796 NarrowIVDefUse(): NarrowDef(0), NarrowUse(0), WideDef(0) {}
798 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
799 NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
802 /// WidenIV - The goal of this transform is to remove sign and zero extends
803 /// without creating any new induction variables. To do this, it creates a new
804 /// phi of the wider type and redirects all users, either removing extends or
805 /// inserting truncs whenever we stop propagating the type.
821 Instruction *WideInc;
822 const SCEV *WideIncExpr;
823 SmallVectorImpl<WeakVH> &DeadInsts;
825 SmallPtrSet<Instruction*,16> Widened;
826 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
829 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
830 ScalarEvolution *SEv, DominatorTree *DTree,
831 SmallVectorImpl<WeakVH> &DI) :
833 WideType(WI.WidestNativeType),
834 IsSigned(WI.IsSigned),
836 L(LI->getLoopFor(OrigPhi->getParent())),
843 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
846 PHINode *CreateWideIV(SCEVExpander &Rewriter);
849 Instruction *CloneIVUser(NarrowIVDefUse DU);
851 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
853 Instruction *WidenIVUse(NarrowIVDefUse DU);
855 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
857 } // anonymous namespace
859 static Value *getExtend( Value *NarrowOper, Type *WideType,
860 bool IsSigned, IRBuilder<> &Builder) {
861 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
862 Builder.CreateZExt(NarrowOper, WideType);
865 /// CloneIVUser - Instantiate a wide operation to replace a narrow
866 /// operation. This only needs to handle operations that can evaluation to
867 /// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
868 Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
869 unsigned Opcode = DU.NarrowUse->getOpcode();
873 case Instruction::Add:
874 case Instruction::Mul:
875 case Instruction::UDiv:
876 case Instruction::Sub:
877 case Instruction::And:
878 case Instruction::Or:
879 case Instruction::Xor:
880 case Instruction::Shl:
881 case Instruction::LShr:
882 case Instruction::AShr:
883 DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
885 IRBuilder<> Builder(DU.NarrowUse);
887 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
888 // anything about the narrow operand yet so must insert a [sz]ext. It is
889 // probably loop invariant and will be folded or hoisted. If it actually
890 // comes from a widened IV, it should be removed during a future call to
892 Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
893 getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, Builder);
894 Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
895 getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, Builder);
897 BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
898 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
900 NarrowBO->getName());
901 Builder.Insert(WideBO);
902 if (const OverflowingBinaryOperator *OBO =
903 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
904 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
905 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
912 /// HoistStep - Attempt to hoist an IV increment above a potential use.
914 /// To successfully hoist, two criteria must be met:
915 /// - IncV operands dominate InsertPos and
916 /// - InsertPos dominates IncV
918 /// Meeting the second condition means that we don't need to check all of IncV's
919 /// existing uses (it's moving up in the domtree).
921 /// This does not yet recursively hoist the operands, although that would
922 /// not be difficult.
923 static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
924 const DominatorTree *DT)
926 if (DT->dominates(IncV, InsertPos))
929 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
932 if (IncV->mayHaveSideEffects())
935 // Attempt to hoist IncV
936 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
938 Instruction *OInst = dyn_cast<Instruction>(OI);
939 if (OInst && !DT->dominates(OInst, InsertPos))
942 IncV->moveBefore(InsertPos);
946 // GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
947 // perspective after widening it's type? In other words, can the extend be
948 // safely hoisted out of the loop with SCEV reducing the value to a recurrence
949 // on the same loop. If so, return the sign or zero extended
950 // recurrence. Otherwise return NULL.
951 const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
952 if (!SE->isSCEVable(NarrowUse->getType()))
955 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
956 if (SE->getTypeSizeInBits(NarrowExpr->getType())
957 >= SE->getTypeSizeInBits(WideType)) {
958 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
959 // index. So don't follow this use.
963 const SCEV *WideExpr = IsSigned ?
964 SE->getSignExtendExpr(NarrowExpr, WideType) :
965 SE->getZeroExtendExpr(NarrowExpr, WideType);
966 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
967 if (!AddRec || AddRec->getLoop() != L)
973 /// WidenIVUse - Determine whether an individual user of the narrow IV can be
974 /// widened. If so, return the wide clone of the user.
975 Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU) {
977 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
978 if (isa<PHINode>(DU.NarrowUse) &&
979 LI->getLoopFor(DU.NarrowUse->getParent()) != L)
982 // Our raison d'etre! Eliminate sign and zero extension.
983 if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
984 Value *NewDef = DU.WideDef;
985 if (DU.NarrowUse->getType() != WideType) {
986 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
987 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
988 if (CastWidth < IVWidth) {
989 // The cast isn't as wide as the IV, so insert a Trunc.
990 IRBuilder<> Builder(DU.NarrowUse);
991 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
994 // A wider extend was hidden behind a narrower one. This may induce
995 // another round of IV widening in which the intermediate IV becomes
996 // dead. It should be very rare.
997 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
998 << " not wide enough to subsume " << *DU.NarrowUse << "\n");
999 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1000 NewDef = DU.NarrowUse;
1003 if (NewDef != DU.NarrowUse) {
1004 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1005 << " replaced by " << *DU.WideDef << "\n");
1007 DU.NarrowUse->replaceAllUsesWith(NewDef);
1008 DeadInsts.push_back(DU.NarrowUse);
1010 // Now that the extend is gone, we want to expose it's uses for potential
1011 // further simplification. We don't need to directly inform SimplifyIVUsers
1012 // of the new users, because their parent IV will be processed later as a
1013 // new loop phi. If we preserved IVUsers analysis, we would also want to
1014 // push the uses of WideDef here.
1016 // No further widening is needed. The deceased [sz]ext had done it for us.
1020 // Does this user itself evaluate to a recurrence after widening?
1021 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
1023 // This user does not evaluate to a recurence after widening, so don't
1024 // follow it. Instead insert a Trunc to kill off the original use,
1025 // eventually isolating the original narrow IV so it can be removed.
1026 Use *U = std::find(DU.NarrowUse->op_begin(), DU.NarrowUse->op_end(),
1028 IRBuilder<> Builder(*U);
1029 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1030 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1033 // Assume block terminators cannot evaluate to a recurrence. We can't to
1034 // insert a Trunc after a terminator if there happens to be a critical edge.
1035 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1036 "SCEV is not expected to evaluate a block terminator");
1038 // Reuse the IV increment that SCEVExpander created as long as it dominates
1040 Instruction *WideUse = 0;
1041 if (WideAddRec == WideIncExpr && HoistStep(WideInc, DU.NarrowUse, DT)) {
1045 WideUse = CloneIVUser(DU);
1049 // Evaluation of WideAddRec ensured that the narrow expression could be
1050 // extended outside the loop without overflow. This suggests that the wide use
1051 // evaluates to the same expression as the extended narrow use, but doesn't
1052 // absolutely guarantee it. Hence the following failsafe check. In rare cases
1053 // where it fails, we simply throw away the newly created wide use.
1054 if (WideAddRec != SE->getSCEV(WideUse)) {
1055 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1056 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1057 DeadInsts.push_back(WideUse);
1061 // Returning WideUse pushes it on the worklist.
1065 /// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
1067 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1068 for (Value::use_iterator UI = NarrowDef->use_begin(),
1069 UE = NarrowDef->use_end(); UI != UE; ++UI) {
1070 Instruction *NarrowUse = cast<Instruction>(*UI);
1072 // Handle data flow merges and bizarre phi cycles.
1073 if (!Widened.insert(NarrowUse))
1076 NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUse, WideDef));
1080 /// CreateWideIV - Process a single induction variable. First use the
1081 /// SCEVExpander to create a wide induction variable that evaluates to the same
1082 /// recurrence as the original narrow IV. Then use a worklist to forward
1083 /// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
1084 /// interesting IV users, the narrow IV will be isolated for removal by
1087 /// It would be simpler to delete uses as they are processed, but we must avoid
1088 /// invalidating SCEV expressions.
1090 PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
1091 // Is this phi an induction variable?
1092 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1096 // Widen the induction variable expression.
1097 const SCEV *WideIVExpr = IsSigned ?
1098 SE->getSignExtendExpr(AddRec, WideType) :
1099 SE->getZeroExtendExpr(AddRec, WideType);
1101 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1102 "Expect the new IV expression to preserve its type");
1104 // Can the IV be extended outside the loop without overflow?
1105 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1106 if (!AddRec || AddRec->getLoop() != L)
1109 // An AddRec must have loop-invariant operands. Since this AddRec is
1110 // materialized by a loop header phi, the expression cannot have any post-loop
1111 // operands, so they must dominate the loop header.
1112 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1113 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1114 && "Loop header phi recurrence inputs do not dominate the loop");
1116 // The rewriter provides a value for the desired IV expression. This may
1117 // either find an existing phi or materialize a new one. Either way, we
1118 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1119 // of the phi-SCC dominates the loop entry.
1120 Instruction *InsertPt = L->getHeader()->begin();
1121 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1123 // Remembering the WideIV increment generated by SCEVExpander allows
1124 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
1125 // employ a general reuse mechanism because the call above is the only call to
1126 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
1127 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1129 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1130 WideIncExpr = SE->getSCEV(WideInc);
1133 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1136 // Traverse the def-use chain using a worklist starting at the original IV.
1137 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
1139 Widened.insert(OrigPhi);
1140 pushNarrowIVUsers(OrigPhi, WidePhi);
1142 while (!NarrowIVUsers.empty()) {
1143 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1145 // Process a def-use edge. This may replace the use, so don't hold a
1146 // use_iterator across it.
1147 Instruction *WideUse = WidenIVUse(DU);
1149 // Follow all def-use edges from the previous narrow use.
1151 pushNarrowIVUsers(DU.NarrowUse, WideUse);
1153 // WidenIVUse may have removed the def-use edge.
1154 if (DU.NarrowDef->use_empty())
1155 DeadInsts.push_back(DU.NarrowDef);
1160 //===----------------------------------------------------------------------===//
1161 // Simplification of IV users based on SCEV evaluation.
1162 //===----------------------------------------------------------------------===//
1164 void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
1165 unsigned IVOperIdx = 0;
1166 ICmpInst::Predicate Pred = ICmp->getPredicate();
1167 if (IVOperand != ICmp->getOperand(0)) {
1169 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
1171 Pred = ICmpInst::getSwappedPredicate(Pred);
1174 // Get the SCEVs for the ICmp operands.
1175 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
1176 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
1178 // Simplify unnecessary loops away.
1179 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
1180 S = SE->getSCEVAtScope(S, ICmpLoop);
1181 X = SE->getSCEVAtScope(X, ICmpLoop);
1183 // If the condition is always true or always false, replace it with
1184 // a constant value.
1185 if (SE->isKnownPredicate(Pred, S, X))
1186 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
1187 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
1188 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
1192 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
1195 DeadInsts.push_back(ICmp);
1198 void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
1201 // We're only interested in the case where we know something about
1203 if (IVOperand != Rem->getOperand(0))
1206 // Get the SCEVs for the ICmp operands.
1207 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
1208 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
1210 // Simplify unnecessary loops away.
1211 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
1212 S = SE->getSCEVAtScope(S, ICmpLoop);
1213 X = SE->getSCEVAtScope(X, ICmpLoop);
1215 // i % n --> i if i is in [0,n).
1216 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
1217 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1219 Rem->replaceAllUsesWith(Rem->getOperand(0));
1221 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
1222 const SCEV *LessOne =
1223 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
1224 if (IsSigned && !SE->isKnownNonNegative(LessOne))
1227 if (!SE->isKnownPredicate(IsSigned ?
1228 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1232 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
1233 Rem->getOperand(0), Rem->getOperand(1),
1236 SelectInst::Create(ICmp,
1237 ConstantInt::get(Rem->getType(), 0),
1238 Rem->getOperand(0), "tmp", Rem);
1239 Rem->replaceAllUsesWith(Sel);
1242 // Inform IVUsers about the new users.
1244 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
1245 IU->AddUsersIfInteresting(I);
1247 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
1250 DeadInsts.push_back(Rem);
1253 /// EliminateIVUser - Eliminate an operation that consumes a simple IV and has
1254 /// no observable side-effect given the range of IV values.
1255 bool IndVarSimplify::EliminateIVUser(Instruction *UseInst,
1256 Instruction *IVOperand) {
1257 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
1258 EliminateIVComparison(ICmp, IVOperand);
1261 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
1262 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
1263 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
1264 EliminateIVRemainder(Rem, IVOperand, IsSigned);
1269 // Eliminate any operation that SCEV can prove is an identity function.
1270 if (!SE->isSCEVable(UseInst->getType()) ||
1271 (UseInst->getType() != IVOperand->getType()) ||
1272 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
1275 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
1277 UseInst->replaceAllUsesWith(IVOperand);
1280 DeadInsts.push_back(UseInst);
1284 /// pushIVUsers - Add all uses of Def to the current IV's worklist.
1286 static void pushIVUsers(
1288 SmallPtrSet<Instruction*,16> &Simplified,
1289 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
1291 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
1293 Instruction *User = cast<Instruction>(*UI);
1295 // Avoid infinite or exponential worklist processing.
1296 // Also ensure unique worklist users.
1297 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
1298 // self edges first.
1299 if (User != Def && Simplified.insert(User))
1300 SimpleIVUsers.push_back(std::make_pair(User, Def));
1304 /// isSimpleIVUser - Return true if this instruction generates a simple SCEV
1305 /// expression in terms of that IV.
1307 /// This is similar to IVUsers' isInsteresting() but processes each instruction
1308 /// non-recursively when the operand is already known to be a simpleIVUser.
1310 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
1311 if (!SE->isSCEVable(I->getType()))
1314 // Get the symbolic expression for this instruction.
1315 const SCEV *S = SE->getSCEV(I);
1317 // Only consider affine recurrences.
1318 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
1319 if (AR && AR->getLoop() == L)
1325 /// SimplifyIVUsersNoRewrite - Iteratively perform simplification on a worklist
1326 /// of IV users. Each successive simplification may push more users which may
1327 /// themselves be candidates for simplification.
1329 /// The "NoRewrite" algorithm does not require IVUsers analysis. Instead, it
1330 /// simplifies instructions in-place during analysis. Rather than rewriting
1331 /// induction variables bottom-up from their users, it transforms a chain of
1332 /// IVUsers top-down, updating the IR only when it encouters a clear
1333 /// optimization opportunitiy. A SCEVExpander "Rewriter" instance is still
1334 /// needed, but only used to generate a new IV (phi) of wider type for sign/zero
1335 /// extend elimination.
1337 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
1339 void IndVarSimplify::SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter) {
1340 std::map<PHINode *, WideIVInfo> WideIVMap;
1342 SmallVector<PHINode*, 8> LoopPhis;
1343 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1344 LoopPhis.push_back(cast<PHINode>(I));
1346 // Each round of simplification iterates through the SimplifyIVUsers worklist
1347 // for all current phis, then determines whether any IVs can be
1348 // widened. Widening adds new phis to LoopPhis, inducing another round of
1349 // simplification on the wide IVs.
1350 while (!LoopPhis.empty()) {
1351 // Evaluate as many IV expressions as possible before widening any IVs. This
1352 // forces SCEV to set no-wrap flags before evaluating sign/zero
1353 // extension. The first time SCEV attempts to normalize sign/zero extension,
1354 // the result becomes final. So for the most predictable results, we delay
1355 // evaluation of sign/zero extend evaluation until needed, and avoid running
1356 // other SCEV based analysis prior to SimplifyIVUsersNoRewrite.
1358 PHINode *CurrIV = LoopPhis.pop_back_val();
1360 // Information about sign/zero extensions of CurrIV.
1363 // Instructions processed by SimplifyIVUsers for CurrIV.
1364 SmallPtrSet<Instruction*,16> Simplified;
1366 // Use-def pairs if IV users waiting to be processed for CurrIV.
1367 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
1369 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
1370 // called multiple times for the same LoopPhi. This is the proper thing to
1371 // do for loop header phis that use each other.
1372 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
1374 while (!SimpleIVUsers.empty()) {
1375 Instruction *UseInst, *Operand;
1376 tie(UseInst, Operand) = SimpleIVUsers.pop_back_val();
1377 // Bypass back edges to avoid extra work.
1378 if (UseInst == CurrIV) continue;
1380 if (EliminateIVUser(UseInst, Operand)) {
1381 pushIVUsers(Operand, Simplified, SimpleIVUsers);
1384 if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) {
1385 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
1386 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
1387 CollectExtend(Cast, IsSigned, WI, SE, TD);
1391 if (isSimpleIVUser(UseInst, L, SE)) {
1392 pushIVUsers(UseInst, Simplified, SimpleIVUsers);
1395 if (WI.WidestNativeType) {
1396 WideIVMap[CurrIV] = WI;
1398 } while(!LoopPhis.empty());
1400 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(),
1401 E = WideIVMap.end(); I != E; ++I) {
1402 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts);
1403 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1405 LoopPhis.push_back(WidePhi);
1412 /// SimplifyCongruentIVs - Check for congruent phis in this loop header and
1413 /// populate ExprToIVMap for use later.
1415 void IndVarSimplify::SimplifyCongruentIVs(Loop *L) {
1416 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1417 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1418 PHINode *Phi = cast<PHINode>(I);
1419 if (!SE->isSCEVable(Phi->getType()))
1422 const SCEV *S = SE->getSCEV(Phi);
1423 DenseMap<const SCEV *, PHINode *>::const_iterator Pos;
1425 tie(Pos, Inserted) = ExprToIVMap.insert(std::make_pair(S, Phi));
1428 PHINode *OrigPhi = Pos->second;
1430 // If one phi derives from the other via GEPs, types may differ.
1431 if (OrigPhi->getType() != Phi->getType())
1434 // Replacing the congruent phi is sufficient because acyclic redundancy
1435 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1436 // that a phi is congruent, it's almost certain to be the head of an IV
1437 // user cycle that is isomorphic with the original phi. So it's worth
1438 // eagerly cleaning up the common case of a single IV increment.
1439 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1440 Instruction *OrigInc =
1441 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1442 Instruction *IsomorphicInc =
1443 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1444 if (OrigInc != IsomorphicInc &&
1445 OrigInc->getType() == IsomorphicInc->getType() &&
1446 SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) &&
1447 HoistStep(OrigInc, IsomorphicInc, DT)) {
1448 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1449 << *IsomorphicInc << '\n');
1450 IsomorphicInc->replaceAllUsesWith(OrigInc);
1451 DeadInsts.push_back(IsomorphicInc);
1454 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1456 Phi->replaceAllUsesWith(OrigPhi);
1457 DeadInsts.push_back(Phi);
1461 //===----------------------------------------------------------------------===//
1462 // LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1463 //===----------------------------------------------------------------------===//
1465 // Check for expressions that ScalarEvolution generates to compute
1466 // BackedgeTakenInfo. If these expressions have not been reduced, then expanding
1467 // them may incur additional cost (albeit in the loop preheader).
1468 static bool isHighCostExpansion(const SCEV *S, BranchInst *BI,
1469 ScalarEvolution *SE) {
1470 // If the backedge-taken count is a UDiv, it's very likely a UDiv that
1471 // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a
1472 // precise expression, rather than a UDiv from the user's code. If we can't
1473 // find a UDiv in the code with some simple searching, assume the former and
1474 // forego rewriting the loop.
1475 if (isa<SCEVUDivExpr>(S)) {
1476 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
1477 if (!OrigCond) return true;
1478 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
1479 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
1481 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
1482 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
1488 if (!DisableIVRewrite || ForceLFTR)
1491 // Recurse past add expressions, which commonly occur in the
1492 // BackedgeTakenCount. They may already exist in program code, and if not,
1493 // they are not too expensive rematerialize.
1494 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1495 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1497 if (isHighCostExpansion(*I, BI, SE))
1503 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1504 // the exit condition.
1505 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1508 // If we haven't recognized an expensive SCEV patter, assume its an expression
1509 // produced by program code.
1513 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1514 /// count expression can be safely and cheaply expanded into an instruction
1515 /// sequence that can be used by LinearFunctionTestReplace.
1516 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
1517 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1518 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1519 BackedgeTakenCount->isZero())
1522 if (!L->getExitingBlock())
1525 // Can't rewrite non-branch yet.
1526 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1530 if (isHighCostExpansion(BackedgeTakenCount, BI, SE))
1536 /// getBackedgeIVType - Get the widest type used by the loop test after peeking
1539 /// TODO: Unnecessary when ForceLFTR is removed.
1540 static Type *getBackedgeIVType(Loop *L) {
1541 if (!L->getExitingBlock())
1544 // Can't rewrite non-branch yet.
1545 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1549 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1554 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
1556 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
1557 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
1561 return Trunc->getSrcTy();
1566 /// isLoopInvariant - Perform a quick domtree based check for loop invariance
1567 /// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
1568 /// gratuitous for this purpose.
1569 static bool isLoopInvariant(Value *V, Loop *L, DominatorTree *DT) {
1570 Instruction *Inst = dyn_cast<Instruction>(V);
1574 return DT->properlyDominates(Inst->getParent(), L->getHeader());
1577 /// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
1578 /// invariant value to the phi.
1579 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1580 Instruction *IncI = dyn_cast<Instruction>(IncV);
1584 switch (IncI->getOpcode()) {
1585 case Instruction::Add:
1586 case Instruction::Sub:
1588 case Instruction::GetElementPtr:
1589 // An IV counter must preserve its type.
1590 if (IncI->getNumOperands() == 2)
1596 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1597 if (Phi && Phi->getParent() == L->getHeader()) {
1598 if (isLoopInvariant(IncI->getOperand(1), L, DT))
1602 if (IncI->getOpcode() == Instruction::GetElementPtr)
1605 // Allow add/sub to be commuted.
1606 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1607 if (Phi && Phi->getParent() == L->getHeader()) {
1608 if (isLoopInvariant(IncI->getOperand(0), L, DT))
1614 /// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
1615 /// that the current exit test is already sufficiently canonical.
1616 static bool needsLFTR(Loop *L, DominatorTree *DT) {
1617 assert(L->getExitingBlock() && "expected loop exit");
1619 BasicBlock *LatchBlock = L->getLoopLatch();
1620 // Don't bother with LFTR if the loop is not properly simplified.
1624 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1625 assert(BI && "expected exit branch");
1627 // Do LFTR to simplify the exit condition to an ICMP.
1628 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1632 // Do LFTR to simplify the exit ICMP to EQ/NE
1633 ICmpInst::Predicate Pred = Cond->getPredicate();
1634 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1637 // Look for a loop invariant RHS
1638 Value *LHS = Cond->getOperand(0);
1639 Value *RHS = Cond->getOperand(1);
1640 if (!isLoopInvariant(RHS, L, DT)) {
1641 if (!isLoopInvariant(LHS, L, DT))
1643 std::swap(LHS, RHS);
1645 // Look for a simple IV counter LHS
1646 PHINode *Phi = dyn_cast<PHINode>(LHS);
1648 Phi = getLoopPhiForCounter(LHS, L, DT);
1653 // Do LFTR if the exit condition's IV is *not* a simple counter.
1654 Value *IncV = Phi->getIncomingValueForBlock(L->getLoopLatch());
1655 return Phi != getLoopPhiForCounter(IncV, L, DT);
1658 /// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
1659 /// be rewritten) loop exit test.
1660 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1661 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1662 Value *IncV = Phi->getIncomingValue(LatchIdx);
1664 for (Value::use_iterator UI = Phi->use_begin(), UE = Phi->use_end();
1666 if (*UI != Cond && *UI != IncV) return false;
1669 for (Value::use_iterator UI = IncV->use_begin(), UE = IncV->use_end();
1671 if (*UI != Cond && *UI != Phi) return false;
1676 /// FindLoopCounter - Find an affine IV in canonical form.
1678 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
1680 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
1681 /// This is difficult in general for SCEV because of potential overflow. But we
1682 /// could at least handle constant BECounts.
1684 FindLoopCounter(Loop *L, const SCEV *BECount,
1685 ScalarEvolution *SE, DominatorTree *DT, const TargetData *TD) {
1686 // I'm not sure how BECount could be a pointer type, but we definitely don't
1687 // want to LFTR that.
1688 if (BECount->getType()->isPointerTy())
1691 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
1694 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
1696 // Loop over all of the PHI nodes, looking for a simple counter.
1697 PHINode *BestPhi = 0;
1698 const SCEV *BestInit = 0;
1699 BasicBlock *LatchBlock = L->getLoopLatch();
1700 assert(LatchBlock && "needsLFTR should guarantee a loop latch");
1702 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1703 PHINode *Phi = cast<PHINode>(I);
1704 if (!SE->isSCEVable(Phi->getType()))
1707 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
1708 if (!AR || AR->getLoop() != L || !AR->isAffine())
1711 // AR may be a pointer type, while BECount is an integer type.
1712 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
1713 // AR may not be a narrower type, or we may never exit.
1714 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
1715 if (PhiWidth < BCWidth || (TD && !TD->isLegalInteger(PhiWidth)))
1718 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
1719 if (!Step || !Step->isOne())
1722 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1723 Value *IncV = Phi->getIncomingValue(LatchIdx);
1724 if (getLoopPhiForCounter(IncV, L, DT) != Phi)
1727 const SCEV *Init = AR->getStart();
1729 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
1730 // Don't force a live loop counter if another IV can be used.
1731 if (AlmostDeadIV(Phi, LatchBlock, Cond))
1734 // Prefer to count-from-zero. This is a more "canonical" counter form. It
1735 // also prefers integer to pointer IVs.
1736 if (BestInit->isZero() != Init->isZero()) {
1737 if (BestInit->isZero())
1740 // If two IVs both count from zero or both count from nonzero then the
1741 // narrower is likely a dead phi that has been widened. Use the wider phi
1742 // to allow the other to be eliminated.
1743 if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
1752 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
1753 /// loop to be a canonical != comparison against the incremented loop induction
1754 /// variable. This pass is able to rewrite the exit tests of any loop where the
1755 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
1756 /// is actually a much broader range than just linear tests.
1757 Value *IndVarSimplify::
1758 LinearFunctionTestReplace(Loop *L,
1759 const SCEV *BackedgeTakenCount,
1761 SCEVExpander &Rewriter) {
1762 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
1763 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1765 // In DisableIVRewrite mode, IndVar is not necessarily a canonical IV. In this
1766 // mode, LFTR can ignore IV overflow and truncate to the width of
1767 // BECount. This avoids materializing the add(zext(add)) expression.
1768 Type *CntTy = DisableIVRewrite ?
1769 BackedgeTakenCount->getType() : IndVar->getType();
1771 const SCEV *IVLimit = BackedgeTakenCount;
1773 // If the exiting block is not the same as the backedge block, we must compare
1774 // against the preincremented value, otherwise we prefer to compare against
1775 // the post-incremented value.
1777 if (L->getExitingBlock() == L->getLoopLatch()) {
1778 // Add one to the "backedge-taken" count to get the trip count.
1779 // If this addition may overflow, we have to be more pessimistic and
1780 // cast the induction variable before doing the add.
1782 SE->getAddExpr(IVLimit, SE->getConstant(IVLimit->getType(), 1));
1783 if (CntTy == IVLimit->getType())
1786 const SCEV *Zero = SE->getConstant(IVLimit->getType(), 0);
1787 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
1788 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
1789 // No overflow. Cast the sum.
1790 IVLimit = SE->getTruncateOrZeroExtend(N, CntTy);
1792 // Potential overflow. Cast before doing the add.
1793 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
1794 IVLimit = SE->getAddExpr(IVLimit, SE->getConstant(CntTy, 1));
1797 // The BackedgeTaken expression contains the number of times that the
1798 // backedge branches to the loop header. This is one less than the
1799 // number of times the loop executes, so use the incremented indvar.
1800 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1802 // We have to use the preincremented value...
1803 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
1807 // For unit stride, IVLimit = Start + BECount with 2's complement overflow.
1808 // So for, non-zero start compute the IVLimit here.
1809 bool isPtrIV = false;
1810 Type *CmpTy = CntTy;
1811 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1812 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
1813 if (!AR->getStart()->isZero()) {
1814 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
1815 const SCEV *IVInit = AR->getStart();
1817 // For pointer types, sign extend BECount in order to materialize a GEP.
1818 // Note that for DisableIVRewrite, we never run SCEVExpander on a
1819 // pointer type, because we must preserve the existing GEPs. Instead we
1820 // directly generate a GEP later.
1821 if (IVInit->getType()->isPointerTy()) {
1823 CmpTy = SE->getEffectiveSCEVType(IVInit->getType());
1824 IVLimit = SE->getTruncateOrSignExtend(IVLimit, CmpTy);
1826 // For integer types, truncate the IV before computing IVInit + BECount.
1828 if (SE->getTypeSizeInBits(IVInit->getType())
1829 > SE->getTypeSizeInBits(CmpTy))
1830 IVInit = SE->getTruncateExpr(IVInit, CmpTy);
1832 IVLimit = SE->getAddExpr(IVInit, IVLimit);
1835 // Expand the code for the iteration count.
1836 IRBuilder<> Builder(BI);
1838 assert(SE->isLoopInvariant(IVLimit, L) &&
1839 "Computed iteration count is not loop invariant!");
1840 Value *ExitCnt = Rewriter.expandCodeFor(IVLimit, CmpTy, BI);
1842 // Create a gep for IVInit + IVLimit from on an existing pointer base.
1843 assert(isPtrIV == IndVar->getType()->isPointerTy() &&
1844 "IndVar type must match IVInit type");
1846 Value *IVStart = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
1847 assert(AR->getStart() == SE->getSCEV(IVStart) && "bad loop counter");
1848 assert(SE->getSizeOfExpr(
1849 cast<PointerType>(IVStart->getType())->getElementType())->isOne()
1850 && "unit stride pointer IV must be i8*");
1852 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1853 ExitCnt = Builder.CreateGEP(IVStart, ExitCnt, "lftr.limit");
1854 Builder.SetInsertPoint(BI);
1857 // Insert a new icmp_ne or icmp_eq instruction before the branch.
1858 ICmpInst::Predicate P;
1859 if (L->contains(BI->getSuccessor(0)))
1860 P = ICmpInst::ICMP_NE;
1862 P = ICmpInst::ICMP_EQ;
1864 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1865 << " LHS:" << *CmpIndVar << '\n'
1867 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1868 << " RHS:\t" << *ExitCnt << "\n"
1869 << " Expr:\t" << *IVLimit << "\n");
1871 if (SE->getTypeSizeInBits(CmpIndVar->getType())
1872 > SE->getTypeSizeInBits(CmpTy)) {
1873 CmpIndVar = Builder.CreateTrunc(CmpIndVar, CmpTy, "lftr.wideiv");
1876 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
1877 Value *OrigCond = BI->getCondition();
1878 // It's tempting to use replaceAllUsesWith here to fully replace the old
1879 // comparison, but that's not immediately safe, since users of the old
1880 // comparison may not be dominated by the new comparison. Instead, just
1881 // update the branch to use the new comparison; in the common case this
1882 // will make old comparison dead.
1883 BI->setCondition(Cond);
1884 DeadInsts.push_back(OrigCond);
1891 //===----------------------------------------------------------------------===//
1892 // SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1893 //===----------------------------------------------------------------------===//
1895 /// If there's a single exit block, sink any loop-invariant values that
1896 /// were defined in the preheader but not used inside the loop into the
1897 /// exit block to reduce register pressure in the loop.
1898 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1899 BasicBlock *ExitBlock = L->getExitBlock();
1900 if (!ExitBlock) return;
1902 BasicBlock *Preheader = L->getLoopPreheader();
1903 if (!Preheader) return;
1905 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
1906 BasicBlock::iterator I = Preheader->getTerminator();
1907 while (I != Preheader->begin()) {
1909 // New instructions were inserted at the end of the preheader.
1910 if (isa<PHINode>(I))
1913 // Don't move instructions which might have side effects, since the side
1914 // effects need to complete before instructions inside the loop. Also don't
1915 // move instructions which might read memory, since the loop may modify
1916 // memory. Note that it's okay if the instruction might have undefined
1917 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1919 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
1922 // Skip debug info intrinsics.
1923 if (isa<DbgInfoIntrinsic>(I))
1926 // Don't sink static AllocaInsts out of the entry block, which would
1927 // turn them into dynamic allocas!
1928 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1929 if (AI->isStaticAlloca())
1932 // Determine if there is a use in or before the loop (direct or
1934 bool UsedInLoop = false;
1935 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1938 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1939 if (PHINode *P = dyn_cast<PHINode>(U)) {
1941 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1942 UseBB = P->getIncomingBlock(i);
1944 if (UseBB == Preheader || L->contains(UseBB)) {
1950 // If there is, the def must remain in the preheader.
1954 // Otherwise, sink it to the exit block.
1955 Instruction *ToMove = I;
1958 if (I != Preheader->begin()) {
1959 // Skip debug info intrinsics.
1962 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1964 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1970 ToMove->moveBefore(InsertPt);
1976 //===----------------------------------------------------------------------===//
1977 // IndVarSimplify driver. Manage several subpasses of IV simplification.
1978 //===----------------------------------------------------------------------===//
1980 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
1981 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1982 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1983 // canonicalization can be a pessimization without LSR to "clean up"
1985 // - We depend on having a preheader; in particular,
1986 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1987 // and we're in trouble if we can't find the induction variable even when
1988 // we've manually inserted one.
1989 if (!L->isLoopSimplifyForm())
1992 if (!DisableIVRewrite)
1993 IU = &getAnalysis<IVUsers>();
1994 LI = &getAnalysis<LoopInfo>();
1995 SE = &getAnalysis<ScalarEvolution>();
1996 DT = &getAnalysis<DominatorTree>();
1997 TD = getAnalysisIfAvailable<TargetData>();
2002 // If there are any floating-point recurrences, attempt to
2003 // transform them to use integer recurrences.
2004 RewriteNonIntegerIVs(L);
2006 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2008 // Create a rewriter object which we'll use to transform the code with.
2009 SCEVExpander Rewriter(*SE, "indvars");
2011 // Eliminate redundant IV users.
2013 // Simplification works best when run before other consumers of SCEV. We
2014 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2015 // other expressions involving loop IVs have been evaluated. This helps SCEV
2016 // set no-wrap flags before normalizing sign/zero extension.
2017 if (DisableIVRewrite) {
2018 Rewriter.disableCanonicalMode();
2019 SimplifyIVUsersNoRewrite(L, Rewriter);
2022 // Check to see if this loop has a computable loop-invariant execution count.
2023 // If so, this means that we can compute the final value of any expressions
2024 // that are recurrent in the loop, and substitute the exit values from the
2025 // loop into any instructions outside of the loop that use the final values of
2026 // the current expressions.
2028 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2029 RewriteLoopExitValues(L, Rewriter);
2031 // Eliminate redundant IV users.
2032 if (!DisableIVRewrite)
2033 SimplifyIVUsers(Rewriter);
2035 // Eliminate redundant IV cycles.
2036 if (DisableIVRewrite)
2037 SimplifyCongruentIVs(L);
2039 // Compute the type of the largest recurrence expression, and decide whether
2040 // a canonical induction variable should be inserted.
2041 Type *LargestType = 0;
2042 bool NeedCannIV = false;
2043 bool ReuseIVForExit = DisableIVRewrite && !ForceLFTR;
2044 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
2045 if (ExpandBECount && !ReuseIVForExit) {
2046 // If we have a known trip count and a single exit block, we'll be
2047 // rewriting the loop exit test condition below, which requires a
2048 // canonical induction variable.
2050 Type *Ty = BackedgeTakenCount->getType();
2051 if (DisableIVRewrite) {
2052 // In this mode, SimplifyIVUsers may have already widened the IV used by
2053 // the backedge test and inserted a Trunc on the compare's operand. Get
2054 // the wider type to avoid creating a redundant narrow IV only used by the
2056 LargestType = getBackedgeIVType(L);
2059 SE->getTypeSizeInBits(Ty) >
2060 SE->getTypeSizeInBits(LargestType))
2061 LargestType = SE->getEffectiveSCEVType(Ty);
2063 if (!DisableIVRewrite) {
2064 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
2067 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
2069 SE->getTypeSizeInBits(Ty) >
2070 SE->getTypeSizeInBits(LargestType))
2075 // Now that we know the largest of the induction variable expressions
2076 // in this loop, insert a canonical induction variable of the largest size.
2077 PHINode *IndVar = 0;
2079 // Check to see if the loop already has any canonical-looking induction
2080 // variables. If any are present and wider than the planned canonical
2081 // induction variable, temporarily remove them, so that the Rewriter
2082 // doesn't attempt to reuse them.
2083 SmallVector<PHINode *, 2> OldCannIVs;
2084 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
2085 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
2086 SE->getTypeSizeInBits(LargestType))
2087 OldCannIV->removeFromParent();
2090 OldCannIVs.push_back(OldCannIV);
2093 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
2097 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
2099 // Now that the official induction variable is established, reinsert
2100 // any old canonical-looking variables after it so that the IR remains
2101 // consistent. They will be deleted as part of the dead-PHI deletion at
2102 // the end of the pass.
2103 while (!OldCannIVs.empty()) {
2104 PHINode *OldCannIV = OldCannIVs.pop_back_val();
2105 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
2108 else if (ExpandBECount && ReuseIVForExit && needsLFTR(L, DT)) {
2109 IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD);
2111 // If we have a trip count expression, rewrite the loop's exit condition
2112 // using it. We can currently only handle loops with a single exit.
2114 if (ExpandBECount && IndVar) {
2115 // Check preconditions for proper SCEVExpander operation. SCEV does not
2116 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
2117 // pass that uses the SCEVExpander must do it. This does not work well for
2118 // loop passes because SCEVExpander makes assumptions about all loops, while
2119 // LoopPassManager only forces the current loop to be simplified.
2121 // FIXME: SCEV expansion has no way to bail out, so the caller must
2122 // explicitly check any assumptions made by SCEV. Brittle.
2123 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
2124 if (!AR || AR->getLoop()->getLoopPreheader())
2126 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
2128 // Rewrite IV-derived expressions.
2129 if (!DisableIVRewrite)
2130 RewriteIVExpressions(L, Rewriter);
2132 // Clear the rewriter cache, because values that are in the rewriter's cache
2133 // can be deleted in the loop below, causing the AssertingVH in the cache to
2137 // Now that we're done iterating through lists, clean up any instructions
2138 // which are now dead.
2139 while (!DeadInsts.empty())
2140 if (Instruction *Inst =
2141 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
2142 RecursivelyDeleteTriviallyDeadInstructions(Inst);
2144 // The Rewriter may not be used from this point on.
2146 // Loop-invariant instructions in the preheader that aren't used in the
2147 // loop may be sunk below the loop to reduce register pressure.
2148 SinkUnusedInvariants(L);
2150 // For completeness, inform IVUsers of the IV use in the newly-created
2151 // loop exit test instruction.
2152 if (IU && NewICmp) {
2153 ICmpInst *NewICmpInst = dyn_cast<ICmpInst>(NewICmp);
2155 IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(0)));
2157 // Clean up dead instructions.
2158 Changed |= DeleteDeadPHIs(L->getHeader());
2159 // Check a post-condition.
2160 assert(L->isLCSSAForm(*DT) &&
2161 "Indvars did not leave the loop in lcssa form!");
2163 // Verify that LFTR, and any other change have not interfered with SCEV's
2164 // ability to compute trip count.
2166 if (DisableIVRewrite && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2168 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2169 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
2170 SE->getTypeSizeInBits(NewBECount->getType()))
2171 NewBECount = SE->getTruncateOrNoop(NewBECount,
2172 BackedgeTakenCount->getType());
2174 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2175 NewBECount->getType());
2176 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");