blob: f909cc233b5946046dc65cdf2277086758266639 [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"
Reid Spencer557ab152007-02-05 23:32:05 +000049#include "llvm/Support/Compiler.h"
Chris Lattner08165592007-01-07 01:14:12 +000050#include "llvm/Support/Debug.h"
Chris Lattner9776f722004-10-11 23:06:50 +000051#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswellb22e9b42003-12-18 17:19:19 +000052#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000053#include "llvm/Support/CommandLine.h"
Reid Spencer7a9c62b2007-01-12 07:05:14 +000054#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000055#include "llvm/ADT/Statistic.h"
John Criswellb22e9b42003-12-18 17:19:19 +000056using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner79a42ac2006-12-19 21:40:18 +000058STATISTIC(NumRemoved , "Number of aux indvars removed");
59STATISTIC(NumPointer , "Number of pointer indvars promoted");
60STATISTIC(NumInserted, "Number of canonical indvars added");
61STATISTIC(NumReplaced, "Number of exit values replaced");
62STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattnerd3678bc2003-12-22 03:58:44 +000063
Chris Lattner79a42ac2006-12-19 21:40:18 +000064namespace {
Reid Spencer557ab152007-02-05 23:32:05 +000065 class VISIBILITY_HIDDEN IndVarSimplify : public FunctionPass {
Chris Lattnere61b67d2004-04-02 20:24:31 +000066 LoopInfo *LI;
67 ScalarEvolution *SE;
Chris Lattner7e755e42003-12-23 07:47:09 +000068 bool Changed;
Chris Lattnerd3678bc2003-12-22 03:58:44 +000069 public:
70 virtual bool runOnFunction(Function &) {
Chris Lattnere61b67d2004-04-02 20:24:31 +000071 LI = &getAnalysis<LoopInfo>();
72 SE = &getAnalysis<ScalarEvolution>();
Chris Lattner7e755e42003-12-23 07:47:09 +000073 Changed = false;
74
Chris Lattnerd3678bc2003-12-22 03:58:44 +000075 // Induction Variables live in the header nodes of loops
Chris Lattnere61b67d2004-04-02 20:24:31 +000076 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner59d2d7f2004-01-08 00:09:44 +000077 runOnLoop(*I);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000078 return Changed;
79 }
80
Chris Lattnerd3678bc2003-12-22 03:58:44 +000081 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerd3678bc2003-12-22 03:58:44 +000082 AU.addRequiredID(LoopSimplifyID);
Chris Lattnere61b67d2004-04-02 20:24:31 +000083 AU.addRequired<ScalarEvolution>();
84 AU.addRequired<LoopInfo>();
Chris Lattnerd3678bc2003-12-22 03:58:44 +000085 AU.addPreservedID(LoopSimplifyID);
Owen Anderson8cca95c2006-08-25 17:41:25 +000086 AU.addPreservedID(LCSSAID);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000087 AU.setPreservesCFG();
88 }
Chris Lattnere61b67d2004-04-02 20:24:31 +000089 private:
90 void runOnLoop(Loop *L);
91 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
92 std::set<Instruction*> &DeadInsts);
Chris Lattner51c95cd2006-09-21 05:12:20 +000093 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
94 SCEVExpander &RW);
Chris Lattnere61b67d2004-04-02 20:24:31 +000095 void RewriteLoopExitValues(Loop *L);
96
97 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000098 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +000099 RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner4184bcc2002-09-10 05:24:05 +0000100}
Chris Lattner91daaab2001-12-04 04:32:29 +0000101
Chris Lattner3e860842004-09-20 04:43:15 +0000102FunctionPass *llvm::createIndVarSimplifyPass() {
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000103 return new IndVarSimplify();
Chris Lattner91daaab2001-12-04 04:32:29 +0000104}
105
Chris Lattnere61b67d2004-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 Lattner08165592007-01-07 01:14:12 +0000119 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattner9776f722004-10-11 23:06:50 +0000120 I->eraseFromParent();
Chris Lattnere61b67d2004-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 Brukmanb1c93172005-04-21 23:48:37 +0000130void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattnere61b67d2004-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 Lattner677d8572005-08-10 01:12:06 +0000137 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattnere61b67d2004-04-02 20:24:31 +0000138 if (GEPI->getOperand(0) == PN) {
Chris Lattner677d8572005-08-10 01:12:06 +0000139 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattner08165592007-01-07 01:14:12 +0000140 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
141
Chris Lattnere61b67d2004-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 Lattnerc9e06332004-06-20 05:04:01 +0000150 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
151
Chris Lattnere61b67d2004-04-02 20:24:31 +0000152 // Create the new add instruction.
Chris Lattnerc9e06332004-06-20 05:04:01 +0000153 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
154 GEPI->getName()+".rec", GEPI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000155 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000156
Chris Lattnere61b67d2004-04-02 20:24:31 +0000157 // Update the existing GEP to use the recurrence.
158 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000159
Chris Lattnere61b67d2004-04-02 20:24:31 +0000160 // Update the GEP to use the new recurrence we just inserted.
161 GEPI->setOperand(1, NewAdd);
162
Chris Lattner9776f722004-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 Lattner9c37f232005-11-18 18:30:47 +0000171 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerbca0be82005-11-17 19:35:42 +0000172 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattner9776f722004-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 Lattnerf96f4a82007-01-31 04:40:53 +0000177 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattner9776f722004-10-11 23:06:50 +0000178 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000179 &CEIdxs[0],
180 CEIdxs.size());
Reid Spencer2e54a152007-03-02 00:28:52 +0000181 GetElementPtrInst *NGEPI = new GetElementPtrInst(
182 NCE, Constant::getNullValue(Type::Int32Ty), NewAdd,
183 GEPI->getName(), GEPI);
Chris Lattner9776f722004-10-11 23:06:50 +0000184 GEPI->replaceAllUsesWith(NGEPI);
185 GEPI->eraseFromParent();
186 GEPI = NGEPI;
187 }
188 }
189 }
190
191
Chris Lattnere61b67d2004-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 Lattnere61b67d2004-04-02 20:24:31 +0000198 Value *PreInc =
199 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
Chris Lattner6e0123b2007-02-11 01:23:03 +0000200 NewPhi, "", InsertPos);
201 PreInc->takeName(PN);
Chris Lattnere61b67d2004-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 Lattner0cec5cb2004-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 Lattner51c95cd2006-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 Lattnere61b67d2004-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 Lattnerd72c3eb2004-04-18 22:14:10 +0000226 std::vector<BasicBlock*> ExitBlocks;
227 L->getExitBlocks(ExitBlocks);
Chris Lattner51c95cd2006-09-21 05:12:20 +0000228 if (ExitBlocks.size() != 1) return 0;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000229 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattnere61b67d2004-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 Lattner51c95cd2006-09-21 05:12:20 +0000239 return 0; // Multiple exits from loop to this block.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000240 }
241 assert(ExitingBlock && "Loop info is broken");
242
243 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
Chris Lattner51c95cd2006-09-21 05:12:20 +0000244 return 0; // Can't rewrite non-branch yet
Chris Lattnere61b67d2004-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 Lattner51c95cd2006-09-21 05:12:20 +0000248 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
249
Chris Lattnerd7a559e2004-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 Lattner0cec5cb2004-04-15 15:21:43 +0000259
Chris Lattnerd7a559e2004-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 Lattner08165592007-01-07 01:14:12 +0000273
274 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
275 << " IndVar = " << *IndVar << "\n";
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000276
Chris Lattnere61b67d2004-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 Lattner83cd87e2004-04-23 21:29:48 +0000279 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
Chris Lattnere61b67d2004-04-02 20:24:31 +0000280 IndVar->getType());
281
Reid Spencer266e42b2006-12-23 06:05:41 +0000282 // Insert a new icmp_ne or icmp_eq instruction before the branch.
283 ICmpInst::Predicate Opcode;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000284 if (L->contains(BI->getSuccessor(0)))
Reid Spencer266e42b2006-12-23 06:05:41 +0000285 Opcode = ICmpInst::ICMP_NE;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000286 else
Reid Spencer266e42b2006-12-23 06:05:41 +0000287 Opcode = ICmpInst::ICMP_EQ;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000288
Reid Spencer266e42b2006-12-23 06:05:41 +0000289 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000290 BI->setCondition(Cond);
291 ++NumLFTR;
292 Changed = true;
Chris Lattner51c95cd2006-09-21 05:12:20 +0000293 return PotentiallyDeadInst;
Chris Lattnere61b67d2004-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 Lattner83cd87e2004-04-23 21:29:48 +0000307 SCEVExpander Rewriter(*SE, *LI);
Chris Lattnere61b67d2004-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 Lattnerd72c3eb2004-04-18 22:14:10 +0000312 std::vector<BasicBlock*> ExitBlocks;
313 L->getExitBlocks(ExitBlocks);
314 if (ExitBlocks.size() == 1)
315 BlockToInsertInto = ExitBlocks[0];
Chris Lattnere61b67d2004-04-02 20:24:31 +0000316 else
317 BlockToInsertInto = Preheader;
318 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
319 while (isa<PHINode>(InsertPt)) ++InsertPt;
320
Chris Lattnera8140802004-04-17 18:44:09 +0000321 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
322
Chris Lattnere61b67d2004-04-02 20:24:31 +0000323 std::set<Instruction*> InstructionsToDelete;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000324
Chris Lattnered30abf2007-03-03 22:48:48 +0000325 // Loop over all of the integer-valued instructions in this loop, but that are
326 // not in a subloop.
327 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
328 if (LI->getLoopFor(L->getBlocks()[i]) != L)
329 continue; // The Block is in a subloop, skip it.
330 BasicBlock *BB = L->getBlocks()[i];
331 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
332 Instruction *I = II++;
333
334 if (!I->getType()->isInteger())
335 continue; // SCEV only supports integer expressions for now.
336
337 SCEVHandle SH = SE->getSCEV(I);
338 if (!HasConstantItCount &&
339 !SH->hasComputableLoopEvolution(L)) { // Varies predictably
340 continue; // Cannot exit evolution for the loop value.
Chris Lattnerdf815392005-06-15 21:29:31 +0000341 }
Chris Lattnered30abf2007-03-03 22:48:48 +0000342
343 // Find out if this predictably varying value is actually used
344 // outside of the loop. "Extra" is as opposed to "intra".
345 std::vector<Instruction*> ExtraLoopUsers;
346 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
347 UI != E; ++UI) {
348 Instruction *User = cast<Instruction>(*UI);
349 if (!L->contains(User->getParent())) {
350 // If this is a PHI node in the exit block and we're inserting,
351 // into the exit block, it must have a single entry. In this
352 // case, we can't insert the code after the PHI and have the PHI
353 // still use it. Instead, don't insert the the PHI.
354 if (PHINode *PN = dyn_cast<PHINode>(User)) {
355 // FIXME: This is a case where LCSSA pessimizes code, this
356 // should be fixed better.
357 if (PN->getNumOperands() == 2 &&
358 PN->getParent() == BlockToInsertInto)
359 continue;
360 }
361 ExtraLoopUsers.push_back(User);
362 }
363 }
364
365 // If nothing outside the loop uses this value, don't rewrite it.
366 if (ExtraLoopUsers.empty())
367 continue;
368
369 // Okay, this instruction has a user outside of the current loop
370 // and varies predictably *inside* the loop. Evaluate the value it
371 // contains when the loop exits if possible.
372 SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
373 if (isa<SCEVCouldNotCompute>(ExitValue))
374 continue;
375
376 Changed = true;
377 ++NumReplaced;
378
379 Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
380 I->getType());
Chris Lattnere61b67d2004-04-02 20:24:31 +0000381
Chris Lattnered30abf2007-03-03 22:48:48 +0000382 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *NewVal
383 << " LoopVal = " << *I << "\n";
384
385 // Rewrite any users of the computed value outside of the loop
386 // with the newly computed value.
387 for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i) {
388 PHINode* PN = dyn_cast<PHINode>(ExtraLoopUsers[i]);
389 if (PN && PN->getNumOperands() == 2 &&
390 !L->contains(PN->getParent())) {
391 // We're dealing with an LCSSA Phi. Handle it specially.
392 Instruction* LCSSAInsertPt = BlockToInsertInto->begin();
393
394 Instruction* NewInstr = dyn_cast<Instruction>(NewVal);
395 if (NewInstr && !isa<PHINode>(NewInstr) &&
396 !L->contains(NewInstr->getParent()))
397 for (unsigned j = 0; j != NewInstr->getNumOperands(); ++j) {
398 Instruction* PredI =
399 dyn_cast<Instruction>(NewInstr->getOperand(j));
400 if (PredI && L->contains(PredI->getParent())) {
401 PHINode* NewLCSSA = new PHINode(PredI->getType(),
402 PredI->getName() + ".lcssa",
403 LCSSAInsertPt);
404 NewLCSSA->addIncoming(PredI,
405 BlockToInsertInto->getSinglePredecessor());
406
407 NewInstr->replaceUsesOfWith(PredI, NewLCSSA);
408 }
409 }
410
411 PN->replaceAllUsesWith(NewVal);
412 PN->eraseFromParent();
413 } else {
414 ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
415 }
416 }
417
418 // If this instruction is dead now, schedule it to be removed.
419 if (I->use_empty())
420 InstructionsToDelete.insert(I);
421 }
422 }
423
Chris Lattnere61b67d2004-04-02 20:24:31 +0000424 DeleteTriviallyDeadInstructions(InstructionsToDelete);
425}
426
427
428void IndVarSimplify::runOnLoop(Loop *L) {
429 // First step. Check to see if there are any trivial GEP pointer recurrences.
430 // If there are, change them into integer recurrences, permitting analysis by
431 // the SCEV routines.
432 //
433 BasicBlock *Header = L->getHeader();
434 BasicBlock *Preheader = L->getLoopPreheader();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000435
Chris Lattnere61b67d2004-04-02 20:24:31 +0000436 std::set<Instruction*> DeadInsts;
Reid Spencer66149462004-09-15 17:06:42 +0000437 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
438 PHINode *PN = cast<PHINode>(I);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000439 if (isa<PointerType>(PN->getType()))
440 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Reid Spencer66149462004-09-15 17:06:42 +0000441 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000442
443 if (!DeadInsts.empty())
444 DeleteTriviallyDeadInstructions(DeadInsts);
445
446
447 // Next, transform all loops nesting inside of this loop.
448 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000449 runOnLoop(*I);
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000450
Chris Lattnere61b67d2004-04-02 20:24:31 +0000451 // Check to see if this loop has a computable loop-invariant execution count.
452 // If so, this means that we can compute the final value of any expressions
453 // that are recurrent in the loop, and substitute the exit values from the
454 // loop into any instructions outside of the loop that use the final values of
455 // the current expressions.
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000456 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000457 SCEVHandle IterationCount = SE->getIterationCount(L);
458 if (!isa<SCEVCouldNotCompute>(IterationCount))
459 RewriteLoopExitValues(L);
Chris Lattner476e6df2001-12-03 17:28:42 +0000460
Chris Lattnere61b67d2004-04-02 20:24:31 +0000461 // Next, analyze all of the induction variables in the loop, canonicalizing
462 // auxillary induction variables.
463 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
464
Reid Spencer66149462004-09-15 17:06:42 +0000465 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
466 PHINode *PN = cast<PHINode>(I);
Chris Lattner03c49532007-01-15 02:27:26 +0000467 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattnere61b67d2004-04-02 20:24:31 +0000468 SCEVHandle SCEV = SE->getSCEV(PN);
469 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattner677d8572005-08-10 01:12:06 +0000470 // FIXME: It is an extremely bad idea to indvar substitute anything more
471 // complex than affine induction variables. Doing so will put expensive
472 // polynomial evaluations inside of the loop, and the str reduction pass
473 // currently can only reduce affine polynomials. For now just disable
474 // indvar subst on anything more complex than an affine addrec.
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000475 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattner677d8572005-08-10 01:12:06 +0000476 if (AR->isAffine())
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000477 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattnere61b67d2004-04-02 20:24:31 +0000478 }
Reid Spencer66149462004-09-15 17:06:42 +0000479 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000480
481 // If there are no induction variables in the loop, there is nothing more to
482 // do.
Chris Lattner885a6eb2004-04-17 18:08:33 +0000483 if (IndVars.empty()) {
484 // Actually, if we know how many times the loop iterates, lets insert a
485 // canonical induction variable to help subsequent passes.
486 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner83cd87e2004-04-23 21:29:48 +0000487 SCEVExpander Rewriter(*SE, *LI);
488 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattner885a6eb2004-04-17 18:08:33 +0000489 IterationCount->getType());
Chris Lattner51c95cd2006-09-21 05:12:20 +0000490 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
491 Rewriter)) {
492 std::set<Instruction*> InstructionsToDelete;
493 InstructionsToDelete.insert(I);
494 DeleteTriviallyDeadInstructions(InstructionsToDelete);
495 }
Chris Lattner885a6eb2004-04-17 18:08:33 +0000496 }
497 return;
498 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000499
500 // Compute the type of the largest recurrence expression.
Chris Lattner476e6df2001-12-03 17:28:42 +0000501 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000502 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000503 bool DifferingSizes = false;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000504 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
505 const Type *Ty = IndVars[i].first->getType();
Reid Spencer8f166b02007-01-08 16:32:00 +0000506 DifferingSizes |=
507 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
508 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
Chris Lattnere61b67d2004-04-02 20:24:31 +0000509 LargestType = Ty;
Chris Lattner476e6df2001-12-03 17:28:42 +0000510 }
511
Chris Lattnere61b67d2004-04-02 20:24:31 +0000512 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000513 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner7e755e42003-12-23 07:47:09 +0000514
Chris Lattnere61b67d2004-04-02 20:24:31 +0000515 // Now that we know the largest of of the induction variables in this loop,
516 // insert a canonical induction variable of the largest size.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000517 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000518 ++NumInserted;
519 Changed = true;
Chris Lattner08165592007-01-07 01:14:12 +0000520 DOUT << "INDVARS: New CanIV: " << *IndVar;
Chris Lattner7e755e42003-12-23 07:47:09 +0000521
Chris Lattnere61b67d2004-04-02 20:24:31 +0000522 if (!isa<SCEVCouldNotCompute>(IterationCount))
Chris Lattner51c95cd2006-09-21 05:12:20 +0000523 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
524 DeadInsts.insert(DI);
Chris Lattner7e755e42003-12-23 07:47:09 +0000525
Chris Lattnere61b67d2004-04-02 20:24:31 +0000526 // Now that we have a canonical induction variable, we can rewrite any
527 // recurrences in terms of the induction variable. Start with the auxillary
528 // induction variables, and recursively rewrite any of their uses.
529 BasicBlock::iterator InsertPt = Header->begin();
530 while (isa<PHINode>(InsertPt)) ++InsertPt;
Chris Lattner476e6df2001-12-03 17:28:42 +0000531
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000532 // If there were induction variables of other sizes, cast the primary
533 // induction variable to the right size for them, avoiding the need for the
534 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000535 if (DifferingSizes) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000536 SmallVector<unsigned,4> InsertedSizes;
537 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
538 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
539 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5e52362007-01-12 22:51:20 +0000540 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
541 == InsertedSizes.end()) {
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000542 PHINode *PN = IndVars[i].first;
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000543 InsertedSizes.push_back(ithSize);
Chris Lattner08165592007-01-07 01:14:12 +0000544 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
545 InsertPt);
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000546 Rewriter.addInsertedValue(New, SE->getSCEV(New));
Chris Lattner08165592007-01-07 01:14:12 +0000547 DOUT << "INDVARS: Made trunc IV for " << *PN
548 << " NewVal = " << *New << "\n";
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000549 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000550 }
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000551 }
552
Chris Lattner08165592007-01-07 01:14:12 +0000553 // Rewrite all induction variables in terms of the canonical induction
554 // variable.
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000555 std::map<unsigned, Value*> InsertedSizes;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000556 while (!IndVars.empty()) {
557 PHINode *PN = IndVars.back().first;
Chris Lattner83cd87e2004-04-23 21:29:48 +0000558 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000559 PN->getType());
Chris Lattner08165592007-01-07 01:14:12 +0000560 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
561 << " into = " << *NewVal << "\n";
Chris Lattner6e0123b2007-02-11 01:23:03 +0000562 NewVal->takeName(PN);
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000563
Chris Lattnere61b67d2004-04-02 20:24:31 +0000564 // Replace the old PHI Node with the inserted computation.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000565 PN->replaceAllUsesWith(NewVal);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000566 DeadInsts.insert(PN);
567 IndVars.pop_back();
568 ++NumRemoved;
Chris Lattner67439402001-12-05 19:41:33 +0000569 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000570 }
571
Chris Lattnerc27302c2004-04-22 15:12:36 +0000572#if 0
Chris Lattneraf532f22004-04-21 23:36:08 +0000573 // Now replace all derived expressions in the loop body with simpler
574 // expressions.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000575 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
576 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
577 BasicBlock *BB = L->getBlocks()[i];
578 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner03c49532007-01-15 02:27:26 +0000579 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattneraf532f22004-04-21 23:36:08 +0000580 !I->use_empty() &&
Chris Lattnere61b67d2004-04-02 20:24:31 +0000581 !Rewriter.isInsertedInstruction(I)) {
582 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner83cd87e2004-04-23 21:29:48 +0000583 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattneraf532f22004-04-21 23:36:08 +0000584 if (V != I) {
Chris Lattner6e0123b2007-02-11 01:23:03 +0000585 if (isa<Instruction>(V))
586 V->takeName(I);
Chris Lattneraf532f22004-04-21 23:36:08 +0000587 I->replaceAllUsesWith(V);
588 DeadInsts.insert(I);
589 ++NumRemoved;
590 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000591 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000592 }
Chris Lattner91daaab2001-12-04 04:32:29 +0000593 }
Chris Lattnerc27302c2004-04-22 15:12:36 +0000594#endif
Chris Lattneraf532f22004-04-21 23:36:08 +0000595
Chris Lattneraf532f22004-04-21 23:36:08 +0000596 DeleteTriviallyDeadInstructions(DeadInsts);
Owen Anderson8e4b0292006-08-25 22:12:36 +0000597
598 if (mustPreserveAnalysisID(LCSSAID)) assert(L->isLCSSAForm());
Chris Lattner476e6df2001-12-03 17:28:42 +0000599}