1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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. Any pointer arithmetic recurrences are raised to use array subscripts.
22 // If the trip count of a loop is computable, this pass also makes the following
24 // 1. The exit condition for the loop is canonicalized to compare the
25 // induction value against the exit value. This turns loops like:
26 // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
27 // 2. Any use outside of the loop of an expression derived from the indvar
28 // is changed to compute the derived value outside of the loop, eliminating
29 // the dependence on the exit value of the induction variable. If the only
30 // purpose of the loop is to compute the exit value of some derived
31 // expression, this transformation will make the loop dead.
33 // This transformation should be followed by strength reduction after all of the
34 // desired loop transformations have been performed. Additionally, on targets
35 // where it is profitable, the loop could be transformed to count down to zero
36 // (the "do loop" optimization).
38 //===----------------------------------------------------------------------===//
40 #define DEBUG_TYPE "indvars"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/BasicBlock.h"
43 #include "llvm/Constants.h"
44 #include "llvm/Instructions.h"
45 #include "llvm/Type.h"
46 #include "llvm/Analysis/ScalarEvolutionExpander.h"
47 #include "llvm/Analysis/LoopInfo.h"
48 #include "llvm/Support/CFG.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/GetElementPtrTypeIterator.h"
52 #include "llvm/Transforms/Utils/Local.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/Statistic.h"
58 STATISTIC(NumRemoved , "Number of aux indvars removed");
59 STATISTIC(NumPointer , "Number of pointer indvars promoted");
60 STATISTIC(NumInserted, "Number of canonical indvars added");
61 STATISTIC(NumReplaced, "Number of exit values replaced");
62 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
65 class VISIBILITY_HIDDEN IndVarSimplify : public FunctionPass {
70 virtual bool runOnFunction(Function &) {
71 LI = &getAnalysis<LoopInfo>();
72 SE = &getAnalysis<ScalarEvolution>();
75 // Induction Variables live in the header nodes of loops
76 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
81 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82 AU.addRequiredID(LCSSAID);
83 AU.addRequiredID(LoopSimplifyID);
84 AU.addRequired<ScalarEvolution>();
85 AU.addRequired<LoopInfo>();
86 AU.addPreservedID(LoopSimplifyID);
87 AU.addPreservedID(LCSSAID);
91 void runOnLoop(Loop *L);
92 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
93 std::set<Instruction*> &DeadInsts);
94 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
96 void RewriteLoopExitValues(Loop *L);
98 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
100 RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
103 FunctionPass *llvm::createIndVarSimplifyPass() {
104 return new IndVarSimplify();
107 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
108 /// specified set are trivially dead, delete them and see if this makes any of
109 /// their operands subsequently dead.
110 void IndVarSimplify::
111 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
112 while (!Insts.empty()) {
113 Instruction *I = *Insts.begin();
114 Insts.erase(Insts.begin());
115 if (isInstructionTriviallyDead(I)) {
116 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
117 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
119 SE->deleteInstructionFromRecords(I);
120 DOUT << "INDVARS: Deleting: " << *I;
121 I->eraseFromParent();
128 /// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
129 /// recurrence. If so, change it into an integer recurrence, permitting
130 /// analysis by the SCEV routines.
131 void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
132 BasicBlock *Preheader,
133 std::set<Instruction*> &DeadInsts) {
134 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
135 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
136 unsigned BackedgeIdx = PreheaderIdx^1;
137 if (GetElementPtrInst *GEPI =
138 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
139 if (GEPI->getOperand(0) == PN) {
140 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
141 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
143 // Okay, we found a pointer recurrence. Transform this pointer
144 // recurrence into an integer recurrence. Compute the value that gets
145 // added to the pointer at every iteration.
146 Value *AddedVal = GEPI->getOperand(1);
148 // Insert a new integer PHI node into the top of the block.
149 PHINode *NewPhi = new PHINode(AddedVal->getType(),
150 PN->getName()+".rec", PN);
151 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
153 // Create the new add instruction.
154 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
155 GEPI->getName()+".rec", GEPI);
156 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
158 // Update the existing GEP to use the recurrence.
159 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
161 // Update the GEP to use the new recurrence we just inserted.
162 GEPI->setOperand(1, NewAdd);
164 // If the incoming value is a constant expr GEP, try peeling out the array
165 // 0 index if possible to make things simpler.
166 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
167 if (CE->getOpcode() == Instruction::GetElementPtr) {
168 unsigned NumOps = CE->getNumOperands();
169 assert(NumOps > 1 && "CE folding didn't work!");
170 if (CE->getOperand(NumOps-1)->isNullValue()) {
171 // Check to make sure the last index really is an array index.
172 gep_type_iterator GTI = gep_type_begin(CE);
173 for (unsigned i = 1, e = CE->getNumOperands()-1;
176 if (isa<SequentialType>(*GTI)) {
177 // Pull the last index out of the constant expr GEP.
178 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
179 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
182 GetElementPtrInst *NGEPI = new GetElementPtrInst(
183 NCE, Constant::getNullValue(Type::Int32Ty), NewAdd,
184 GEPI->getName(), GEPI);
185 GEPI->replaceAllUsesWith(NGEPI);
186 GEPI->eraseFromParent();
193 // Finally, if there are any other users of the PHI node, we must
194 // insert a new GEP instruction that uses the pre-incremented version
195 // of the induction amount.
196 if (!PN->use_empty()) {
197 BasicBlock::iterator InsertPos = PN; ++InsertPos;
198 while (isa<PHINode>(InsertPos)) ++InsertPos;
200 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
201 NewPhi, "", InsertPos);
202 PreInc->takeName(PN);
203 PN->replaceAllUsesWith(PreInc);
206 // Delete the old PHI for sure, and the GEP if its otherwise unused.
207 DeadInsts.insert(PN);
214 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
215 /// loop to be a canonical != comparison against the incremented loop induction
216 /// variable. This pass is able to rewrite the exit tests of any loop where the
217 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
218 /// is actually a much broader range than just linear tests.
220 /// This method returns a "potentially dead" instruction whose computation chain
221 /// should be deleted when convenient.
222 Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
223 SCEV *IterationCount,
225 // Find the exit block for the loop. We can currently only handle loops with
227 std::vector<BasicBlock*> ExitBlocks;
228 L->getExitBlocks(ExitBlocks);
229 if (ExitBlocks.size() != 1) return 0;
230 BasicBlock *ExitBlock = ExitBlocks[0];
232 // Make sure there is only one predecessor block in the loop.
233 BasicBlock *ExitingBlock = 0;
234 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
236 if (L->contains(*PI)) {
237 if (ExitingBlock == 0)
240 return 0; // Multiple exits from loop to this block.
242 assert(ExitingBlock && "Loop info is broken");
244 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
245 return 0; // Can't rewrite non-branch yet
246 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
247 assert(BI->isConditional() && "Must be conditional to be part of loop!");
249 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
251 // If the exiting block is not the same as the backedge block, we must compare
252 // against the preincremented value, otherwise we prefer to compare against
253 // the post-incremented value.
254 BasicBlock *Header = L->getHeader();
255 pred_iterator HPI = pred_begin(Header);
256 assert(HPI != pred_end(Header) && "Loop with zero preds???");
257 if (!L->contains(*HPI)) ++HPI;
258 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
259 "No backedge in loop?");
261 SCEVHandle TripCount = IterationCount;
263 if (*HPI == ExitingBlock) {
264 // The IterationCount expression contains the number of times that the
265 // backedge actually branches to the loop header. This is one less than the
266 // number of times the loop executes, so add one to it.
267 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
268 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
269 IndVar = L->getCanonicalInductionVariableIncrement();
271 // We have to use the preincremented value...
272 IndVar = L->getCanonicalInductionVariable();
275 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
276 << " IndVar = " << *IndVar << "\n";
278 // Expand the code for the iteration count into the preheader of the loop.
279 BasicBlock *Preheader = L->getLoopPreheader();
280 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
283 // Insert a new icmp_ne or icmp_eq instruction before the branch.
284 ICmpInst::Predicate Opcode;
285 if (L->contains(BI->getSuccessor(0)))
286 Opcode = ICmpInst::ICMP_NE;
288 Opcode = ICmpInst::ICMP_EQ;
290 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
291 BI->setCondition(Cond);
294 return PotentiallyDeadInst;
298 /// RewriteLoopExitValues - Check to see if this loop has a computable
299 /// loop-invariant execution count. If so, this means that we can compute the
300 /// final value of any expressions that are recurrent in the loop, and
301 /// substitute the exit values from the loop into any instructions outside of
302 /// the loop that use the final values of the current expressions.
303 void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
304 BasicBlock *Preheader = L->getLoopPreheader();
306 // Scan all of the instructions in the loop, looking at those that have
307 // extra-loop users and which are recurrences.
308 SCEVExpander Rewriter(*SE, *LI);
310 // We insert the code into the preheader of the loop if the loop contains
311 // multiple exit blocks, or in the exit block if there is exactly one.
312 BasicBlock *BlockToInsertInto;
313 std::vector<BasicBlock*> ExitBlocks;
314 L->getExitBlocks(ExitBlocks);
315 if (ExitBlocks.size() == 1)
316 BlockToInsertInto = ExitBlocks[0];
318 BlockToInsertInto = Preheader;
319 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
320 while (isa<PHINode>(InsertPt)) ++InsertPt;
322 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
324 std::set<Instruction*> InstructionsToDelete;
326 // Loop over all of the integer-valued instructions in this loop, but that are
328 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
329 if (LI->getLoopFor(L->getBlocks()[i]) != L)
330 continue; // The Block is in a subloop, skip it.
331 BasicBlock *BB = L->getBlocks()[i];
332 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
333 Instruction *I = II++;
335 if (!I->getType()->isInteger())
336 continue; // SCEV only supports integer expressions for now.
338 // We require that this value either have a computable evolution or that
339 // the loop have a constant iteration count. In the case where the loop
340 // has a constant iteration count, we can sometimes force evaluation of
341 // the exit value through brute force.
342 SCEVHandle SH = SE->getSCEV(I);
343 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
344 continue; // Cannot get exit evolution for the loop value.
346 // Find out if this predictably varying value is actually used
347 // outside of the loop. "Extra" is as opposed to "intra".
348 std::vector<Instruction*> ExtraLoopUsers;
349 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
351 Instruction *User = cast<Instruction>(*UI);
352 if (!L->contains(User->getParent()))
353 ExtraLoopUsers.push_back(User);
356 // If nothing outside the loop uses this value, don't rewrite it.
357 if (ExtraLoopUsers.empty())
360 // Okay, this instruction has a user outside of the current loop
361 // and varies predictably *inside* the loop. Evaluate the value it
362 // contains when the loop exits if possible.
363 SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
364 if (isa<SCEVCouldNotCompute>(ExitValue) ||
365 !ExitValue->isLoopInvariant(L))
371 Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
374 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *NewVal
375 << " LoopVal = " << *I << "\n";
377 // Rewrite any users of the computed value outside of the loop
378 // with the newly computed value.
379 for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i) {
380 Instruction *User = ExtraLoopUsers[i];
382 User->replaceUsesOfWith(I, NewVal);
384 // See if this is an LCSSA PHI node. If so, we can (and have to) remove
385 // the PHI entirely. This is safe, because the NewVal won't be variant
386 // in the loop, so we don't need an LCSSA phi node anymore.
387 PHINode *LCSSAPN = dyn_cast<PHINode>(User);
388 if (LCSSAPN && LCSSAPN->getNumOperands() == 2 &&
389 L->contains(LCSSAPN->getIncomingBlock(0))) {
390 LCSSAPN->replaceAllUsesWith(NewVal);
391 LCSSAPN->eraseFromParent();
395 // If this instruction is dead now, schedule it to be removed.
397 InstructionsToDelete.insert(I);
401 DeleteTriviallyDeadInstructions(InstructionsToDelete);
405 void IndVarSimplify::runOnLoop(Loop *L) {
406 // First step. Check to see if there are any trivial GEP pointer recurrences.
407 // If there are, change them into integer recurrences, permitting analysis by
408 // the SCEV routines.
410 BasicBlock *Header = L->getHeader();
411 BasicBlock *Preheader = L->getLoopPreheader();
413 std::set<Instruction*> DeadInsts;
414 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
415 PHINode *PN = cast<PHINode>(I);
416 if (isa<PointerType>(PN->getType()))
417 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
420 if (!DeadInsts.empty())
421 DeleteTriviallyDeadInstructions(DeadInsts);
424 // Next, transform all loops nesting inside of this loop.
425 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
428 // Verify the input to the pass in already in LCSSA form.
429 assert(L->isLCSSAForm());
431 // Check to see if this loop has a computable loop-invariant execution count.
432 // If so, this means that we can compute the final value of any expressions
433 // that are recurrent in the loop, and substitute the exit values from the
434 // loop into any instructions outside of the loop that use the final values of
435 // the current expressions.
437 SCEVHandle IterationCount = SE->getIterationCount(L);
438 if (!isa<SCEVCouldNotCompute>(IterationCount))
439 RewriteLoopExitValues(L);
441 // Next, analyze all of the induction variables in the loop, canonicalizing
442 // auxillary induction variables.
443 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
445 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
446 PHINode *PN = cast<PHINode>(I);
447 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
448 SCEVHandle SCEV = SE->getSCEV(PN);
449 if (SCEV->hasComputableLoopEvolution(L))
450 // FIXME: It is an extremely bad idea to indvar substitute anything more
451 // complex than affine induction variables. Doing so will put expensive
452 // polynomial evaluations inside of the loop, and the str reduction pass
453 // currently can only reduce affine polynomials. For now just disable
454 // indvar subst on anything more complex than an affine addrec.
455 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
457 IndVars.push_back(std::make_pair(PN, SCEV));
461 // If there are no induction variables in the loop, there is nothing more to
463 if (IndVars.empty()) {
464 // Actually, if we know how many times the loop iterates, lets insert a
465 // canonical induction variable to help subsequent passes.
466 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
467 SCEVExpander Rewriter(*SE, *LI);
468 Rewriter.getOrInsertCanonicalInductionVariable(L,
469 IterationCount->getType());
470 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
472 std::set<Instruction*> InstructionsToDelete;
473 InstructionsToDelete.insert(I);
474 DeleteTriviallyDeadInstructions(InstructionsToDelete);
480 // Compute the type of the largest recurrence expression.
482 const Type *LargestType = IndVars[0].first->getType();
483 bool DifferingSizes = false;
484 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
485 const Type *Ty = IndVars[i].first->getType();
487 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
488 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
492 // Create a rewriter object which we'll use to transform the code with.
493 SCEVExpander Rewriter(*SE, *LI);
495 // Now that we know the largest of of the induction variables in this loop,
496 // insert a canonical induction variable of the largest size.
497 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
500 DOUT << "INDVARS: New CanIV: " << *IndVar;
502 if (!isa<SCEVCouldNotCompute>(IterationCount))
503 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
504 DeadInsts.insert(DI);
506 // Now that we have a canonical induction variable, we can rewrite any
507 // recurrences in terms of the induction variable. Start with the auxillary
508 // induction variables, and recursively rewrite any of their uses.
509 BasicBlock::iterator InsertPt = Header->begin();
510 while (isa<PHINode>(InsertPt)) ++InsertPt;
512 // If there were induction variables of other sizes, cast the primary
513 // induction variable to the right size for them, avoiding the need for the
514 // code evaluation methods to insert induction variables of different sizes.
515 if (DifferingSizes) {
516 SmallVector<unsigned,4> InsertedSizes;
517 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
518 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
519 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
520 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
521 == InsertedSizes.end()) {
522 PHINode *PN = IndVars[i].first;
523 InsertedSizes.push_back(ithSize);
524 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
526 Rewriter.addInsertedValue(New, SE->getSCEV(New));
527 DOUT << "INDVARS: Made trunc IV for " << *PN
528 << " NewVal = " << *New << "\n";
533 // Rewrite all induction variables in terms of the canonical induction
535 std::map<unsigned, Value*> InsertedSizes;
536 while (!IndVars.empty()) {
537 PHINode *PN = IndVars.back().first;
538 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
540 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
541 << " into = " << *NewVal << "\n";
542 NewVal->takeName(PN);
544 // Replace the old PHI Node with the inserted computation.
545 PN->replaceAllUsesWith(NewVal);
546 DeadInsts.insert(PN);
553 // Now replace all derived expressions in the loop body with simpler
555 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
556 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
557 BasicBlock *BB = L->getBlocks()[i];
558 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
559 if (I->getType()->isInteger() && // Is an integer instruction
561 !Rewriter.isInsertedInstruction(I)) {
562 SCEVHandle SH = SE->getSCEV(I);
563 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
565 if (isa<Instruction>(V))
567 I->replaceAllUsesWith(V);
576 DeleteTriviallyDeadInstructions(DeadInsts);
578 assert(L->isLCSSAForm());