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 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/BasicBlock.h"
42 #include "llvm/Constants.h"
43 #include "llvm/Instructions.h"
44 #include "llvm/Type.h"
45 #include "llvm/Analysis/ScalarEvolutionExpander.h"
46 #include "llvm/Analysis/LoopInfo.h"
47 #include "llvm/Support/CFG.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/ADT/Statistic.h"
55 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
56 Statistic<> NumPointer ("indvars", "Number of pointer indvars promoted");
57 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
58 Statistic<> NumReplaced("indvars", "Number of exit values replaced");
59 Statistic<> NumLFTR ("indvars", "Number of loop exit tests replaced");
61 class IndVarSimplify : public FunctionPass {
66 virtual bool runOnFunction(Function &) {
67 LI = &getAnalysis<LoopInfo>();
68 SE = &getAnalysis<ScalarEvolution>();
71 // Induction Variables live in the header nodes of loops
72 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequiredID(LoopSimplifyID);
79 AU.addRequired<ScalarEvolution>();
80 AU.addRequired<LoopInfo>();
81 AU.addPreservedID(LoopSimplifyID);
82 AU.addPreservedID(LCSSAID);
86 void runOnLoop(Loop *L);
87 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
88 std::set<Instruction*> &DeadInsts);
89 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
91 void RewriteLoopExitValues(Loop *L);
93 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
95 RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
98 FunctionPass *llvm::createIndVarSimplifyPass() {
99 return new IndVarSimplify();
102 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
103 /// specified set are trivially dead, delete them and see if this makes any of
104 /// their operands subsequently dead.
105 void IndVarSimplify::
106 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
107 while (!Insts.empty()) {
108 Instruction *I = *Insts.begin();
109 Insts.erase(Insts.begin());
110 if (isInstructionTriviallyDead(I)) {
111 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
112 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
114 SE->deleteInstructionFromRecords(I);
115 I->eraseFromParent();
122 /// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
123 /// recurrence. If so, change it into an integer recurrence, permitting
124 /// analysis by the SCEV routines.
125 void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
126 BasicBlock *Preheader,
127 std::set<Instruction*> &DeadInsts) {
128 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
129 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
130 unsigned BackedgeIdx = PreheaderIdx^1;
131 if (GetElementPtrInst *GEPI =
132 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
133 if (GEPI->getOperand(0) == PN) {
134 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
136 // Okay, we found a pointer recurrence. Transform this pointer
137 // recurrence into an integer recurrence. Compute the value that gets
138 // added to the pointer at every iteration.
139 Value *AddedVal = GEPI->getOperand(1);
141 // Insert a new integer PHI node into the top of the block.
142 PHINode *NewPhi = new PHINode(AddedVal->getType(),
143 PN->getName()+".rec", PN);
144 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
146 // Create the new add instruction.
147 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
148 GEPI->getName()+".rec", GEPI);
149 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
151 // Update the existing GEP to use the recurrence.
152 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
154 // Update the GEP to use the new recurrence we just inserted.
155 GEPI->setOperand(1, NewAdd);
157 // If the incoming value is a constant expr GEP, try peeling out the array
158 // 0 index if possible to make things simpler.
159 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
160 if (CE->getOpcode() == Instruction::GetElementPtr) {
161 unsigned NumOps = CE->getNumOperands();
162 assert(NumOps > 1 && "CE folding didn't work!");
163 if (CE->getOperand(NumOps-1)->isNullValue()) {
164 // Check to make sure the last index really is an array index.
165 gep_type_iterator GTI = gep_type_begin(CE);
166 for (unsigned i = 1, e = CE->getNumOperands()-1;
169 if (isa<SequentialType>(*GTI)) {
170 // Pull the last index out of the constant expr GEP.
171 std::vector<Value*> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
172 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
174 GetElementPtrInst *NGEPI =
175 new GetElementPtrInst(NCE, Constant::getNullValue(Type::IntTy),
176 NewAdd, GEPI->getName(), GEPI);
177 GEPI->replaceAllUsesWith(NGEPI);
178 GEPI->eraseFromParent();
185 // Finally, if there are any other users of the PHI node, we must
186 // insert a new GEP instruction that uses the pre-incremented version
187 // of the induction amount.
188 if (!PN->use_empty()) {
189 BasicBlock::iterator InsertPos = PN; ++InsertPos;
190 while (isa<PHINode>(InsertPos)) ++InsertPos;
191 std::string Name = PN->getName(); PN->setName("");
193 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
194 std::vector<Value*>(1, NewPhi), Name,
196 PN->replaceAllUsesWith(PreInc);
199 // Delete the old PHI for sure, and the GEP if its otherwise unused.
200 DeadInsts.insert(PN);
207 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
208 /// loop to be a canonical != comparison against the incremented loop induction
209 /// variable. This pass is able to rewrite the exit tests of any loop where the
210 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
211 /// is actually a much broader range than just linear tests.
213 /// This method returns a "potentially dead" instruction whose computation chain
214 /// should be deleted when convenient.
215 Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
216 SCEV *IterationCount,
218 // Find the exit block for the loop. We can currently only handle loops with
220 std::vector<BasicBlock*> ExitBlocks;
221 L->getExitBlocks(ExitBlocks);
222 if (ExitBlocks.size() != 1) return 0;
223 BasicBlock *ExitBlock = ExitBlocks[0];
225 // Make sure there is only one predecessor block in the loop.
226 BasicBlock *ExitingBlock = 0;
227 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
229 if (L->contains(*PI)) {
230 if (ExitingBlock == 0)
233 return 0; // Multiple exits from loop to this block.
235 assert(ExitingBlock && "Loop info is broken");
237 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
238 return 0; // Can't rewrite non-branch yet
239 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
240 assert(BI->isConditional() && "Must be conditional to be part of loop!");
242 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
244 // If the exiting block is not the same as the backedge block, we must compare
245 // against the preincremented value, otherwise we prefer to compare against
246 // the post-incremented value.
247 BasicBlock *Header = L->getHeader();
248 pred_iterator HPI = pred_begin(Header);
249 assert(HPI != pred_end(Header) && "Loop with zero preds???");
250 if (!L->contains(*HPI)) ++HPI;
251 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
252 "No backedge in loop?");
254 SCEVHandle TripCount = IterationCount;
256 if (*HPI == ExitingBlock) {
257 // The IterationCount expression contains the number of times that the
258 // backedge actually branches to the loop header. This is one less than the
259 // number of times the loop executes, so add one to it.
260 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
261 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
262 IndVar = L->getCanonicalInductionVariableIncrement();
264 // We have to use the preincremented value...
265 IndVar = L->getCanonicalInductionVariable();
268 // Expand the code for the iteration count into the preheader of the loop.
269 BasicBlock *Preheader = L->getLoopPreheader();
270 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
273 // Insert a new setne or seteq instruction before the branch.
274 Instruction::BinaryOps Opcode;
275 if (L->contains(BI->getSuccessor(0)))
276 Opcode = Instruction::SetNE;
278 Opcode = Instruction::SetEQ;
280 Value *Cond = new SetCondInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
281 BI->setCondition(Cond);
284 return PotentiallyDeadInst;
288 /// RewriteLoopExitValues - Check to see if this loop has a computable
289 /// loop-invariant execution count. If so, this means that we can compute the
290 /// final value of any expressions that are recurrent in the loop, and
291 /// substitute the exit values from the loop into any instructions outside of
292 /// the loop that use the final values of the current expressions.
293 void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
294 BasicBlock *Preheader = L->getLoopPreheader();
296 // Scan all of the instructions in the loop, looking at those that have
297 // extra-loop users and which are recurrences.
298 SCEVExpander Rewriter(*SE, *LI);
300 // We insert the code into the preheader of the loop if the loop contains
301 // multiple exit blocks, or in the exit block if there is exactly one.
302 BasicBlock *BlockToInsertInto;
303 std::vector<BasicBlock*> ExitBlocks;
304 L->getExitBlocks(ExitBlocks);
305 if (ExitBlocks.size() == 1)
306 BlockToInsertInto = ExitBlocks[0];
308 BlockToInsertInto = Preheader;
309 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
310 while (isa<PHINode>(InsertPt)) ++InsertPt;
312 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
314 std::set<Instruction*> InstructionsToDelete;
316 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
317 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
318 BasicBlock *BB = L->getBlocks()[i];
319 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
320 if (I->getType()->isInteger()) { // Is an integer instruction
321 SCEVHandle SH = SE->getSCEV(I);
322 if (SH->hasComputableLoopEvolution(L) || // Varies predictably
323 HasConstantItCount) {
324 // Find out if this predictably varying value is actually used
325 // outside of the loop. "extra" as opposed to "intra".
326 std::vector<Instruction*> ExtraLoopUsers;
327 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
329 Instruction *User = cast<Instruction>(*UI);
330 if (!L->contains(User->getParent())) {
331 // If this is a PHI node in the exit block and we're inserting,
332 // into the exit block, it must have a single entry. In this
333 // case, we can't insert the code after the PHI and have the PHI
334 // still use it. Instead, don't insert the the PHI.
335 if (PHINode *PN = dyn_cast<PHINode>(User)) {
336 // FIXME: This is a case where LCSSA pessimizes code, this
337 // should be fixed better.
338 if (PN->getNumOperands() == 2 &&
339 PN->getParent() == BlockToInsertInto)
342 ExtraLoopUsers.push_back(User);
346 if (!ExtraLoopUsers.empty()) {
347 // Okay, this instruction has a user outside of the current loop
348 // and varies predictably in this loop. Evaluate the value it
349 // contains when the loop exits, and insert code for it.
350 SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
351 if (!isa<SCEVCouldNotCompute>(ExitValue)) {
354 // Remember the next instruction. The rewriter can move code
355 // around in some cases.
356 BasicBlock::iterator NextI = I; ++NextI;
358 Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
361 // Rewrite any users of the computed value outside of the loop
362 // with the newly computed value.
363 for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i) {
364 PHINode* PN = dyn_cast<PHINode>(ExtraLoopUsers[i]);
365 if (PN && PN->getNumOperands() == 2 &&
366 !L->contains(PN->getParent())) {
367 // We're dealing with an LCSSA Phi. Handle it specially.
368 Instruction* LCSSAInsertPt = BlockToInsertInto->begin();
370 Instruction* NewInstr = dyn_cast<Instruction>(NewVal);
371 if (NewInstr && !isa<PHINode>(NewInstr) &&
372 !L->contains(NewInstr->getParent()))
373 for (unsigned j = 0; j < NewInstr->getNumOperands(); ++j){
375 dyn_cast<Instruction>(NewInstr->getOperand(j));
376 if (PredI && L->contains(PredI->getParent())) {
377 PHINode* NewLCSSA = new PHINode(PredI->getType(),
378 PredI->getName() + ".lcssa",
380 NewLCSSA->addIncoming(PredI,
381 BlockToInsertInto->getSinglePredecessor());
383 NewInstr->replaceUsesOfWith(PredI, NewLCSSA);
387 PN->replaceAllUsesWith(NewVal);
388 PN->eraseFromParent();
390 ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
394 // If this instruction is dead now, schedule it to be removed.
396 InstructionsToDelete.insert(I);
398 continue; // Skip the ++I
404 // Next instruction. Continue instruction skips this.
409 DeleteTriviallyDeadInstructions(InstructionsToDelete);
413 void IndVarSimplify::runOnLoop(Loop *L) {
414 // First step. Check to see if there are any trivial GEP pointer recurrences.
415 // If there are, change them into integer recurrences, permitting analysis by
416 // the SCEV routines.
418 BasicBlock *Header = L->getHeader();
419 BasicBlock *Preheader = L->getLoopPreheader();
421 std::set<Instruction*> DeadInsts;
422 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
423 PHINode *PN = cast<PHINode>(I);
424 if (isa<PointerType>(PN->getType()))
425 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
428 if (!DeadInsts.empty())
429 DeleteTriviallyDeadInstructions(DeadInsts);
432 // Next, transform all loops nesting inside of this loop.
433 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
436 // Check to see if this loop has a computable loop-invariant execution count.
437 // If so, this means that we can compute the final value of any expressions
438 // that are recurrent in the loop, and substitute the exit values from the
439 // loop into any instructions outside of the loop that use the final values of
440 // the current expressions.
442 SCEVHandle IterationCount = SE->getIterationCount(L);
443 if (!isa<SCEVCouldNotCompute>(IterationCount))
444 RewriteLoopExitValues(L);
446 // Next, analyze all of the induction variables in the loop, canonicalizing
447 // auxillary induction variables.
448 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
450 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
451 PHINode *PN = cast<PHINode>(I);
452 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
453 SCEVHandle SCEV = SE->getSCEV(PN);
454 if (SCEV->hasComputableLoopEvolution(L))
455 // FIXME: It is an extremely bad idea to indvar substitute anything more
456 // complex than affine induction variables. Doing so will put expensive
457 // polynomial evaluations inside of the loop, and the str reduction pass
458 // currently can only reduce affine polynomials. For now just disable
459 // indvar subst on anything more complex than an affine addrec.
460 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
462 IndVars.push_back(std::make_pair(PN, SCEV));
466 // If there are no induction variables in the loop, there is nothing more to
468 if (IndVars.empty()) {
469 // Actually, if we know how many times the loop iterates, lets insert a
470 // canonical induction variable to help subsequent passes.
471 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
472 SCEVExpander Rewriter(*SE, *LI);
473 Rewriter.getOrInsertCanonicalInductionVariable(L,
474 IterationCount->getType());
475 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
477 std::set<Instruction*> InstructionsToDelete;
478 InstructionsToDelete.insert(I);
479 DeleteTriviallyDeadInstructions(InstructionsToDelete);
485 // Compute the type of the largest recurrence expression.
487 const Type *LargestType = IndVars[0].first->getType();
488 bool DifferingSizes = false;
489 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
490 const Type *Ty = IndVars[i].first->getType();
491 DifferingSizes |= Ty->getPrimitiveSize() != LargestType->getPrimitiveSize();
492 if (Ty->getPrimitiveSize() > LargestType->getPrimitiveSize())
496 // Create a rewriter object which we'll use to transform the code with.
497 SCEVExpander Rewriter(*SE, *LI);
499 // Now that we know the largest of of the induction variables in this loop,
500 // insert a canonical induction variable of the largest size.
501 LargestType = LargestType->getUnsignedVersion();
502 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
506 if (!isa<SCEVCouldNotCompute>(IterationCount))
507 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
508 DeadInsts.insert(DI);
510 // Now that we have a canonical induction variable, we can rewrite any
511 // recurrences in terms of the induction variable. Start with the auxillary
512 // induction variables, and recursively rewrite any of their uses.
513 BasicBlock::iterator InsertPt = Header->begin();
514 while (isa<PHINode>(InsertPt)) ++InsertPt;
516 // If there were induction variables of other sizes, cast the primary
517 // induction variable to the right size for them, avoiding the need for the
518 // code evaluation methods to insert induction variables of different sizes.
519 if (DifferingSizes) {
520 bool InsertedSizes[17] = { false };
521 InsertedSizes[LargestType->getPrimitiveSize()] = true;
522 for (unsigned i = 0, e = IndVars.size(); i != e; ++i)
523 if (!InsertedSizes[IndVars[i].first->getType()->getPrimitiveSize()]) {
524 PHINode *PN = IndVars[i].first;
525 InsertedSizes[PN->getType()->getPrimitiveSize()] = true;
526 Instruction *New = new CastInst(IndVar,
527 PN->getType()->getUnsignedVersion(),
529 Rewriter.addInsertedValue(New, SE->getSCEV(New));
533 // If there were induction variables of other sizes, cast the primary
534 // induction variable to the right size for them, avoiding the need for the
535 // code evaluation methods to insert induction variables of different sizes.
536 std::map<unsigned, Value*> InsertedSizes;
537 while (!IndVars.empty()) {
538 PHINode *PN = IndVars.back().first;
539 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
541 std::string Name = PN->getName();
543 NewVal->setName(Name);
545 // Replace the old PHI Node with the inserted computation.
546 PN->replaceAllUsesWith(NewVal);
547 DeadInsts.insert(PN);
554 // Now replace all derived expressions in the loop body with simpler
556 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
557 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
558 BasicBlock *BB = L->getBlocks()[i];
559 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
560 if (I->getType()->isInteger() && // Is an integer instruction
562 !Rewriter.isInsertedInstruction(I)) {
563 SCEVHandle SH = SE->getSCEV(I);
564 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
566 if (isa<Instruction>(V)) {
567 std::string Name = I->getName();
571 I->replaceAllUsesWith(V);
580 DeleteTriviallyDeadInstructions(DeadInsts);
582 if (mustPreserveAnalysisID(LCSSAID)) assert(L->isLCSSAForm());