blob: a5a9f69c2a69a34d62b3fcbd5e3fbb9783459dd1 [file] [log] [blame]
Chris Lattner476e6df2001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner476e6df2001-12-03 17:28:42 +00009//
Chris Lattnere61b67d2004-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 Spencer5495fe82006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattnere61b67d2004-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 Lattner476e6df2001-12-03 17:28:42 +000037//
38//===----------------------------------------------------------------------===//
39
Chris Lattner79a42ac2006-12-19 21:40:18 +000040#define DEBUG_TYPE "indvars"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000041#include "llvm/Transforms/Scalar.h"
Chris Lattnere61b67d2004-04-02 20:24:31 +000042#include "llvm/BasicBlock.h"
Chris Lattner0cec5cb2004-04-15 15:21:43 +000043#include "llvm/Constants.h"
Chris Lattner6449dce2003-12-22 05:02:01 +000044#include "llvm/Instructions.h"
Chris Lattnere61b67d2004-04-02 20:24:31 +000045#include "llvm/Type.h"
Nate Begeman2bca4d92005-07-30 00:12:19 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswellb22e9b42003-12-18 17:19:19 +000047#include "llvm/Analysis/LoopInfo.h"
Chris Lattner83d485b2002-02-12 22:39:50 +000048#include "llvm/Support/CFG.h"
Chris Lattner08165592007-01-07 01:14:12 +000049#include "llvm/Support/Debug.h"
Chris Lattner9776f722004-10-11 23:06:50 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswellb22e9b42003-12-18 17:19:19 +000051#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/CommandLine.h"
53#include "llvm/ADT/Statistic.h"
John Criswellb22e9b42003-12-18 17:19:19 +000054using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000055
Chris Lattner79a42ac2006-12-19 21:40:18 +000056STATISTIC(NumRemoved , "Number of aux indvars removed");
57STATISTIC(NumPointer , "Number of pointer indvars promoted");
58STATISTIC(NumInserted, "Number of canonical indvars added");
59STATISTIC(NumReplaced, "Number of exit values replaced");
60STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattnerd3678bc2003-12-22 03:58:44 +000061
Chris Lattner79a42ac2006-12-19 21:40:18 +000062namespace {
Chris Lattnerd3678bc2003-12-22 03:58:44 +000063 class IndVarSimplify : public FunctionPass {
Chris Lattnere61b67d2004-04-02 20:24:31 +000064 LoopInfo *LI;
65 ScalarEvolution *SE;
Chris Lattner7e755e42003-12-23 07:47:09 +000066 bool Changed;
Chris Lattnerd3678bc2003-12-22 03:58:44 +000067 public:
68 virtual bool runOnFunction(Function &) {
Chris Lattnere61b67d2004-04-02 20:24:31 +000069 LI = &getAnalysis<LoopInfo>();
70 SE = &getAnalysis<ScalarEvolution>();
Chris Lattner7e755e42003-12-23 07:47:09 +000071 Changed = false;
72
Chris Lattnerd3678bc2003-12-22 03:58:44 +000073 // Induction Variables live in the header nodes of loops
Chris Lattnere61b67d2004-04-02 20:24:31 +000074 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner59d2d7f2004-01-08 00:09:44 +000075 runOnLoop(*I);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000076 return Changed;
77 }
78
Chris Lattnerd3678bc2003-12-22 03:58:44 +000079 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerd3678bc2003-12-22 03:58:44 +000080 AU.addRequiredID(LoopSimplifyID);
Chris Lattnere61b67d2004-04-02 20:24:31 +000081 AU.addRequired<ScalarEvolution>();
82 AU.addRequired<LoopInfo>();
Chris Lattnerd3678bc2003-12-22 03:58:44 +000083 AU.addPreservedID(LoopSimplifyID);
Owen Anderson8cca95c2006-08-25 17:41:25 +000084 AU.addPreservedID(LCSSAID);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000085 AU.setPreservesCFG();
86 }
Chris Lattnere61b67d2004-04-02 20:24:31 +000087 private:
88 void runOnLoop(Loop *L);
89 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
90 std::set<Instruction*> &DeadInsts);
Chris Lattner51c95cd2006-09-21 05:12:20 +000091 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
92 SCEVExpander &RW);
Chris Lattnere61b67d2004-04-02 20:24:31 +000093 void RewriteLoopExitValues(Loop *L);
94
95 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000096 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +000097 RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner4184bcc2002-09-10 05:24:05 +000098}
Chris Lattner91daaab2001-12-04 04:32:29 +000099
Chris Lattner3e860842004-09-20 04:43:15 +0000100FunctionPass *llvm::createIndVarSimplifyPass() {
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000101 return new IndVarSimplify();
Chris Lattner91daaab2001-12-04 04:32:29 +0000102}
103
Chris Lattnere61b67d2004-04-02 20:24:31 +0000104/// DeleteTriviallyDeadInstructions - If any of the instructions is the
105/// specified set are trivially dead, delete them and see if this makes any of
106/// their operands subsequently dead.
107void IndVarSimplify::
108DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
109 while (!Insts.empty()) {
110 Instruction *I = *Insts.begin();
111 Insts.erase(Insts.begin());
112 if (isInstructionTriviallyDead(I)) {
113 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
114 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
115 Insts.insert(U);
116 SE->deleteInstructionFromRecords(I);
Chris Lattner08165592007-01-07 01:14:12 +0000117 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattner9776f722004-10-11 23:06:50 +0000118 I->eraseFromParent();
Chris Lattnere61b67d2004-04-02 20:24:31 +0000119 Changed = true;
120 }
121 }
122}
123
124
125/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
126/// recurrence. If so, change it into an integer recurrence, permitting
127/// analysis by the SCEV routines.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000128void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattnere61b67d2004-04-02 20:24:31 +0000129 BasicBlock *Preheader,
130 std::set<Instruction*> &DeadInsts) {
131 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
132 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
133 unsigned BackedgeIdx = PreheaderIdx^1;
134 if (GetElementPtrInst *GEPI =
Chris Lattner677d8572005-08-10 01:12:06 +0000135 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattnere61b67d2004-04-02 20:24:31 +0000136 if (GEPI->getOperand(0) == PN) {
Chris Lattner677d8572005-08-10 01:12:06 +0000137 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattner08165592007-01-07 01:14:12 +0000138 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
139
Chris Lattnere61b67d2004-04-02 20:24:31 +0000140 // Okay, we found a pointer recurrence. Transform this pointer
141 // recurrence into an integer recurrence. Compute the value that gets
142 // added to the pointer at every iteration.
143 Value *AddedVal = GEPI->getOperand(1);
144
145 // Insert a new integer PHI node into the top of the block.
146 PHINode *NewPhi = new PHINode(AddedVal->getType(),
147 PN->getName()+".rec", PN);
Chris Lattnerc9e06332004-06-20 05:04:01 +0000148 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
149
Chris Lattnere61b67d2004-04-02 20:24:31 +0000150 // Create the new add instruction.
Chris Lattnerc9e06332004-06-20 05:04:01 +0000151 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
152 GEPI->getName()+".rec", GEPI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000153 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000154
Chris Lattnere61b67d2004-04-02 20:24:31 +0000155 // Update the existing GEP to use the recurrence.
156 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000157
Chris Lattnere61b67d2004-04-02 20:24:31 +0000158 // Update the GEP to use the new recurrence we just inserted.
159 GEPI->setOperand(1, NewAdd);
160
Chris Lattner9776f722004-10-11 23:06:50 +0000161 // If the incoming value is a constant expr GEP, try peeling out the array
162 // 0 index if possible to make things simpler.
163 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
164 if (CE->getOpcode() == Instruction::GetElementPtr) {
165 unsigned NumOps = CE->getNumOperands();
166 assert(NumOps > 1 && "CE folding didn't work!");
167 if (CE->getOperand(NumOps-1)->isNullValue()) {
168 // Check to make sure the last index really is an array index.
Chris Lattner9c37f232005-11-18 18:30:47 +0000169 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerbca0be82005-11-17 19:35:42 +0000170 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattner9776f722004-10-11 23:06:50 +0000171 i != e; ++i, ++GTI)
172 /*empty*/;
173 if (isa<SequentialType>(*GTI)) {
174 // Pull the last index out of the constant expr GEP.
175 std::vector<Value*> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
176 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
177 CEIdxs);
178 GetElementPtrInst *NGEPI =
Reid Spencerc635f472006-12-31 05:48:39 +0000179 new GetElementPtrInst(NCE, Constant::getNullValue(Type::Int32Ty),
Chris Lattner9776f722004-10-11 23:06:50 +0000180 NewAdd, GEPI->getName(), GEPI);
181 GEPI->replaceAllUsesWith(NGEPI);
182 GEPI->eraseFromParent();
183 GEPI = NGEPI;
184 }
185 }
186 }
187
188
Chris Lattnere61b67d2004-04-02 20:24:31 +0000189 // Finally, if there are any other users of the PHI node, we must
190 // insert a new GEP instruction that uses the pre-incremented version
191 // of the induction amount.
192 if (!PN->use_empty()) {
193 BasicBlock::iterator InsertPos = PN; ++InsertPos;
194 while (isa<PHINode>(InsertPos)) ++InsertPos;
195 std::string Name = PN->getName(); PN->setName("");
196 Value *PreInc =
197 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
198 std::vector<Value*>(1, NewPhi), Name,
199 InsertPos);
200 PN->replaceAllUsesWith(PreInc);
201 }
202
203 // Delete the old PHI for sure, and the GEP if its otherwise unused.
204 DeadInsts.insert(PN);
205
206 ++NumPointer;
207 Changed = true;
208 }
209}
210
211/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000212/// loop to be a canonical != comparison against the incremented loop induction
213/// variable. This pass is able to rewrite the exit tests of any loop where the
214/// SCEV analysis can determine a loop-invariant trip count of the loop, which
215/// is actually a much broader range than just linear tests.
Chris Lattner51c95cd2006-09-21 05:12:20 +0000216///
217/// This method returns a "potentially dead" instruction whose computation chain
218/// should be deleted when convenient.
219Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
220 SCEV *IterationCount,
221 SCEVExpander &RW) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000222 // Find the exit block for the loop. We can currently only handle loops with
223 // a single exit.
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000224 std::vector<BasicBlock*> ExitBlocks;
225 L->getExitBlocks(ExitBlocks);
Chris Lattner51c95cd2006-09-21 05:12:20 +0000226 if (ExitBlocks.size() != 1) return 0;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000227 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattnere61b67d2004-04-02 20:24:31 +0000228
229 // Make sure there is only one predecessor block in the loop.
230 BasicBlock *ExitingBlock = 0;
231 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
232 PI != PE; ++PI)
233 if (L->contains(*PI)) {
234 if (ExitingBlock == 0)
235 ExitingBlock = *PI;
236 else
Chris Lattner51c95cd2006-09-21 05:12:20 +0000237 return 0; // Multiple exits from loop to this block.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000238 }
239 assert(ExitingBlock && "Loop info is broken");
240
241 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
Chris Lattner51c95cd2006-09-21 05:12:20 +0000242 return 0; // Can't rewrite non-branch yet
Chris Lattnere61b67d2004-04-02 20:24:31 +0000243 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
244 assert(BI->isConditional() && "Must be conditional to be part of loop!");
245
Chris Lattner51c95cd2006-09-21 05:12:20 +0000246 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
247
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000248 // If the exiting block is not the same as the backedge block, we must compare
249 // against the preincremented value, otherwise we prefer to compare against
250 // the post-incremented value.
251 BasicBlock *Header = L->getHeader();
252 pred_iterator HPI = pred_begin(Header);
253 assert(HPI != pred_end(Header) && "Loop with zero preds???");
254 if (!L->contains(*HPI)) ++HPI;
255 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
256 "No backedge in loop?");
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000257
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000258 SCEVHandle TripCount = IterationCount;
259 Value *IndVar;
260 if (*HPI == ExitingBlock) {
261 // The IterationCount expression contains the number of times that the
262 // backedge actually branches to the loop header. This is one less than the
263 // number of times the loop executes, so add one to it.
264 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
265 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
266 IndVar = L->getCanonicalInductionVariableIncrement();
267 } else {
268 // We have to use the preincremented value...
269 IndVar = L->getCanonicalInductionVariable();
270 }
Chris Lattner08165592007-01-07 01:14:12 +0000271
272 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
273 << " IndVar = " << *IndVar << "\n";
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000274
Chris Lattnere61b67d2004-04-02 20:24:31 +0000275 // Expand the code for the iteration count into the preheader of the loop.
276 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattner83cd87e2004-04-23 21:29:48 +0000277 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
Chris Lattnere61b67d2004-04-02 20:24:31 +0000278 IndVar->getType());
279
Reid Spencer266e42b2006-12-23 06:05:41 +0000280 // Insert a new icmp_ne or icmp_eq instruction before the branch.
281 ICmpInst::Predicate Opcode;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000282 if (L->contains(BI->getSuccessor(0)))
Reid Spencer266e42b2006-12-23 06:05:41 +0000283 Opcode = ICmpInst::ICMP_NE;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000284 else
Reid Spencer266e42b2006-12-23 06:05:41 +0000285 Opcode = ICmpInst::ICMP_EQ;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000286
Reid Spencer266e42b2006-12-23 06:05:41 +0000287 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000288 BI->setCondition(Cond);
289 ++NumLFTR;
290 Changed = true;
Chris Lattner51c95cd2006-09-21 05:12:20 +0000291 return PotentiallyDeadInst;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000292}
293
294
295/// RewriteLoopExitValues - Check to see if this loop has a computable
296/// loop-invariant execution count. If so, this means that we can compute the
297/// final value of any expressions that are recurrent in the loop, and
298/// substitute the exit values from the loop into any instructions outside of
299/// the loop that use the final values of the current expressions.
300void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
301 BasicBlock *Preheader = L->getLoopPreheader();
302
303 // Scan all of the instructions in the loop, looking at those that have
304 // extra-loop users and which are recurrences.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000305 SCEVExpander Rewriter(*SE, *LI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000306
307 // We insert the code into the preheader of the loop if the loop contains
308 // multiple exit blocks, or in the exit block if there is exactly one.
309 BasicBlock *BlockToInsertInto;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000310 std::vector<BasicBlock*> ExitBlocks;
311 L->getExitBlocks(ExitBlocks);
312 if (ExitBlocks.size() == 1)
313 BlockToInsertInto = ExitBlocks[0];
Chris Lattnere61b67d2004-04-02 20:24:31 +0000314 else
315 BlockToInsertInto = Preheader;
316 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
317 while (isa<PHINode>(InsertPt)) ++InsertPt;
318
Chris Lattnera8140802004-04-17 18:44:09 +0000319 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
320
Chris Lattnere61b67d2004-04-02 20:24:31 +0000321 std::set<Instruction*> InstructionsToDelete;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000322
Chris Lattnere61b67d2004-04-02 20:24:31 +0000323 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
324 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
325 BasicBlock *BB = L->getBlocks()[i];
Chris Lattnerdf815392005-06-15 21:29:31 +0000326 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000327 if (I->getType()->isInteger()) { // Is an integer instruction
328 SCEVHandle SH = SE->getSCEV(I);
Chris Lattnera8140802004-04-17 18:44:09 +0000329 if (SH->hasComputableLoopEvolution(L) || // Varies predictably
330 HasConstantItCount) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000331 // Find out if this predictably varying value is actually used
332 // outside of the loop. "extra" as opposed to "intra".
Chris Lattner053fb932006-06-17 01:02:31 +0000333 std::vector<Instruction*> ExtraLoopUsers;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000334 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Chris Lattner053fb932006-06-17 01:02:31 +0000335 UI != E; ++UI) {
336 Instruction *User = cast<Instruction>(*UI);
Chris Lattner9b6c02e2006-07-13 19:05:20 +0000337 if (!L->contains(User->getParent())) {
338 // If this is a PHI node in the exit block and we're inserting,
339 // into the exit block, it must have a single entry. In this
340 // case, we can't insert the code after the PHI and have the PHI
341 // still use it. Instead, don't insert the the PHI.
342 if (PHINode *PN = dyn_cast<PHINode>(User)) {
343 // FIXME: This is a case where LCSSA pessimizes code, this
344 // should be fixed better.
345 if (PN->getNumOperands() == 2 &&
346 PN->getParent() == BlockToInsertInto)
347 continue;
348 }
Chris Lattner053fb932006-06-17 01:02:31 +0000349 ExtraLoopUsers.push_back(User);
Chris Lattner9b6c02e2006-07-13 19:05:20 +0000350 }
Chris Lattner053fb932006-06-17 01:02:31 +0000351 }
352
Chris Lattnere61b67d2004-04-02 20:24:31 +0000353 if (!ExtraLoopUsers.empty()) {
354 // Okay, this instruction has a user outside of the current loop
355 // and varies predictably in this loop. Evaluate the value it
356 // contains when the loop exits, and insert code for it.
Chris Lattnera8140802004-04-17 18:44:09 +0000357 SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
Chris Lattnere61b67d2004-04-02 20:24:31 +0000358 if (!isa<SCEVCouldNotCompute>(ExitValue)) {
359 Changed = true;
360 ++NumReplaced;
Chris Lattnerdf815392005-06-15 21:29:31 +0000361 // Remember the next instruction. The rewriter can move code
362 // around in some cases.
363 BasicBlock::iterator NextI = I; ++NextI;
364
Chris Lattner83cd87e2004-04-23 21:29:48 +0000365 Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
Chris Lattnere61b67d2004-04-02 20:24:31 +0000366 I->getType());
367
Chris Lattner08165592007-01-07 01:14:12 +0000368 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *NewVal
369 << " LoopVal = " << *I << "\n";
370
Chris Lattnere61b67d2004-04-02 20:24:31 +0000371 // Rewrite any users of the computed value outside of the loop
372 // with the newly computed value.
Owen Andersonbea70ee2006-07-14 18:49:15 +0000373 for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i) {
374 PHINode* PN = dyn_cast<PHINode>(ExtraLoopUsers[i]);
375 if (PN && PN->getNumOperands() == 2 &&
376 !L->contains(PN->getParent())) {
377 // We're dealing with an LCSSA Phi. Handle it specially.
378 Instruction* LCSSAInsertPt = BlockToInsertInto->begin();
379
380 Instruction* NewInstr = dyn_cast<Instruction>(NewVal);
381 if (NewInstr && !isa<PHINode>(NewInstr) &&
382 !L->contains(NewInstr->getParent()))
383 for (unsigned j = 0; j < NewInstr->getNumOperands(); ++j){
384 Instruction* PredI =
385 dyn_cast<Instruction>(NewInstr->getOperand(j));
386 if (PredI && L->contains(PredI->getParent())) {
387 PHINode* NewLCSSA = new PHINode(PredI->getType(),
388 PredI->getName() + ".lcssa",
389 LCSSAInsertPt);
390 NewLCSSA->addIncoming(PredI,
391 BlockToInsertInto->getSinglePredecessor());
392
393 NewInstr->replaceUsesOfWith(PredI, NewLCSSA);
394 }
395 }
396
397 PN->replaceAllUsesWith(NewVal);
398 PN->eraseFromParent();
399 } else {
400 ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
401 }
402 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000403
404 // If this instruction is dead now, schedule it to be removed.
405 if (I->use_empty())
406 InstructionsToDelete.insert(I);
Chris Lattnerdf815392005-06-15 21:29:31 +0000407 I = NextI;
408 continue; // Skip the ++I
Chris Lattnere61b67d2004-04-02 20:24:31 +0000409 }
410 }
411 }
412 }
Chris Lattnerdf815392005-06-15 21:29:31 +0000413
414 // Next instruction. Continue instruction skips this.
415 ++I;
416 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000417 }
418
419 DeleteTriviallyDeadInstructions(InstructionsToDelete);
420}
421
422
423void IndVarSimplify::runOnLoop(Loop *L) {
424 // First step. Check to see if there are any trivial GEP pointer recurrences.
425 // If there are, change them into integer recurrences, permitting analysis by
426 // the SCEV routines.
427 //
428 BasicBlock *Header = L->getHeader();
429 BasicBlock *Preheader = L->getLoopPreheader();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000430
Chris Lattnere61b67d2004-04-02 20:24:31 +0000431 std::set<Instruction*> DeadInsts;
Reid Spencer66149462004-09-15 17:06:42 +0000432 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
433 PHINode *PN = cast<PHINode>(I);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000434 if (isa<PointerType>(PN->getType()))
435 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Reid Spencer66149462004-09-15 17:06:42 +0000436 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000437
438 if (!DeadInsts.empty())
439 DeleteTriviallyDeadInstructions(DeadInsts);
440
441
442 // Next, transform all loops nesting inside of this loop.
443 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000444 runOnLoop(*I);
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000445
Chris Lattnere61b67d2004-04-02 20:24:31 +0000446 // Check to see if this loop has a computable loop-invariant execution count.
447 // If so, this means that we can compute the final value of any expressions
448 // that are recurrent in the loop, and substitute the exit values from the
449 // loop into any instructions outside of the loop that use the final values of
450 // the current expressions.
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000451 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000452 SCEVHandle IterationCount = SE->getIterationCount(L);
453 if (!isa<SCEVCouldNotCompute>(IterationCount))
454 RewriteLoopExitValues(L);
Chris Lattner476e6df2001-12-03 17:28:42 +0000455
Chris Lattnere61b67d2004-04-02 20:24:31 +0000456 // Next, analyze all of the induction variables in the loop, canonicalizing
457 // auxillary induction variables.
458 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
459
Reid Spencer66149462004-09-15 17:06:42 +0000460 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
461 PHINode *PN = cast<PHINode>(I);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000462 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
463 SCEVHandle SCEV = SE->getSCEV(PN);
464 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattner677d8572005-08-10 01:12:06 +0000465 // FIXME: It is an extremely bad idea to indvar substitute anything more
466 // complex than affine induction variables. Doing so will put expensive
467 // polynomial evaluations inside of the loop, and the str reduction pass
468 // currently can only reduce affine polynomials. For now just disable
469 // indvar subst on anything more complex than an affine addrec.
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000470 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattner677d8572005-08-10 01:12:06 +0000471 if (AR->isAffine())
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000472 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattnere61b67d2004-04-02 20:24:31 +0000473 }
Reid Spencer66149462004-09-15 17:06:42 +0000474 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000475
476 // If there are no induction variables in the loop, there is nothing more to
477 // do.
Chris Lattner885a6eb2004-04-17 18:08:33 +0000478 if (IndVars.empty()) {
479 // Actually, if we know how many times the loop iterates, lets insert a
480 // canonical induction variable to help subsequent passes.
481 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner83cd87e2004-04-23 21:29:48 +0000482 SCEVExpander Rewriter(*SE, *LI);
483 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattner885a6eb2004-04-17 18:08:33 +0000484 IterationCount->getType());
Chris Lattner51c95cd2006-09-21 05:12:20 +0000485 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
486 Rewriter)) {
487 std::set<Instruction*> InstructionsToDelete;
488 InstructionsToDelete.insert(I);
489 DeleteTriviallyDeadInstructions(InstructionsToDelete);
490 }
Chris Lattner885a6eb2004-04-17 18:08:33 +0000491 }
492 return;
493 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000494
495 // Compute the type of the largest recurrence expression.
Chris Lattner476e6df2001-12-03 17:28:42 +0000496 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000497 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000498 bool DifferingSizes = false;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000499 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
500 const Type *Ty = IndVars[i].first->getType();
Reid Spencer8f166b02007-01-08 16:32:00 +0000501 DifferingSizes |=
502 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
503 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
Chris Lattnere61b67d2004-04-02 20:24:31 +0000504 LargestType = Ty;
Chris Lattner476e6df2001-12-03 17:28:42 +0000505 }
506
Chris Lattnere61b67d2004-04-02 20:24:31 +0000507 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000508 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner7e755e42003-12-23 07:47:09 +0000509
Chris Lattnere61b67d2004-04-02 20:24:31 +0000510 // Now that we know the largest of of the induction variables in this loop,
511 // insert a canonical induction variable of the largest size.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000512 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000513 ++NumInserted;
514 Changed = true;
Chris Lattner08165592007-01-07 01:14:12 +0000515 DOUT << "INDVARS: New CanIV: " << *IndVar;
Chris Lattner7e755e42003-12-23 07:47:09 +0000516
Chris Lattnere61b67d2004-04-02 20:24:31 +0000517 if (!isa<SCEVCouldNotCompute>(IterationCount))
Chris Lattner51c95cd2006-09-21 05:12:20 +0000518 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
519 DeadInsts.insert(DI);
Chris Lattner7e755e42003-12-23 07:47:09 +0000520
Chris Lattnere61b67d2004-04-02 20:24:31 +0000521 // Now that we have a canonical induction variable, we can rewrite any
522 // recurrences in terms of the induction variable. Start with the auxillary
523 // induction variables, and recursively rewrite any of their uses.
524 BasicBlock::iterator InsertPt = Header->begin();
525 while (isa<PHINode>(InsertPt)) ++InsertPt;
Chris Lattner476e6df2001-12-03 17:28:42 +0000526
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000527 // If there were induction variables of other sizes, cast the primary
528 // induction variable to the right size for them, avoiding the need for the
529 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000530 if (DifferingSizes) {
531 bool InsertedSizes[17] = { false };
532 InsertedSizes[LargestType->getPrimitiveSize()] = true;
533 for (unsigned i = 0, e = IndVars.size(); i != e; ++i)
534 if (!InsertedSizes[IndVars[i].first->getType()->getPrimitiveSize()]) {
535 PHINode *PN = IndVars[i].first;
536 InsertedSizes[PN->getType()->getPrimitiveSize()] = true;
Chris Lattner08165592007-01-07 01:14:12 +0000537 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
538 InsertPt);
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000539 Rewriter.addInsertedValue(New, SE->getSCEV(New));
Chris Lattner08165592007-01-07 01:14:12 +0000540 DOUT << "INDVARS: Made trunc IV for " << *PN
541 << " NewVal = " << *New << "\n";
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000542 }
543 }
544
Chris Lattner08165592007-01-07 01:14:12 +0000545 // Rewrite all induction variables in terms of the canonical induction
546 // variable.
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000547 std::map<unsigned, Value*> InsertedSizes;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000548 while (!IndVars.empty()) {
549 PHINode *PN = IndVars.back().first;
Chris Lattner83cd87e2004-04-23 21:29:48 +0000550 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000551 PN->getType());
Chris Lattner08165592007-01-07 01:14:12 +0000552 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
553 << " into = " << *NewVal << "\n";
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000554 std::string Name = PN->getName();
555 PN->setName("");
556 NewVal->setName(Name);
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000557
Chris Lattnere61b67d2004-04-02 20:24:31 +0000558 // Replace the old PHI Node with the inserted computation.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000559 PN->replaceAllUsesWith(NewVal);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000560 DeadInsts.insert(PN);
561 IndVars.pop_back();
562 ++NumRemoved;
Chris Lattner67439402001-12-05 19:41:33 +0000563 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000564 }
565
Chris Lattnerc27302c2004-04-22 15:12:36 +0000566#if 0
Chris Lattneraf532f22004-04-21 23:36:08 +0000567 // Now replace all derived expressions in the loop body with simpler
568 // expressions.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000569 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
570 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
571 BasicBlock *BB = L->getBlocks()[i];
572 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
573 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattneraf532f22004-04-21 23:36:08 +0000574 !I->use_empty() &&
Chris Lattnere61b67d2004-04-02 20:24:31 +0000575 !Rewriter.isInsertedInstruction(I)) {
576 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner83cd87e2004-04-23 21:29:48 +0000577 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattneraf532f22004-04-21 23:36:08 +0000578 if (V != I) {
579 if (isa<Instruction>(V)) {
580 std::string Name = I->getName();
581 I->setName("");
582 V->setName(Name);
583 }
584 I->replaceAllUsesWith(V);
585 DeadInsts.insert(I);
586 ++NumRemoved;
587 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000588 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000589 }
Chris Lattner91daaab2001-12-04 04:32:29 +0000590 }
Chris Lattnerc27302c2004-04-22 15:12:36 +0000591#endif
Chris Lattneraf532f22004-04-21 23:36:08 +0000592
Chris Lattneraf532f22004-04-21 23:36:08 +0000593 DeleteTriviallyDeadInstructions(DeadInsts);
Owen Anderson8e4b0292006-08-25 22:12:36 +0000594
595 if (mustPreserveAnalysisID(LCSSAID)) assert(L->isLCSSAForm());
Chris Lattner476e6df2001-12-03 17:28:42 +0000596}