blob: 13be455c4d0b590c0ca017865367536b775dc2ce [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//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Devang Patel2ac57e12007-03-07 06:39:01 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattner83d485b2002-02-12 22:39:50 +000049#include "llvm/Support/CFG.h"
Reid Spencer557ab152007-02-05 23:32:05 +000050#include "llvm/Support/Compiler.h"
Chris Lattner08165592007-01-07 01:14:12 +000051#include "llvm/Support/Debug.h"
Chris Lattner9776f722004-10-11 23:06:50 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswellb22e9b42003-12-18 17:19:19 +000053#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000054#include "llvm/Support/CommandLine.h"
Reid Spencer7a9c62b2007-01-12 07:05:14 +000055#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
John Criswellb22e9b42003-12-18 17:19:19 +000057using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner79a42ac2006-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 Lattnerd3678bc2003-12-22 03:58:44 +000064
Chris Lattner79a42ac2006-12-19 21:40:18 +000065namespace {
Devang Patel2ac57e12007-03-07 06:39:01 +000066 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Chris Lattnere61b67d2004-04-02 20:24:31 +000067 LoopInfo *LI;
68 ScalarEvolution *SE;
Chris Lattner7e755e42003-12-23 07:47:09 +000069 bool Changed;
Chris Lattnerd3678bc2003-12-22 03:58:44 +000070 public:
Devang Patel09f162c2007-05-01 21:15:47 +000071
Nick Lewyckye7da2d62007-05-06 13:37:16 +000072 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +000073 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +000074
Devang Patel2ac57e12007-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 {
Devang Pateld7409fd2007-09-10 18:08:23 +000078 AU.addRequired<ScalarEvolution>();
Devang Patel2ac57e12007-03-07 06:39:01 +000079 AU.addRequiredID(LCSSAID);
80 AU.addRequiredID(LoopSimplifyID);
Devang Patel2ac57e12007-03-07 06:39:01 +000081 AU.addRequired<LoopInfo>();
82 AU.addPreservedID(LoopSimplifyID);
83 AU.addPreservedID(LCSSAID);
84 AU.setPreservesCFG();
85 }
Chris Lattner7e755e42003-12-23 07:47:09 +000086
Chris Lattnere61b67d2004-04-02 20:24:31 +000087 private:
Devang Patel2ac57e12007-03-07 06:39:01 +000088
Chris Lattnere61b67d2004-04-02 20:24:31 +000089 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);
Dan Gohman1fcc8042008-08-05 22:34:21 +000093 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Chris Lattnere61b67d2004-04-02 20:24:31 +000094
95 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
Devang Patel92b032f2008-09-09 21:41:07 +000096
97 void OptimizeCanonicalIVType(Loop *L);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000098 };
Chris Lattner4184bcc2002-09-10 05:24:05 +000099}
Chris Lattner91daaab2001-12-04 04:32:29 +0000100
Dan Gohmand78c4002008-05-13 00:00:25 +0000101char IndVarSimplify::ID = 0;
102static RegisterPass<IndVarSimplify>
103X("indvars", "Canonicalize Induction Variables");
104
Devang Patel2ac57e12007-03-07 06:39:01 +0000105LoopPass *llvm::createIndVarSimplifyPass() {
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000106 return new IndVarSimplify();
Chris Lattner91daaab2001-12-04 04:32:29 +0000107}
108
Chris Lattnere61b67d2004-04-02 20:24:31 +0000109/// DeleteTriviallyDeadInstructions - If any of the instructions is the
110/// specified set are trivially dead, delete them and see if this makes any of
111/// their operands subsequently dead.
112void IndVarSimplify::
113DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
114 while (!Insts.empty()) {
115 Instruction *I = *Insts.begin();
116 Insts.erase(Insts.begin());
117 if (isInstructionTriviallyDead(I)) {
118 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
119 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
120 Insts.insert(U);
Dan Gohman32f53bb2007-06-19 14:28:31 +0000121 SE->deleteValueFromRecords(I);
Chris Lattner08165592007-01-07 01:14:12 +0000122 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattner9776f722004-10-11 23:06:50 +0000123 I->eraseFromParent();
Chris Lattnere61b67d2004-04-02 20:24:31 +0000124 Changed = true;
125 }
126 }
127}
128
129
130/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
131/// recurrence. If so, change it into an integer recurrence, permitting
132/// analysis by the SCEV routines.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000133void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattnere61b67d2004-04-02 20:24:31 +0000134 BasicBlock *Preheader,
135 std::set<Instruction*> &DeadInsts) {
136 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
137 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
138 unsigned BackedgeIdx = PreheaderIdx^1;
139 if (GetElementPtrInst *GEPI =
Chris Lattner677d8572005-08-10 01:12:06 +0000140 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattnere61b67d2004-04-02 20:24:31 +0000141 if (GEPI->getOperand(0) == PN) {
Chris Lattner677d8572005-08-10 01:12:06 +0000142 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattner08165592007-01-07 01:14:12 +0000143 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
144
Chris Lattnere61b67d2004-04-02 20:24:31 +0000145 // Okay, we found a pointer recurrence. Transform this pointer
146 // recurrence into an integer recurrence. Compute the value that gets
147 // added to the pointer at every iteration.
148 Value *AddedVal = GEPI->getOperand(1);
149
150 // Insert a new integer PHI node into the top of the block.
Gabor Greife9ecc682008-04-06 20:25:17 +0000151 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
152 PN->getName()+".rec", PN);
Chris Lattnerc9e06332004-06-20 05:04:01 +0000153 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
154
Chris Lattnere61b67d2004-04-02 20:24:31 +0000155 // Create the new add instruction.
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000156 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Chris Lattnerc9e06332004-06-20 05:04:01 +0000157 GEPI->getName()+".rec", GEPI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000158 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000159
Chris Lattnere61b67d2004-04-02 20:24:31 +0000160 // Update the existing GEP to use the recurrence.
161 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162
Chris Lattnere61b67d2004-04-02 20:24:31 +0000163 // Update the GEP to use the new recurrence we just inserted.
164 GEPI->setOperand(1, NewAdd);
165
Chris Lattner9776f722004-10-11 23:06:50 +0000166 // If the incoming value is a constant expr GEP, try peeling out the array
167 // 0 index if possible to make things simpler.
168 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
169 if (CE->getOpcode() == Instruction::GetElementPtr) {
170 unsigned NumOps = CE->getNumOperands();
171 assert(NumOps > 1 && "CE folding didn't work!");
172 if (CE->getOperand(NumOps-1)->isNullValue()) {
173 // Check to make sure the last index really is an array index.
Chris Lattner9c37f232005-11-18 18:30:47 +0000174 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerbca0be82005-11-17 19:35:42 +0000175 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattner9776f722004-10-11 23:06:50 +0000176 i != e; ++i, ++GTI)
177 /*empty*/;
178 if (isa<SequentialType>(*GTI)) {
179 // Pull the last index out of the constant expr GEP.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000180 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattner9776f722004-10-11 23:06:50 +0000181 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000182 &CEIdxs[0],
183 CEIdxs.size());
David Greenec656cbb2007-09-04 15:46:09 +0000184 Value *Idx[2];
185 Idx[0] = Constant::getNullValue(Type::Int32Ty);
186 Idx[1] = NewAdd;
Gabor Greife9ecc682008-04-06 20:25:17 +0000187 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
David Greenec656cbb2007-09-04 15:46:09 +0000188 NCE, Idx, Idx + 2,
Reid Spencer2e54a152007-03-02 00:28:52 +0000189 GEPI->getName(), GEPI);
Dan Gohman32f53bb2007-06-19 14:28:31 +0000190 SE->deleteValueFromRecords(GEPI);
Chris Lattner9776f722004-10-11 23:06:50 +0000191 GEPI->replaceAllUsesWith(NGEPI);
192 GEPI->eraseFromParent();
193 GEPI = NGEPI;
194 }
195 }
196 }
197
198
Chris Lattnere61b67d2004-04-02 20:24:31 +0000199 // Finally, if there are any other users of the PHI node, we must
200 // insert a new GEP instruction that uses the pre-incremented version
201 // of the induction amount.
202 if (!PN->use_empty()) {
203 BasicBlock::iterator InsertPos = PN; ++InsertPos;
204 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000205 Value *PreInc =
Gabor Greife9ecc682008-04-06 20:25:17 +0000206 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
207 NewPhi, "", InsertPos);
Chris Lattner6e0123b2007-02-11 01:23:03 +0000208 PreInc->takeName(PN);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000209 PN->replaceAllUsesWith(PreInc);
210 }
211
212 // Delete the old PHI for sure, and the GEP if its otherwise unused.
213 DeadInsts.insert(PN);
214
215 ++NumPointer;
216 Changed = true;
217 }
218}
219
220/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000221/// loop to be a canonical != comparison against the incremented loop induction
222/// variable. This pass is able to rewrite the exit tests of any loop where the
223/// SCEV analysis can determine a loop-invariant trip count of the loop, which
224/// is actually a much broader range than just linear tests.
Chris Lattner51c95cd2006-09-21 05:12:20 +0000225///
226/// This method returns a "potentially dead" instruction whose computation chain
227/// should be deleted when convenient.
228Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
229 SCEV *IterationCount,
230 SCEVExpander &RW) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000231 // Find the exit block for the loop. We can currently only handle loops with
232 // a single exit.
Devang Patelb5933bb2007-08-21 00:31:24 +0000233 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000234 L->getExitBlocks(ExitBlocks);
Chris Lattner51c95cd2006-09-21 05:12:20 +0000235 if (ExitBlocks.size() != 1) return 0;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000236 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattnere61b67d2004-04-02 20:24:31 +0000237
238 // Make sure there is only one predecessor block in the loop.
239 BasicBlock *ExitingBlock = 0;
240 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
241 PI != PE; ++PI)
242 if (L->contains(*PI)) {
243 if (ExitingBlock == 0)
244 ExitingBlock = *PI;
245 else
Chris Lattner51c95cd2006-09-21 05:12:20 +0000246 return 0; // Multiple exits from loop to this block.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000247 }
248 assert(ExitingBlock && "Loop info is broken");
249
250 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
Chris Lattner51c95cd2006-09-21 05:12:20 +0000251 return 0; // Can't rewrite non-branch yet
Chris Lattnere61b67d2004-04-02 20:24:31 +0000252 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
253 assert(BI->isConditional() && "Must be conditional to be part of loop!");
254
Chris Lattner51c95cd2006-09-21 05:12:20 +0000255 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
256
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000257 // If the exiting block is not the same as the backedge block, we must compare
258 // against the preincremented value, otherwise we prefer to compare against
259 // the post-incremented value.
260 BasicBlock *Header = L->getHeader();
261 pred_iterator HPI = pred_begin(Header);
262 assert(HPI != pred_end(Header) && "Loop with zero preds???");
263 if (!L->contains(*HPI)) ++HPI;
264 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
265 "No backedge in loop?");
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000266
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000267 SCEVHandle TripCount = IterationCount;
268 Value *IndVar;
269 if (*HPI == ExitingBlock) {
270 // The IterationCount expression contains the number of times that the
271 // backedge actually branches to the loop header. This is one less than the
272 // number of times the loop executes, so add one to it.
Dan Gohman203a0352007-06-15 18:00:55 +0000273 ConstantInt *OneC = ConstantInt::get(IterationCount->getType(), 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +0000274 TripCount = SE->getAddExpr(IterationCount, SE->getConstant(OneC));
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000275 IndVar = L->getCanonicalInductionVariableIncrement();
276 } else {
277 // We have to use the preincremented value...
278 IndVar = L->getCanonicalInductionVariable();
279 }
Chris Lattner08165592007-01-07 01:14:12 +0000280
281 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
282 << " IndVar = " << *IndVar << "\n";
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000283
Chris Lattnere61b67d2004-04-02 20:24:31 +0000284 // Expand the code for the iteration count into the preheader of the loop.
285 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000286 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator());
Chris Lattnere61b67d2004-04-02 20:24:31 +0000287
Reid Spencer266e42b2006-12-23 06:05:41 +0000288 // Insert a new icmp_ne or icmp_eq instruction before the branch.
289 ICmpInst::Predicate Opcode;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000290 if (L->contains(BI->getSuccessor(0)))
Reid Spencer266e42b2006-12-23 06:05:41 +0000291 Opcode = ICmpInst::ICMP_NE;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000292 else
Reid Spencer266e42b2006-12-23 06:05:41 +0000293 Opcode = ICmpInst::ICMP_EQ;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000294
Reid Spencer266e42b2006-12-23 06:05:41 +0000295 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000296 BI->setCondition(Cond);
297 ++NumLFTR;
298 Changed = true;
Chris Lattner51c95cd2006-09-21 05:12:20 +0000299 return PotentiallyDeadInst;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000300}
301
302
303/// RewriteLoopExitValues - Check to see if this loop has a computable
304/// loop-invariant execution count. If so, this means that we can compute the
305/// final value of any expressions that are recurrent in the loop, and
306/// substitute the exit values from the loop into any instructions outside of
307/// the loop that use the final values of the current expressions.
Dan Gohman1fcc8042008-08-05 22:34:21 +0000308void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000309 BasicBlock *Preheader = L->getLoopPreheader();
310
311 // Scan all of the instructions in the loop, looking at those that have
312 // extra-loop users and which are recurrences.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000313 SCEVExpander Rewriter(*SE, *LI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000314
315 // We insert the code into the preheader of the loop if the loop contains
316 // multiple exit blocks, or in the exit block if there is exactly one.
317 BasicBlock *BlockToInsertInto;
Devang Patelb5933bb2007-08-21 00:31:24 +0000318 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000319 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000320 if (ExitBlocks.size() == 1)
321 BlockToInsertInto = ExitBlocks[0];
Chris Lattnere61b67d2004-04-02 20:24:31 +0000322 else
323 BlockToInsertInto = Preheader;
Dan Gohmanf96e1372008-05-23 21:05:58 +0000324 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattnere61b67d2004-04-02 20:24:31 +0000325
Dan Gohman1fcc8042008-08-05 22:34:21 +0000326 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Chris Lattnera8140802004-04-17 18:44:09 +0000327
Chris Lattnere61b67d2004-04-02 20:24:31 +0000328 std::set<Instruction*> InstructionsToDelete;
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000329 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000330
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000331 // Find all values that are computed inside the loop, but used outside of it.
332 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
333 // the exit blocks of the loop to find them.
334 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
335 BasicBlock *ExitBB = ExitBlocks[i];
336
337 // If there are no PHI nodes in this exit block, then no values defined
338 // inside the loop are used on this path, skip it.
339 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
340 if (!PN) continue;
341
342 unsigned NumPreds = PN->getNumIncomingValues();
343
344 // Iterate over all of the PHI nodes.
345 BasicBlock::iterator BBI = ExitBB->begin();
346 while ((PN = dyn_cast<PHINode>(BBI++))) {
Chris Lattnered30abf2007-03-03 22:48:48 +0000347
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000348 // Iterate over all of the values in all the PHI nodes.
349 for (unsigned i = 0; i != NumPreds; ++i) {
350 // If the value being merged in is not integer or is not defined
351 // in the loop, skip it.
352 Value *InVal = PN->getIncomingValue(i);
353 if (!isa<Instruction>(InVal) ||
354 // SCEV only supports integer expressions for now.
355 !isa<IntegerType>(InVal->getType()))
356 continue;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000357
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000358 // If this pred is for a subloop, not L itself, skip it.
359 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
360 continue; // The Block is in a subloop, skip it.
361
362 // Check that InVal is defined in the loop.
363 Instruction *Inst = cast<Instruction>(InVal);
364 if (!L->contains(Inst->getParent()))
365 continue;
Chris Lattner1f7648e2007-03-04 01:00:28 +0000366
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000367 // We require that this value either have a computable evolution or that
368 // the loop have a constant iteration count. In the case where the loop
369 // has a constant iteration count, we can sometimes force evaluation of
370 // the exit value through brute force.
371 SCEVHandle SH = SE->getSCEV(Inst);
372 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
373 continue; // Cannot get exit evolution for the loop value.
374
375 // Okay, this instruction has a user outside of the current loop
376 // and varies predictably *inside* the loop. Evaluate the value it
377 // contains when the loop exits, if possible.
378 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
379 if (isa<SCEVCouldNotCompute>(ExitValue) ||
380 !ExitValue->isLoopInvariant(L))
381 continue;
Chris Lattner1f7648e2007-03-04 01:00:28 +0000382
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000383 Changed = true;
384 ++NumReplaced;
385
386 // See if we already computed the exit value for the instruction, if so,
387 // just reuse it.
388 Value *&ExitVal = ExitValues[Inst];
389 if (!ExitVal)
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000390 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000391
392 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
393 << " LoopVal = " << *Inst << "\n";
394
395 PN->setIncomingValue(i, ExitVal);
396
397 // If this instruction is dead now, schedule it to be removed.
398 if (Inst->use_empty())
399 InstructionsToDelete.insert(Inst);
400
401 // See if this is a single-entry LCSSA PHI node. If so, we can (and
402 // have to) remove
Chris Lattner1f7648e2007-03-04 01:00:28 +0000403 // the PHI entirely. This is safe, because the NewVal won't be variant
404 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000405 if (NumPreds == 1) {
Dan Gohman32f53bb2007-06-19 14:28:31 +0000406 SE->deleteValueFromRecords(PN);
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000407 PN->replaceAllUsesWith(ExitVal);
408 PN->eraseFromParent();
409 break;
Chris Lattnered30abf2007-03-03 22:48:48 +0000410 }
411 }
Chris Lattnered30abf2007-03-03 22:48:48 +0000412 }
413 }
414
Chris Lattnere61b67d2004-04-02 20:24:31 +0000415 DeleteTriviallyDeadInstructions(InstructionsToDelete);
416}
417
Devang Patel2ac57e12007-03-07 06:39:01 +0000418bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000419
Devang Patel2ac57e12007-03-07 06:39:01 +0000420 Changed = false;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000421 // First step. Check to see if there are any trivial GEP pointer recurrences.
422 // If there are, change them into integer recurrences, permitting analysis by
423 // the SCEV routines.
424 //
425 BasicBlock *Header = L->getHeader();
426 BasicBlock *Preheader = L->getLoopPreheader();
Devang Patel2ac57e12007-03-07 06:39:01 +0000427 SE = &LPM.getAnalysis<ScalarEvolution>();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000428
Chris Lattnere61b67d2004-04-02 20:24:31 +0000429 std::set<Instruction*> DeadInsts;
Reid Spencer66149462004-09-15 17:06:42 +0000430 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
431 PHINode *PN = cast<PHINode>(I);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000432 if (isa<PointerType>(PN->getType()))
433 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Reid Spencer66149462004-09-15 17:06:42 +0000434 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000435
436 if (!DeadInsts.empty())
437 DeleteTriviallyDeadInstructions(DeadInsts);
438
Devang Patel2ac57e12007-03-07 06:39:01 +0000439 return Changed;
440}
Chris Lattnere61b67d2004-04-02 20:24:31 +0000441
Devang Patel2ac57e12007-03-07 06:39:01 +0000442bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000443
Devang Patel2ac57e12007-03-07 06:39:01 +0000444
445 LI = &getAnalysis<LoopInfo>();
446 SE = &getAnalysis<ScalarEvolution>();
447
448 Changed = false;
449 BasicBlock *Header = L->getHeader();
450 std::set<Instruction*> DeadInsts;
451
Chris Lattner1f7648e2007-03-04 01:00:28 +0000452 // Verify the input to the pass in already in LCSSA form.
453 assert(L->isLCSSAForm());
454
Chris Lattnere61b67d2004-04-02 20:24:31 +0000455 // Check to see if this loop has a computable loop-invariant execution count.
456 // If so, this means that we can compute the final value of any expressions
457 // that are recurrent in the loop, and substitute the exit values from the
458 // loop into any instructions outside of the loop that use the final values of
459 // the current expressions.
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000460 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000461 SCEVHandle IterationCount = SE->getIterationCount(L);
462 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohman1fcc8042008-08-05 22:34:21 +0000463 RewriteLoopExitValues(L, IterationCount);
Chris Lattner476e6df2001-12-03 17:28:42 +0000464
Chris Lattnere61b67d2004-04-02 20:24:31 +0000465 // Next, analyze all of the induction variables in the loop, canonicalizing
466 // auxillary induction variables.
467 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
468
Reid Spencer66149462004-09-15 17:06:42 +0000469 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
470 PHINode *PN = cast<PHINode>(I);
Chris Lattner03c49532007-01-15 02:27:26 +0000471 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattnere61b67d2004-04-02 20:24:31 +0000472 SCEVHandle SCEV = SE->getSCEV(PN);
473 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattner677d8572005-08-10 01:12:06 +0000474 // FIXME: It is an extremely bad idea to indvar substitute anything more
475 // complex than affine induction variables. Doing so will put expensive
476 // polynomial evaluations inside of the loop, and the str reduction pass
477 // currently can only reduce affine polynomials. For now just disable
478 // indvar subst on anything more complex than an affine addrec.
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000479 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattner677d8572005-08-10 01:12:06 +0000480 if (AR->isAffine())
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000481 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattnere61b67d2004-04-02 20:24:31 +0000482 }
Reid Spencer66149462004-09-15 17:06:42 +0000483 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000484
485 // If there are no induction variables in the loop, there is nothing more to
486 // do.
Chris Lattner885a6eb2004-04-17 18:08:33 +0000487 if (IndVars.empty()) {
488 // Actually, if we know how many times the loop iterates, lets insert a
489 // canonical induction variable to help subsequent passes.
490 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner83cd87e2004-04-23 21:29:48 +0000491 SCEVExpander Rewriter(*SE, *LI);
492 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattner885a6eb2004-04-17 18:08:33 +0000493 IterationCount->getType());
Chris Lattner51c95cd2006-09-21 05:12:20 +0000494 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
495 Rewriter)) {
496 std::set<Instruction*> InstructionsToDelete;
497 InstructionsToDelete.insert(I);
498 DeleteTriviallyDeadInstructions(InstructionsToDelete);
499 }
Chris Lattner885a6eb2004-04-17 18:08:33 +0000500 }
Devang Patel2ac57e12007-03-07 06:39:01 +0000501 return Changed;
Chris Lattner885a6eb2004-04-17 18:08:33 +0000502 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000503
504 // Compute the type of the largest recurrence expression.
Chris Lattner476e6df2001-12-03 17:28:42 +0000505 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000506 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000507 bool DifferingSizes = false;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000508 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
509 const Type *Ty = IndVars[i].first->getType();
Reid Spencer8f166b02007-01-08 16:32:00 +0000510 DifferingSizes |=
511 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
512 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
Chris Lattnere61b67d2004-04-02 20:24:31 +0000513 LargestType = Ty;
Chris Lattner476e6df2001-12-03 17:28:42 +0000514 }
515
Chris Lattnere61b67d2004-04-02 20:24:31 +0000516 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000517 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner7e755e42003-12-23 07:47:09 +0000518
Chris Lattnere61b67d2004-04-02 20:24:31 +0000519 // Now that we know the largest of of the induction variables in this loop,
520 // insert a canonical induction variable of the largest size.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000521 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000522 ++NumInserted;
523 Changed = true;
Chris Lattner08165592007-01-07 01:14:12 +0000524 DOUT << "INDVARS: New CanIV: " << *IndVar;
Chris Lattner7e755e42003-12-23 07:47:09 +0000525
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000526 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Wojciech Matyjewicz25a7f5d2008-06-13 17:02:03 +0000527 IterationCount = SE->getTruncateOrZeroExtend(IterationCount, LargestType);
Chris Lattner51c95cd2006-09-21 05:12:20 +0000528 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
529 DeadInsts.insert(DI);
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000530 }
Chris Lattner7e755e42003-12-23 07:47:09 +0000531
Chris Lattnere61b67d2004-04-02 20:24:31 +0000532 // Now that we have a canonical induction variable, we can rewrite any
533 // recurrences in terms of the induction variable. Start with the auxillary
534 // induction variables, and recursively rewrite any of their uses.
Dan Gohmanf96e1372008-05-23 21:05:58 +0000535 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner476e6df2001-12-03 17:28:42 +0000536
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000537 // If there were induction variables of other sizes, cast the primary
538 // induction variable to the right size for them, avoiding the need for the
539 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000540 if (DifferingSizes) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000541 SmallVector<unsigned,4> InsertedSizes;
542 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
543 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
544 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5e52362007-01-12 22:51:20 +0000545 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
546 == InsertedSizes.end()) {
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000547 PHINode *PN = IndVars[i].first;
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000548 InsertedSizes.push_back(ithSize);
Chris Lattner08165592007-01-07 01:14:12 +0000549 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
550 InsertPt);
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000551 Rewriter.addInsertedValue(New, SE->getSCEV(New));
Chris Lattner08165592007-01-07 01:14:12 +0000552 DOUT << "INDVARS: Made trunc IV for " << *PN
553 << " NewVal = " << *New << "\n";
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000554 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000555 }
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000556 }
557
Chris Lattner08165592007-01-07 01:14:12 +0000558 // Rewrite all induction variables in terms of the canonical induction
559 // variable.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000560 while (!IndVars.empty()) {
561 PHINode *PN = IndVars.back().first;
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000562 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
Chris Lattner08165592007-01-07 01:14:12 +0000563 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
564 << " into = " << *NewVal << "\n";
Chris Lattner6e0123b2007-02-11 01:23:03 +0000565 NewVal->takeName(PN);
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000566
Chris Lattnere61b67d2004-04-02 20:24:31 +0000567 // Replace the old PHI Node with the inserted computation.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000568 PN->replaceAllUsesWith(NewVal);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000569 DeadInsts.insert(PN);
570 IndVars.pop_back();
571 ++NumRemoved;
Chris Lattner67439402001-12-05 19:41:33 +0000572 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000573 }
574
Chris Lattnerc27302c2004-04-22 15:12:36 +0000575#if 0
Chris Lattneraf532f22004-04-21 23:36:08 +0000576 // Now replace all derived expressions in the loop body with simpler
577 // expressions.
Dan Gohman90071072008-06-22 20:18:58 +0000578 for (LoopInfo::block_iterator I = L->block_begin(), E = L->block_end();
579 I != E; ++I) {
580 BasicBlock *BB = *I;
581 if (LI->getLoopFor(BB) == L) { // Not in a subloop...
Chris Lattnere61b67d2004-04-02 20:24:31 +0000582 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner03c49532007-01-15 02:27:26 +0000583 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattneraf532f22004-04-21 23:36:08 +0000584 !I->use_empty() &&
Chris Lattnere61b67d2004-04-02 20:24:31 +0000585 !Rewriter.isInsertedInstruction(I)) {
586 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner83cd87e2004-04-23 21:29:48 +0000587 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattneraf532f22004-04-21 23:36:08 +0000588 if (V != I) {
Chris Lattner6e0123b2007-02-11 01:23:03 +0000589 if (isa<Instruction>(V))
590 V->takeName(I);
Chris Lattneraf532f22004-04-21 23:36:08 +0000591 I->replaceAllUsesWith(V);
592 DeadInsts.insert(I);
593 ++NumRemoved;
594 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000595 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000596 }
Chris Lattner91daaab2001-12-04 04:32:29 +0000597 }
Dan Gohman90071072008-06-22 20:18:58 +0000598 }
Chris Lattnerc27302c2004-04-22 15:12:36 +0000599#endif
Chris Lattneraf532f22004-04-21 23:36:08 +0000600
Chris Lattneraf532f22004-04-21 23:36:08 +0000601 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Patel92b032f2008-09-09 21:41:07 +0000602 OptimizeCanonicalIVType(L);
Chris Lattner1f7648e2007-03-04 01:00:28 +0000603 assert(L->isLCSSAForm());
Devang Patel2ac57e12007-03-07 06:39:01 +0000604 return Changed;
Chris Lattner476e6df2001-12-03 17:28:42 +0000605}
Devang Patel92b032f2008-09-09 21:41:07 +0000606
607/// OptimizeCanonicalIVType - If loop induction variable is always
Devang Patel728c44a2008-09-10 14:49:55 +0000608/// sign or zero extended then extend the type of the induction
Devang Patel92b032f2008-09-09 21:41:07 +0000609/// variable.
610void IndVarSimplify::OptimizeCanonicalIVType(Loop *L) {
611 PHINode *PH = L->getCanonicalInductionVariable();
612 if (!PH) return;
613
614 // Check loop iteration count.
615 SCEVHandle IC = SE->getIterationCount(L);
616 if (isa<SCEVCouldNotCompute>(IC)) return;
617 SCEVConstant *IterationCount = dyn_cast<SCEVConstant>(IC);
618 if (!IterationCount) return;
619
620 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
621 unsigned BackEdge = IncomingEdge^1;
622
623 // Check IV uses. If all IV uses are either SEXT or ZEXT (except
624 // IV increment instruction) then this IV is suitable for this
Devang Patel728c44a2008-09-10 14:49:55 +0000625 // transformation.
626 bool isSEXT = false;
Devang Patel92b032f2008-09-09 21:41:07 +0000627 BinaryOperator *Incr = NULL;
Devang Patel728c44a2008-09-10 14:49:55 +0000628 const Type *NewType = NULL;
Devang Patel92b032f2008-09-09 21:41:07 +0000629 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
630 UI != UE; ++UI) {
631 const Type *CandidateType = NULL;
632 if (ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
633 CandidateType = ZI->getDestTy();
634 else if (SExtInst *SI = dyn_cast<SExtInst>(UI)) {
635 CandidateType = SI->getDestTy();
Devang Patel728c44a2008-09-10 14:49:55 +0000636 isSEXT = true;
Devang Patel92b032f2008-09-09 21:41:07 +0000637 }
638 else if ((Incr = dyn_cast<BinaryOperator>(UI))) {
639 // Validate IV increment instruction.
640 if (PH->getIncomingValue(BackEdge) == Incr)
641 continue;
642 }
643 if (!CandidateType) {
644 NewType = NULL;
645 break;
646 }
647 if (!NewType)
648 NewType = CandidateType;
649 else if (NewType != CandidateType) {
650 NewType = NULL;
651 break;
652 }
653 }
654
655 // IV uses are not suitable then avoid this transformation.
656 if (!NewType || !Incr)
657 return;
658
659 // IV increment instruction has two uses, one is loop exit condition
660 // and second is the IV (phi node) itself.
661 ICmpInst *Exit = NULL;
662 for(Value::use_iterator II = Incr->use_begin(), IE = Incr->use_end();
663 II != IE; ++II) {
664 if (PH == *II) continue;
665 Exit = dyn_cast<ICmpInst>(*II);
666 break;
667 }
668 if (!Exit) return;
669 ConstantInt *EV = dyn_cast<ConstantInt>(Exit->getOperand(0));
670 if (!EV)
671 EV = dyn_cast<ConstantInt>(Exit->getOperand(1));
672 if (!EV) return;
673
674 // Check iteration count max value to avoid loops that wrap around IV.
675 APInt ICount = IterationCount->getValue()->getValue();
676 if (ICount.isNegative()) return;
677 uint32_t BW = PH->getType()->getPrimitiveSizeInBits();
678 APInt Max = (isSEXT ? APInt::getSignedMaxValue(BW) : APInt::getMaxValue(BW));
679 if (ICount.getZExtValue() > Max.getZExtValue()) return;
680
681 // Extend IV type.
682
683 SCEVExpander Rewriter(*SE, *LI);
684 Value *NewIV = Rewriter.getOrInsertCanonicalInductionVariable(L,NewType);
685 PHINode *NewPH = cast<PHINode>(NewIV);
686 Instruction *NewIncr = cast<Instruction>(NewPH->getIncomingValue(BackEdge));
687
688 // Replace all SEXT or ZEXT uses.
689 SmallVector<Instruction *, 4> PHUses;
690 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
691 UI != UE; ++UI) {
692 Instruction *I = cast<Instruction>(UI);
693 PHUses.push_back(I);
694 }
695 while (!PHUses.empty()){
696 Instruction *Use = PHUses.back(); PHUses.pop_back();
697 if (Incr == Use) continue;
698
699 SE->deleteValueFromRecords(Use);
700 Use->replaceAllUsesWith(NewIV);
701 Use->eraseFromParent();
702 }
703
704 // Replace exit condition.
705 ConstantInt *NEV = ConstantInt::get(NewType, EV->getZExtValue());
706 Instruction *NE = new ICmpInst(Exit->getPredicate(),
707 NewIncr, NEV, "new.exit",
708 Exit->getParent()->getTerminator());
709 SE->deleteValueFromRecords(Exit);
710 Exit->replaceAllUsesWith(NE);
711 Exit->eraseFromParent();
712
713 // Remove old IV and increment instructions.
714 SE->deleteValueFromRecords(PH);
715 PH->removeIncomingValue((unsigned)0);
716 PH->removeIncomingValue((unsigned)0);
717 SE->deleteValueFromRecords(Incr);
718 Incr->eraseFromParent();
719}
720