blob: 4e18512a49d5eaa5ab01a43c2d3ab72c1e310009 [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into simpler forms suitable for subsequent
12// analysis and transformation.
13//
Reid Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-04-02 20:24:31 +000015// 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.
21//
22// If the trip count of a loop is computable, this pass also makes the following
23// changes:
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.
32//
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).
Chris Lattner6148c022001-12-03 17:28:42 +000037//
38//===----------------------------------------------------------------------===//
39
Chris Lattner0e5f4992006-12-19 21:40:18 +000040#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000041#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000042#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000043#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000044#include "llvm/Instructions.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000045#include "llvm/Type.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000047#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000049#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000050#include "llvm/Support/Compiler.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000051#include "llvm/Support/Debug.h"
Chris Lattnera4b9c782004-10-11 23:06:50 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswell47df12d2003-12-18 17:19:19 +000053#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000054#include "llvm/Support/CommandLine.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000055#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000057using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000058
Chris Lattner0e5f4992006-12-19 21:40:18 +000059STATISTIC(NumRemoved , "Number of aux indvars removed");
60STATISTIC(NumPointer , "Number of pointer indvars promoted");
61STATISTIC(NumInserted, "Number of canonical indvars added");
62STATISTIC(NumReplaced, "Number of exit values replaced");
63STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000066 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Chris Lattner40bf8b42004-04-02 20:24:31 +000067 LoopInfo *LI;
68 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000069 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000070 public:
Devang Patel794fd752007-05-01 21:15:47 +000071
Devang Patel19974732007-05-03 01:11:54 +000072 static char ID; // Pass identifcation, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000073 IndVarSimplify() : LoopPass((intptr_t)&ID) {}
74
Devang Patel5ee99972007-03-07 06:39:01 +000075 bool runOnLoop(Loop *L, LPPassManager &LPM);
76 bool doInitialization(Loop *L, LPPassManager &LPM);
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequiredID(LCSSAID);
79 AU.addRequiredID(LoopSimplifyID);
80 AU.addRequired<ScalarEvolution>();
81 AU.addRequired<LoopInfo>();
82 AU.addPreservedID(LoopSimplifyID);
83 AU.addPreservedID(LCSSAID);
84 AU.setPreservesCFG();
85 }
Chris Lattner15cad752003-12-23 07:47:09 +000086
Chris Lattner40bf8b42004-04-02 20:24:31 +000087 private:
Devang Patel5ee99972007-03-07 06:39:01 +000088
Chris Lattner40bf8b42004-04-02 20:24:31 +000089 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
90 std::set<Instruction*> &DeadInsts);
Chris Lattner9ba46c12006-09-21 05:12:20 +000091 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
92 SCEVExpander &RW);
Chris Lattner40bf8b42004-04-02 20:24:31 +000093 void RewriteLoopExitValues(Loop *L);
94
95 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
Chris Lattner3324e712003-12-22 03:58:44 +000096 };
Devang Patel794fd752007-05-01 21:15:47 +000097
Devang Patel19974732007-05-03 01:11:54 +000098 char IndVarSimplify::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000099 RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner5e761402002-09-10 05:24:05 +0000100}
Chris Lattner394437f2001-12-04 04:32:29 +0000101
Devang Patel5ee99972007-03-07 06:39:01 +0000102LoopPass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000103 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000104}
105
Chris Lattner40bf8b42004-04-02 20:24:31 +0000106/// DeleteTriviallyDeadInstructions - If any of the instructions is the
107/// specified set are trivially dead, delete them and see if this makes any of
108/// their operands subsequently dead.
109void IndVarSimplify::
110DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
111 while (!Insts.empty()) {
112 Instruction *I = *Insts.begin();
113 Insts.erase(Insts.begin());
114 if (isInstructionTriviallyDead(I)) {
115 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
116 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
117 Insts.insert(U);
118 SE->deleteInstructionFromRecords(I);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000119 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000120 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000121 Changed = true;
122 }
123 }
124}
125
126
127/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
128/// recurrence. If so, change it into an integer recurrence, permitting
129/// analysis by the SCEV routines.
Misha Brukmanfd939082005-04-21 23:48:37 +0000130void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattner40bf8b42004-04-02 20:24:31 +0000131 BasicBlock *Preheader,
132 std::set<Instruction*> &DeadInsts) {
133 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
134 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
135 unsigned BackedgeIdx = PreheaderIdx^1;
136 if (GetElementPtrInst *GEPI =
Chris Lattnercda9ca52005-08-10 01:12:06 +0000137 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattner40bf8b42004-04-02 20:24:31 +0000138 if (GEPI->getOperand(0) == PN) {
Chris Lattnercda9ca52005-08-10 01:12:06 +0000139 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattneree4f13a2007-01-07 01:14:12 +0000140 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
141
Chris Lattner40bf8b42004-04-02 20:24:31 +0000142 // Okay, we found a pointer recurrence. Transform this pointer
143 // recurrence into an integer recurrence. Compute the value that gets
144 // added to the pointer at every iteration.
145 Value *AddedVal = GEPI->getOperand(1);
146
147 // Insert a new integer PHI node into the top of the block.
148 PHINode *NewPhi = new PHINode(AddedVal->getType(),
149 PN->getName()+".rec", PN);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000150 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
151
Chris Lattner40bf8b42004-04-02 20:24:31 +0000152 // Create the new add instruction.
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000153 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
154 GEPI->getName()+".rec", GEPI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000155 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000156
Chris Lattner40bf8b42004-04-02 20:24:31 +0000157 // Update the existing GEP to use the recurrence.
158 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000159
Chris Lattner40bf8b42004-04-02 20:24:31 +0000160 // Update the GEP to use the new recurrence we just inserted.
161 GEPI->setOperand(1, NewAdd);
162
Chris Lattnera4b9c782004-10-11 23:06:50 +0000163 // If the incoming value is a constant expr GEP, try peeling out the array
164 // 0 index if possible to make things simpler.
165 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
166 if (CE->getOpcode() == Instruction::GetElementPtr) {
167 unsigned NumOps = CE->getNumOperands();
168 assert(NumOps > 1 && "CE folding didn't work!");
169 if (CE->getOperand(NumOps-1)->isNullValue()) {
170 // Check to make sure the last index really is an array index.
Chris Lattner17300782005-11-18 18:30:47 +0000171 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerceda6052005-11-17 19:35:42 +0000172 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000173 i != e; ++i, ++GTI)
174 /*empty*/;
175 if (isa<SequentialType>(*GTI)) {
176 // Pull the last index out of the constant expr GEP.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000177 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000178 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000179 &CEIdxs[0],
180 CEIdxs.size());
Reid Spencercae57542007-03-02 00:28:52 +0000181 GetElementPtrInst *NGEPI = new GetElementPtrInst(
182 NCE, Constant::getNullValue(Type::Int32Ty), NewAdd,
183 GEPI->getName(), GEPI);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000184 GEPI->replaceAllUsesWith(NGEPI);
185 GEPI->eraseFromParent();
186 GEPI = NGEPI;
187 }
188 }
189 }
190
191
Chris Lattner40bf8b42004-04-02 20:24:31 +0000192 // Finally, if there are any other users of the PHI node, we must
193 // insert a new GEP instruction that uses the pre-incremented version
194 // of the induction amount.
195 if (!PN->use_empty()) {
196 BasicBlock::iterator InsertPos = PN; ++InsertPos;
197 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000198 Value *PreInc =
199 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
Chris Lattner6934a042007-02-11 01:23:03 +0000200 NewPhi, "", InsertPos);
201 PreInc->takeName(PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000202 PN->replaceAllUsesWith(PreInc);
203 }
204
205 // Delete the old PHI for sure, and the GEP if its otherwise unused.
206 DeadInsts.insert(PN);
207
208 ++NumPointer;
209 Changed = true;
210 }
211}
212
213/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000214/// loop to be a canonical != comparison against the incremented loop induction
215/// variable. This pass is able to rewrite the exit tests of any loop where the
216/// SCEV analysis can determine a loop-invariant trip count of the loop, which
217/// is actually a much broader range than just linear tests.
Chris Lattner9ba46c12006-09-21 05:12:20 +0000218///
219/// This method returns a "potentially dead" instruction whose computation chain
220/// should be deleted when convenient.
221Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
222 SCEV *IterationCount,
223 SCEVExpander &RW) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000224 // Find the exit block for the loop. We can currently only handle loops with
225 // a single exit.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000226 std::vector<BasicBlock*> ExitBlocks;
227 L->getExitBlocks(ExitBlocks);
Chris Lattner9ba46c12006-09-21 05:12:20 +0000228 if (ExitBlocks.size() != 1) return 0;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000229 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000230
231 // Make sure there is only one predecessor block in the loop.
232 BasicBlock *ExitingBlock = 0;
233 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
234 PI != PE; ++PI)
235 if (L->contains(*PI)) {
236 if (ExitingBlock == 0)
237 ExitingBlock = *PI;
238 else
Chris Lattner9ba46c12006-09-21 05:12:20 +0000239 return 0; // Multiple exits from loop to this block.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000240 }
241 assert(ExitingBlock && "Loop info is broken");
242
243 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
Chris Lattner9ba46c12006-09-21 05:12:20 +0000244 return 0; // Can't rewrite non-branch yet
Chris Lattner40bf8b42004-04-02 20:24:31 +0000245 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
246 assert(BI->isConditional() && "Must be conditional to be part of loop!");
247
Chris Lattner9ba46c12006-09-21 05:12:20 +0000248 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
249
Chris Lattnerd2440572004-04-15 20:26:22 +0000250 // If the exiting block is not the same as the backedge block, we must compare
251 // against the preincremented value, otherwise we prefer to compare against
252 // the post-incremented value.
253 BasicBlock *Header = L->getHeader();
254 pred_iterator HPI = pred_begin(Header);
255 assert(HPI != pred_end(Header) && "Loop with zero preds???");
256 if (!L->contains(*HPI)) ++HPI;
257 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
258 "No backedge in loop?");
Chris Lattner59fdaee2004-04-15 15:21:43 +0000259
Chris Lattnerd2440572004-04-15 20:26:22 +0000260 SCEVHandle TripCount = IterationCount;
261 Value *IndVar;
262 if (*HPI == ExitingBlock) {
263 // The IterationCount expression contains the number of times that the
264 // backedge actually branches to the loop header. This is one less than the
265 // number of times the loop executes, so add one to it.
266 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
267 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
268 IndVar = L->getCanonicalInductionVariableIncrement();
269 } else {
270 // We have to use the preincremented value...
271 IndVar = L->getCanonicalInductionVariable();
272 }
Chris Lattneree4f13a2007-01-07 01:14:12 +0000273
274 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
275 << " IndVar = " << *IndVar << "\n";
Chris Lattner59fdaee2004-04-15 15:21:43 +0000276
Chris Lattner40bf8b42004-04-02 20:24:31 +0000277 // Expand the code for the iteration count into the preheader of the loop.
278 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattner4a7553e2004-04-23 21:29:48 +0000279 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
Chris Lattner40bf8b42004-04-02 20:24:31 +0000280 IndVar->getType());
281
Reid Spencere4d87aa2006-12-23 06:05:41 +0000282 // Insert a new icmp_ne or icmp_eq instruction before the branch.
283 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000284 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000285 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000286 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000287 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000288
Reid Spencere4d87aa2006-12-23 06:05:41 +0000289 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000290 BI->setCondition(Cond);
291 ++NumLFTR;
292 Changed = true;
Chris Lattner9ba46c12006-09-21 05:12:20 +0000293 return PotentiallyDeadInst;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000294}
295
296
297/// RewriteLoopExitValues - Check to see if this loop has a computable
298/// loop-invariant execution count. If so, this means that we can compute the
299/// final value of any expressions that are recurrent in the loop, and
300/// substitute the exit values from the loop into any instructions outside of
301/// the loop that use the final values of the current expressions.
302void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
303 BasicBlock *Preheader = L->getLoopPreheader();
304
305 // Scan all of the instructions in the loop, looking at those that have
306 // extra-loop users and which are recurrences.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000307 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000308
309 // We insert the code into the preheader of the loop if the loop contains
310 // multiple exit blocks, or in the exit block if there is exactly one.
311 BasicBlock *BlockToInsertInto;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000312 std::vector<BasicBlock*> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000313 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000314 if (ExitBlocks.size() == 1)
315 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000316 else
317 BlockToInsertInto = Preheader;
318 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
319 while (isa<PHINode>(InsertPt)) ++InsertPt;
320
Chris Lattner20aa0982004-04-17 18:44:09 +0000321 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
322
Chris Lattner40bf8b42004-04-02 20:24:31 +0000323 std::set<Instruction*> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000324 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000325
Chris Lattner9f3d7382007-03-04 03:43:23 +0000326 // Find all values that are computed inside the loop, but used outside of it.
327 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
328 // the exit blocks of the loop to find them.
329 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
330 BasicBlock *ExitBB = ExitBlocks[i];
331
332 // If there are no PHI nodes in this exit block, then no values defined
333 // inside the loop are used on this path, skip it.
334 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
335 if (!PN) continue;
336
337 unsigned NumPreds = PN->getNumIncomingValues();
338
339 // Iterate over all of the PHI nodes.
340 BasicBlock::iterator BBI = ExitBB->begin();
341 while ((PN = dyn_cast<PHINode>(BBI++))) {
Chris Lattnerc9838f22007-03-03 22:48:48 +0000342
Chris Lattner9f3d7382007-03-04 03:43:23 +0000343 // Iterate over all of the values in all the PHI nodes.
344 for (unsigned i = 0; i != NumPreds; ++i) {
345 // If the value being merged in is not integer or is not defined
346 // in the loop, skip it.
347 Value *InVal = PN->getIncomingValue(i);
348 if (!isa<Instruction>(InVal) ||
349 // SCEV only supports integer expressions for now.
350 !isa<IntegerType>(InVal->getType()))
351 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000352
Chris Lattner9f3d7382007-03-04 03:43:23 +0000353 // If this pred is for a subloop, not L itself, skip it.
354 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
355 continue; // The Block is in a subloop, skip it.
356
357 // Check that InVal is defined in the loop.
358 Instruction *Inst = cast<Instruction>(InVal);
359 if (!L->contains(Inst->getParent()))
360 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000361
Chris Lattner9f3d7382007-03-04 03:43:23 +0000362 // We require that this value either have a computable evolution or that
363 // the loop have a constant iteration count. In the case where the loop
364 // has a constant iteration count, we can sometimes force evaluation of
365 // the exit value through brute force.
366 SCEVHandle SH = SE->getSCEV(Inst);
367 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
368 continue; // Cannot get exit evolution for the loop value.
369
370 // Okay, this instruction has a user outside of the current loop
371 // and varies predictably *inside* the loop. Evaluate the value it
372 // contains when the loop exits, if possible.
373 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
374 if (isa<SCEVCouldNotCompute>(ExitValue) ||
375 !ExitValue->isLoopInvariant(L))
376 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000377
Chris Lattner9f3d7382007-03-04 03:43:23 +0000378 Changed = true;
379 ++NumReplaced;
380
381 // See if we already computed the exit value for the instruction, if so,
382 // just reuse it.
383 Value *&ExitVal = ExitValues[Inst];
384 if (!ExitVal)
385 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt,Inst->getType());
386
387 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
388 << " LoopVal = " << *Inst << "\n";
389
390 PN->setIncomingValue(i, ExitVal);
391
392 // If this instruction is dead now, schedule it to be removed.
393 if (Inst->use_empty())
394 InstructionsToDelete.insert(Inst);
395
396 // See if this is a single-entry LCSSA PHI node. If so, we can (and
397 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000398 // the PHI entirely. This is safe, because the NewVal won't be variant
399 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000400 if (NumPreds == 1) {
401 PN->replaceAllUsesWith(ExitVal);
402 PN->eraseFromParent();
403 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000404 }
405 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000406 }
407 }
408
Chris Lattner40bf8b42004-04-02 20:24:31 +0000409 DeleteTriviallyDeadInstructions(InstructionsToDelete);
410}
411
Devang Patel5ee99972007-03-07 06:39:01 +0000412bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000413
Devang Patel5ee99972007-03-07 06:39:01 +0000414 Changed = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000415 // First step. Check to see if there are any trivial GEP pointer recurrences.
416 // If there are, change them into integer recurrences, permitting analysis by
417 // the SCEV routines.
418 //
419 BasicBlock *Header = L->getHeader();
420 BasicBlock *Preheader = L->getLoopPreheader();
Devang Patel5ee99972007-03-07 06:39:01 +0000421 SE = &LPM.getAnalysis<ScalarEvolution>();
Misha Brukmanfd939082005-04-21 23:48:37 +0000422
Chris Lattner40bf8b42004-04-02 20:24:31 +0000423 std::set<Instruction*> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000424 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
425 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000426 if (isa<PointerType>(PN->getType()))
427 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000428 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000429
430 if (!DeadInsts.empty())
431 DeleteTriviallyDeadInstructions(DeadInsts);
432
Devang Patel5ee99972007-03-07 06:39:01 +0000433 return Changed;
434}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000435
Devang Patel5ee99972007-03-07 06:39:01 +0000436bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner3324e712003-12-22 03:58:44 +0000437
Devang Patel5ee99972007-03-07 06:39:01 +0000438
439 LI = &getAnalysis<LoopInfo>();
440 SE = &getAnalysis<ScalarEvolution>();
441
442 Changed = false;
443 BasicBlock *Header = L->getHeader();
444 std::set<Instruction*> DeadInsts;
445
Chris Lattner9caed542007-03-04 01:00:28 +0000446 // Verify the input to the pass in already in LCSSA form.
447 assert(L->isLCSSAForm());
448
Chris Lattner40bf8b42004-04-02 20:24:31 +0000449 // Check to see if this loop has a computable loop-invariant execution count.
450 // If so, this means that we can compute the final value of any expressions
451 // that are recurrent in the loop, and substitute the exit values from the
452 // loop into any instructions outside of the loop that use the final values of
453 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000454 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000455 SCEVHandle IterationCount = SE->getIterationCount(L);
456 if (!isa<SCEVCouldNotCompute>(IterationCount))
457 RewriteLoopExitValues(L);
Chris Lattner6148c022001-12-03 17:28:42 +0000458
Chris Lattner40bf8b42004-04-02 20:24:31 +0000459 // Next, analyze all of the induction variables in the loop, canonicalizing
460 // auxillary induction variables.
461 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
462
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000463 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
464 PHINode *PN = cast<PHINode>(I);
Chris Lattner42a75512007-01-15 02:27:26 +0000465 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattner40bf8b42004-04-02 20:24:31 +0000466 SCEVHandle SCEV = SE->getSCEV(PN);
467 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000468 // FIXME: It is an extremely bad idea to indvar substitute anything more
469 // complex than affine induction variables. Doing so will put expensive
470 // polynomial evaluations inside of the loop, and the str reduction pass
471 // currently can only reduce affine polynomials. For now just disable
472 // indvar subst on anything more complex than an affine addrec.
Chris Lattner595ee7e2004-07-26 02:47:12 +0000473 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000474 if (AR->isAffine())
Chris Lattner595ee7e2004-07-26 02:47:12 +0000475 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000476 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000477 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000478
479 // If there are no induction variables in the loop, there is nothing more to
480 // do.
Chris Lattnerf50af082004-04-17 18:08:33 +0000481 if (IndVars.empty()) {
482 // Actually, if we know how many times the loop iterates, lets insert a
483 // canonical induction variable to help subsequent passes.
484 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner4a7553e2004-04-23 21:29:48 +0000485 SCEVExpander Rewriter(*SE, *LI);
486 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattnerf50af082004-04-17 18:08:33 +0000487 IterationCount->getType());
Chris Lattner9ba46c12006-09-21 05:12:20 +0000488 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
489 Rewriter)) {
490 std::set<Instruction*> InstructionsToDelete;
491 InstructionsToDelete.insert(I);
492 DeleteTriviallyDeadInstructions(InstructionsToDelete);
493 }
Chris Lattnerf50af082004-04-17 18:08:33 +0000494 }
Devang Patel5ee99972007-03-07 06:39:01 +0000495 return Changed;
Chris Lattnerf50af082004-04-17 18:08:33 +0000496 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000497
498 // Compute the type of the largest recurrence expression.
Chris Lattner6148c022001-12-03 17:28:42 +0000499 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000500 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000501 bool DifferingSizes = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000502 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
503 const Type *Ty = IndVars[i].first->getType();
Reid Spencerabaa8ca2007-01-08 16:32:00 +0000504 DifferingSizes |=
505 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
506 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
Chris Lattner40bf8b42004-04-02 20:24:31 +0000507 LargestType = Ty;
Chris Lattner6148c022001-12-03 17:28:42 +0000508 }
509
Chris Lattner40bf8b42004-04-02 20:24:31 +0000510 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000511 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000512
Chris Lattner40bf8b42004-04-02 20:24:31 +0000513 // Now that we know the largest of of the induction variables in this loop,
514 // insert a canonical induction variable of the largest size.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000515 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000516 ++NumInserted;
517 Changed = true;
Chris Lattneree4f13a2007-01-07 01:14:12 +0000518 DOUT << "INDVARS: New CanIV: " << *IndVar;
Chris Lattner15cad752003-12-23 07:47:09 +0000519
Chris Lattner40bf8b42004-04-02 20:24:31 +0000520 if (!isa<SCEVCouldNotCompute>(IterationCount))
Chris Lattner9ba46c12006-09-21 05:12:20 +0000521 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
522 DeadInsts.insert(DI);
Chris Lattner15cad752003-12-23 07:47:09 +0000523
Chris Lattner40bf8b42004-04-02 20:24:31 +0000524 // Now that we have a canonical induction variable, we can rewrite any
525 // recurrences in terms of the induction variable. Start with the auxillary
526 // induction variables, and recursively rewrite any of their uses.
527 BasicBlock::iterator InsertPt = Header->begin();
528 while (isa<PHINode>(InsertPt)) ++InsertPt;
Chris Lattner6148c022001-12-03 17:28:42 +0000529
Chris Lattner5d461d22004-04-21 22:22:01 +0000530 // If there were induction variables of other sizes, cast the primary
531 // induction variable to the right size for them, avoiding the need for the
532 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000533 if (DifferingSizes) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000534 SmallVector<unsigned,4> InsertedSizes;
535 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
536 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
537 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
Chris Lattneref60b2c2007-01-12 22:51:20 +0000538 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
539 == InsertedSizes.end()) {
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000540 PHINode *PN = IndVars[i].first;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000541 InsertedSizes.push_back(ithSize);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000542 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
543 InsertPt);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000544 Rewriter.addInsertedValue(New, SE->getSCEV(New));
Chris Lattneree4f13a2007-01-07 01:14:12 +0000545 DOUT << "INDVARS: Made trunc IV for " << *PN
546 << " NewVal = " << *New << "\n";
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000547 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000548 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000549 }
550
Chris Lattneree4f13a2007-01-07 01:14:12 +0000551 // Rewrite all induction variables in terms of the canonical induction
552 // variable.
Chris Lattner5d461d22004-04-21 22:22:01 +0000553 std::map<unsigned, Value*> InsertedSizes;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000554 while (!IndVars.empty()) {
555 PHINode *PN = IndVars.back().first;
Chris Lattner4a7553e2004-04-23 21:29:48 +0000556 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000557 PN->getType());
Chris Lattneree4f13a2007-01-07 01:14:12 +0000558 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
559 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000560 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000561
Chris Lattner40bf8b42004-04-02 20:24:31 +0000562 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000563 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000564 DeadInsts.insert(PN);
565 IndVars.pop_back();
566 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000567 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000568 }
569
Chris Lattnerb4782d12004-04-22 15:12:36 +0000570#if 0
Chris Lattner1363e852004-04-21 23:36:08 +0000571 // Now replace all derived expressions in the loop body with simpler
572 // expressions.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000573 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
574 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
575 BasicBlock *BB = L->getBlocks()[i];
576 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +0000577 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattner1363e852004-04-21 23:36:08 +0000578 !I->use_empty() &&
Chris Lattner40bf8b42004-04-02 20:24:31 +0000579 !Rewriter.isInsertedInstruction(I)) {
580 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000581 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattner1363e852004-04-21 23:36:08 +0000582 if (V != I) {
Chris Lattner6934a042007-02-11 01:23:03 +0000583 if (isa<Instruction>(V))
584 V->takeName(I);
Chris Lattner1363e852004-04-21 23:36:08 +0000585 I->replaceAllUsesWith(V);
586 DeadInsts.insert(I);
587 ++NumRemoved;
588 Changed = true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000589 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000590 }
Chris Lattner394437f2001-12-04 04:32:29 +0000591 }
Chris Lattnerb4782d12004-04-22 15:12:36 +0000592#endif
Chris Lattner1363e852004-04-21 23:36:08 +0000593
Chris Lattner1363e852004-04-21 23:36:08 +0000594 DeleteTriviallyDeadInstructions(DeadInsts);
Owen Andersoneb705912006-08-25 22:12:36 +0000595
Chris Lattner9caed542007-03-04 01:00:28 +0000596 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000597 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000598}