blob: d5809784ca0480f96751a55cd1e942fdf9afa2a3 [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into simpler forms suitable for subsequent
12// analysis and transformation.
13//
Reid Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-04-02 20:24:31 +000015// identifiable induction variable:
16// 1. All loops are transformed to have a SINGLE canonical induction variable
17// which starts at zero and steps by one.
18// 2. The canonical induction variable is guaranteed to be the first PHI node
19// in the loop header block.
20// 3. Any pointer arithmetic recurrences are raised to use array subscripts.
21//
22// If the trip count of a loop is computable, this pass also makes the following
23// changes:
24// 1. The exit condition for the loop is canonicalized to compare the
25// induction value against the exit value. This turns loops like:
26// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
27// 2. Any use outside of the loop of an expression derived from the indvar
28// is changed to compute the derived value outside of the loop, eliminating
29// the dependence on the exit value of the induction variable. If the only
30// purpose of the loop is to compute the exit value of some derived
31// expression, this transformation will make the loop dead.
32//
33// This transformation should be followed by strength reduction after all of the
34// desired loop transformations have been performed. Additionally, on targets
35// where it is profitable, the loop could be transformed to count down to zero
36// (the "do loop" optimization).
Chris Lattner6148c022001-12-03 17:28:42 +000037//
38//===----------------------------------------------------------------------===//
39
Chris Lattner0e5f4992006-12-19 21:40:18 +000040#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000041#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000042#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000043#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000044#include "llvm/Instructions.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000045#include "llvm/Type.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000047#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000049#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000050#include "llvm/Support/Compiler.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000051#include "llvm/Support/Debug.h"
Chris Lattnera4b9c782004-10-11 23:06:50 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswell47df12d2003-12-18 17:19:19 +000053#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000054#include "llvm/Support/CommandLine.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1a6111f2008-11-16 07:17:51 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000058using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000059
Chris Lattner0e5f4992006-12-19 21:40:18 +000060STATISTIC(NumRemoved , "Number of aux indvars removed");
61STATISTIC(NumPointer , "Number of pointer indvars promoted");
62STATISTIC(NumInserted, "Number of canonical indvars added");
63STATISTIC(NumReplaced, "Number of exit values replaced");
64STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000067 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Chris Lattner40bf8b42004-04-02 20:24:31 +000068 LoopInfo *LI;
69 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000070 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000071 public:
Devang Patel794fd752007-05-01 21:15:47 +000072
Nick Lewyckyecd94c82007-05-06 13:37:16 +000073 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000074 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000075
Devang Patel5ee99972007-03-07 06:39:01 +000076 bool runOnLoop(Loop *L, LPPassManager &LPM);
77 bool doInitialization(Loop *L, LPPassManager &LPM);
78 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelbc533cd2007-09-10 18:08:23 +000079 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000080 AU.addRequiredID(LCSSAID);
81 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000082 AU.addRequired<LoopInfo>();
83 AU.addPreservedID(LoopSimplifyID);
84 AU.addPreservedID(LCSSAID);
85 AU.setPreservesCFG();
86 }
Chris Lattner15cad752003-12-23 07:47:09 +000087
Chris Lattner40bf8b42004-04-02 20:24:31 +000088 private:
Devang Patel5ee99972007-03-07 06:39:01 +000089
Chris Lattner40bf8b42004-04-02 20:24:31 +000090 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +000091 SmallPtrSet<Instruction*, 16> &DeadInsts);
Chris Lattner9ba46c12006-09-21 05:12:20 +000092 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
93 SCEVExpander &RW);
Dan Gohman5a6c4482008-08-05 22:34:21 +000094 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +000095
Chris Lattner1a6111f2008-11-16 07:17:51 +000096 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Pateld22a8492008-09-09 21:41:07 +000097
98 void OptimizeCanonicalIVType(Loop *L);
Devang Patel84e35152008-11-17 21:32:02 +000099 void HandleFloatingPointIV(Loop *L, PHINode *PH,
100 SmallPtrSet<Instruction*, 16> &DeadInsts);
Chris Lattner3324e712003-12-22 03:58:44 +0000101 };
Chris Lattner5e761402002-09-10 05:24:05 +0000102}
Chris Lattner394437f2001-12-04 04:32:29 +0000103
Dan Gohman844731a2008-05-13 00:00:25 +0000104char IndVarSimplify::ID = 0;
105static RegisterPass<IndVarSimplify>
106X("indvars", "Canonicalize Induction Variables");
107
Daniel Dunbar394f0442008-10-22 23:32:42 +0000108Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000109 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000110}
111
Chris Lattner40bf8b42004-04-02 20:24:31 +0000112/// DeleteTriviallyDeadInstructions - If any of the instructions is the
113/// specified set are trivially dead, delete them and see if this makes any of
114/// their operands subsequently dead.
115void IndVarSimplify::
Chris Lattner1a6111f2008-11-16 07:17:51 +0000116DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000117 while (!Insts.empty()) {
118 Instruction *I = *Insts.begin();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000119 Insts.erase(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000120 if (isInstructionTriviallyDead(I)) {
121 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
122 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
123 Insts.insert(U);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000124 SE->deleteValueFromRecords(I);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000125 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000126 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000127 Changed = true;
128 }
129 }
130}
131
132
133/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
134/// recurrence. If so, change it into an integer recurrence, permitting
135/// analysis by the SCEV routines.
Misha Brukmanfd939082005-04-21 23:48:37 +0000136void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattner40bf8b42004-04-02 20:24:31 +0000137 BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +0000138 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000139 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
140 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
141 unsigned BackedgeIdx = PreheaderIdx^1;
142 if (GetElementPtrInst *GEPI =
Chris Lattnercda9ca52005-08-10 01:12:06 +0000143 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattner40bf8b42004-04-02 20:24:31 +0000144 if (GEPI->getOperand(0) == PN) {
Chris Lattnercda9ca52005-08-10 01:12:06 +0000145 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattneree4f13a2007-01-07 01:14:12 +0000146 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
147
Chris Lattner40bf8b42004-04-02 20:24:31 +0000148 // Okay, we found a pointer recurrence. Transform this pointer
149 // recurrence into an integer recurrence. Compute the value that gets
150 // added to the pointer at every iteration.
151 Value *AddedVal = GEPI->getOperand(1);
152
153 // Insert a new integer PHI node into the top of the block.
Gabor Greif051a9502008-04-06 20:25:17 +0000154 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
155 PN->getName()+".rec", PN);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000156 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
157
Chris Lattner40bf8b42004-04-02 20:24:31 +0000158 // Create the new add instruction.
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000159 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000160 GEPI->getName()+".rec", GEPI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000161 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000162
Chris Lattner40bf8b42004-04-02 20:24:31 +0000163 // Update the existing GEP to use the recurrence.
164 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000165
Chris Lattner40bf8b42004-04-02 20:24:31 +0000166 // Update the GEP to use the new recurrence we just inserted.
167 GEPI->setOperand(1, NewAdd);
168
Chris Lattnera4b9c782004-10-11 23:06:50 +0000169 // If the incoming value is a constant expr GEP, try peeling out the array
170 // 0 index if possible to make things simpler.
171 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
172 if (CE->getOpcode() == Instruction::GetElementPtr) {
173 unsigned NumOps = CE->getNumOperands();
174 assert(NumOps > 1 && "CE folding didn't work!");
175 if (CE->getOperand(NumOps-1)->isNullValue()) {
176 // Check to make sure the last index really is an array index.
Chris Lattner17300782005-11-18 18:30:47 +0000177 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerceda6052005-11-17 19:35:42 +0000178 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000179 i != e; ++i, ++GTI)
180 /*empty*/;
181 if (isa<SequentialType>(*GTI)) {
182 // Pull the last index out of the constant expr GEP.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000183 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000184 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000185 &CEIdxs[0],
186 CEIdxs.size());
David Greeneb8f74792007-09-04 15:46:09 +0000187 Value *Idx[2];
188 Idx[0] = Constant::getNullValue(Type::Int32Ty);
189 Idx[1] = NewAdd;
Gabor Greif051a9502008-04-06 20:25:17 +0000190 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
David Greeneb8f74792007-09-04 15:46:09 +0000191 NCE, Idx, Idx + 2,
Reid Spencercae57542007-03-02 00:28:52 +0000192 GEPI->getName(), GEPI);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000193 SE->deleteValueFromRecords(GEPI);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000194 GEPI->replaceAllUsesWith(NGEPI);
195 GEPI->eraseFromParent();
196 GEPI = NGEPI;
197 }
198 }
199 }
200
201
Chris Lattner40bf8b42004-04-02 20:24:31 +0000202 // Finally, if there are any other users of the PHI node, we must
203 // insert a new GEP instruction that uses the pre-incremented version
204 // of the induction amount.
205 if (!PN->use_empty()) {
206 BasicBlock::iterator InsertPos = PN; ++InsertPos;
207 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000208 Value *PreInc =
Gabor Greif051a9502008-04-06 20:25:17 +0000209 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
210 NewPhi, "", InsertPos);
Chris Lattner6934a042007-02-11 01:23:03 +0000211 PreInc->takeName(PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000212 PN->replaceAllUsesWith(PreInc);
213 }
214
215 // Delete the old PHI for sure, and the GEP if its otherwise unused.
216 DeadInsts.insert(PN);
217
218 ++NumPointer;
219 Changed = true;
220 }
221}
222
223/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000224/// loop to be a canonical != comparison against the incremented loop induction
225/// variable. This pass is able to rewrite the exit tests of any loop where the
226/// SCEV analysis can determine a loop-invariant trip count of the loop, which
227/// is actually a much broader range than just linear tests.
Chris Lattner9ba46c12006-09-21 05:12:20 +0000228///
229/// This method returns a "potentially dead" instruction whose computation chain
230/// should be deleted when convenient.
231Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
232 SCEV *IterationCount,
233 SCEVExpander &RW) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000234 // Find the exit block for the loop. We can currently only handle loops with
235 // a single exit.
Devang Patelb7211a22007-08-21 00:31:24 +0000236 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000237 L->getExitBlocks(ExitBlocks);
Chris Lattner9ba46c12006-09-21 05:12:20 +0000238 if (ExitBlocks.size() != 1) return 0;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000239 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000240
241 // Make sure there is only one predecessor block in the loop.
242 BasicBlock *ExitingBlock = 0;
243 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
244 PI != PE; ++PI)
245 if (L->contains(*PI)) {
246 if (ExitingBlock == 0)
247 ExitingBlock = *PI;
248 else
Chris Lattner9ba46c12006-09-21 05:12:20 +0000249 return 0; // Multiple exits from loop to this block.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000250 }
251 assert(ExitingBlock && "Loop info is broken");
252
253 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
Chris Lattner9ba46c12006-09-21 05:12:20 +0000254 return 0; // Can't rewrite non-branch yet
Chris Lattner40bf8b42004-04-02 20:24:31 +0000255 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
256 assert(BI->isConditional() && "Must be conditional to be part of loop!");
257
Chris Lattner9ba46c12006-09-21 05:12:20 +0000258 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
259
Chris Lattnerd2440572004-04-15 20:26:22 +0000260 // If the exiting block is not the same as the backedge block, we must compare
261 // against the preincremented value, otherwise we prefer to compare against
262 // the post-incremented value.
263 BasicBlock *Header = L->getHeader();
264 pred_iterator HPI = pred_begin(Header);
265 assert(HPI != pred_end(Header) && "Loop with zero preds???");
266 if (!L->contains(*HPI)) ++HPI;
267 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
268 "No backedge in loop?");
Chris Lattner59fdaee2004-04-15 15:21:43 +0000269
Chris Lattnerd2440572004-04-15 20:26:22 +0000270 SCEVHandle TripCount = IterationCount;
271 Value *IndVar;
272 if (*HPI == ExitingBlock) {
273 // The IterationCount expression contains the number of times that the
274 // backedge actually branches to the loop header. This is one less than the
275 // number of times the loop executes, so add one to it.
Dan Gohmane19dd872007-06-15 18:00:55 +0000276 ConstantInt *OneC = ConstantInt::get(IterationCount->getType(), 1);
Dan Gohman246b2562007-10-22 18:31:58 +0000277 TripCount = SE->getAddExpr(IterationCount, SE->getConstant(OneC));
Chris Lattnerd2440572004-04-15 20:26:22 +0000278 IndVar = L->getCanonicalInductionVariableIncrement();
279 } else {
280 // We have to use the preincremented value...
281 IndVar = L->getCanonicalInductionVariable();
282 }
Chris Lattneree4f13a2007-01-07 01:14:12 +0000283
284 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
285 << " IndVar = " << *IndVar << "\n";
Chris Lattner59fdaee2004-04-15 15:21:43 +0000286
Chris Lattner40bf8b42004-04-02 20:24:31 +0000287 // Expand the code for the iteration count into the preheader of the loop.
288 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmand19534a2007-06-15 14:38:12 +0000289 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000290
Reid Spencere4d87aa2006-12-23 06:05:41 +0000291 // Insert a new icmp_ne or icmp_eq instruction before the branch.
292 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000293 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000294 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000295 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000296 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000297
Reid Spencere4d87aa2006-12-23 06:05:41 +0000298 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000299 BI->setCondition(Cond);
300 ++NumLFTR;
301 Changed = true;
Chris Lattner9ba46c12006-09-21 05:12:20 +0000302 return PotentiallyDeadInst;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000303}
304
305
306/// RewriteLoopExitValues - Check to see if this loop has a computable
307/// loop-invariant execution count. If so, this means that we can compute the
308/// final value of any expressions that are recurrent in the loop, and
309/// substitute the exit values from the loop into any instructions outside of
310/// the loop that use the final values of the current expressions.
Dan Gohman5a6c4482008-08-05 22:34:21 +0000311void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000312 BasicBlock *Preheader = L->getLoopPreheader();
313
314 // Scan all of the instructions in the loop, looking at those that have
315 // extra-loop users and which are recurrences.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000316 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000317
318 // We insert the code into the preheader of the loop if the loop contains
319 // multiple exit blocks, or in the exit block if there is exactly one.
320 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000321 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000322 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000323 if (ExitBlocks.size() == 1)
324 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000325 else
326 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000327 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000328
Dan Gohman5a6c4482008-08-05 22:34:21 +0000329 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Chris Lattner20aa0982004-04-17 18:44:09 +0000330
Chris Lattner1a6111f2008-11-16 07:17:51 +0000331 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000332 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000333
Chris Lattner9f3d7382007-03-04 03:43:23 +0000334 // Find all values that are computed inside the loop, but used outside of it.
335 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
336 // the exit blocks of the loop to find them.
337 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
338 BasicBlock *ExitBB = ExitBlocks[i];
339
340 // If there are no PHI nodes in this exit block, then no values defined
341 // inside the loop are used on this path, skip it.
342 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
343 if (!PN) continue;
344
345 unsigned NumPreds = PN->getNumIncomingValues();
346
347 // Iterate over all of the PHI nodes.
348 BasicBlock::iterator BBI = ExitBB->begin();
349 while ((PN = dyn_cast<PHINode>(BBI++))) {
Chris Lattnerc9838f22007-03-03 22:48:48 +0000350
Chris Lattner9f3d7382007-03-04 03:43:23 +0000351 // Iterate over all of the values in all the PHI nodes.
352 for (unsigned i = 0; i != NumPreds; ++i) {
353 // If the value being merged in is not integer or is not defined
354 // in the loop, skip it.
355 Value *InVal = PN->getIncomingValue(i);
356 if (!isa<Instruction>(InVal) ||
357 // SCEV only supports integer expressions for now.
358 !isa<IntegerType>(InVal->getType()))
359 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000360
Chris Lattner9f3d7382007-03-04 03:43:23 +0000361 // If this pred is for a subloop, not L itself, skip it.
362 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
363 continue; // The Block is in a subloop, skip it.
364
365 // Check that InVal is defined in the loop.
366 Instruction *Inst = cast<Instruction>(InVal);
367 if (!L->contains(Inst->getParent()))
368 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000369
Chris Lattner9f3d7382007-03-04 03:43:23 +0000370 // We require that this value either have a computable evolution or that
371 // the loop have a constant iteration count. In the case where the loop
372 // has a constant iteration count, we can sometimes force evaluation of
373 // the exit value through brute force.
374 SCEVHandle SH = SE->getSCEV(Inst);
375 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
376 continue; // Cannot get exit evolution for the loop value.
377
378 // Okay, this instruction has a user outside of the current loop
379 // and varies predictably *inside* the loop. Evaluate the value it
380 // contains when the loop exits, if possible.
381 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
382 if (isa<SCEVCouldNotCompute>(ExitValue) ||
383 !ExitValue->isLoopInvariant(L))
384 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000385
Chris Lattner9f3d7382007-03-04 03:43:23 +0000386 Changed = true;
387 ++NumReplaced;
388
389 // See if we already computed the exit value for the instruction, if so,
390 // just reuse it.
391 Value *&ExitVal = ExitValues[Inst];
392 if (!ExitVal)
Dan Gohmand19534a2007-06-15 14:38:12 +0000393 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000394
395 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
396 << " LoopVal = " << *Inst << "\n";
397
398 PN->setIncomingValue(i, ExitVal);
399
400 // If this instruction is dead now, schedule it to be removed.
401 if (Inst->use_empty())
402 InstructionsToDelete.insert(Inst);
403
404 // See if this is a single-entry LCSSA PHI node. If so, we can (and
405 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000406 // the PHI entirely. This is safe, because the NewVal won't be variant
407 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000408 if (NumPreds == 1) {
Dan Gohman5cec4db2007-06-19 14:28:31 +0000409 SE->deleteValueFromRecords(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000410 PN->replaceAllUsesWith(ExitVal);
411 PN->eraseFromParent();
412 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000413 }
414 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000415 }
416 }
417
Chris Lattner40bf8b42004-04-02 20:24:31 +0000418 DeleteTriviallyDeadInstructions(InstructionsToDelete);
419}
420
Devang Patel5ee99972007-03-07 06:39:01 +0000421bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000422
Devang Patel5ee99972007-03-07 06:39:01 +0000423 Changed = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000424 // 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();
Devang Patel5ee99972007-03-07 06:39:01 +0000430 SE = &LPM.getAnalysis<ScalarEvolution>();
Misha Brukmanfd939082005-04-21 23:48:37 +0000431
Chris Lattner1a6111f2008-11-16 07:17:51 +0000432 SmallPtrSet<Instruction*, 16> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000433 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
434 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000435 if (isa<PointerType>(PN->getType()))
436 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Devang Patel84e35152008-11-17 21:32:02 +0000437 else
438 HandleFloatingPointIV(L, PN, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000439 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000440
441 if (!DeadInsts.empty())
442 DeleteTriviallyDeadInstructions(DeadInsts);
443
Devang Patel5ee99972007-03-07 06:39:01 +0000444 return Changed;
445}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000446
Devang Patel5ee99972007-03-07 06:39:01 +0000447bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner3324e712003-12-22 03:58:44 +0000448
Devang Patel5ee99972007-03-07 06:39:01 +0000449
450 LI = &getAnalysis<LoopInfo>();
451 SE = &getAnalysis<ScalarEvolution>();
452
453 Changed = false;
454 BasicBlock *Header = L->getHeader();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000455 SmallPtrSet<Instruction*, 16> DeadInsts;
Devang Patel5ee99972007-03-07 06:39:01 +0000456
Chris Lattner9caed542007-03-04 01:00:28 +0000457 // Verify the input to the pass in already in LCSSA form.
458 assert(L->isLCSSAForm());
459
Chris Lattner40bf8b42004-04-02 20:24:31 +0000460 // Check to see if this loop has a computable loop-invariant execution count.
461 // If so, this means that we can compute the final value of any expressions
462 // that are recurrent in the loop, and substitute the exit values from the
463 // loop into any instructions outside of the loop that use the final values of
464 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000465 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000466 SCEVHandle IterationCount = SE->getIterationCount(L);
467 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohman5a6c4482008-08-05 22:34:21 +0000468 RewriteLoopExitValues(L, IterationCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000469
Chris Lattner40bf8b42004-04-02 20:24:31 +0000470 // Next, analyze all of the induction variables in the loop, canonicalizing
471 // auxillary induction variables.
472 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
473
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000474 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
475 PHINode *PN = cast<PHINode>(I);
Chris Lattner42a75512007-01-15 02:27:26 +0000476 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattner40bf8b42004-04-02 20:24:31 +0000477 SCEVHandle SCEV = SE->getSCEV(PN);
478 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000479 // FIXME: It is an extremely bad idea to indvar substitute anything more
480 // complex than affine induction variables. Doing so will put expensive
481 // polynomial evaluations inside of the loop, and the str reduction pass
482 // currently can only reduce affine polynomials. For now just disable
483 // indvar subst on anything more complex than an affine addrec.
Chris Lattner595ee7e2004-07-26 02:47:12 +0000484 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000485 if (AR->isAffine())
Chris Lattner595ee7e2004-07-26 02:47:12 +0000486 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000487 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000488 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000489
490 // If there are no induction variables in the loop, there is nothing more to
491 // do.
Chris Lattnerf50af082004-04-17 18:08:33 +0000492 if (IndVars.empty()) {
493 // Actually, if we know how many times the loop iterates, lets insert a
494 // canonical induction variable to help subsequent passes.
495 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner4a7553e2004-04-23 21:29:48 +0000496 SCEVExpander Rewriter(*SE, *LI);
497 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattnerf50af082004-04-17 18:08:33 +0000498 IterationCount->getType());
Chris Lattner9ba46c12006-09-21 05:12:20 +0000499 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
500 Rewriter)) {
Chris Lattner1a6111f2008-11-16 07:17:51 +0000501 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9ba46c12006-09-21 05:12:20 +0000502 InstructionsToDelete.insert(I);
503 DeleteTriviallyDeadInstructions(InstructionsToDelete);
504 }
Chris Lattnerf50af082004-04-17 18:08:33 +0000505 }
Devang Patel5ee99972007-03-07 06:39:01 +0000506 return Changed;
Chris Lattnerf50af082004-04-17 18:08:33 +0000507 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000508
509 // Compute the type of the largest recurrence expression.
Chris Lattner6148c022001-12-03 17:28:42 +0000510 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000511 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000512 bool DifferingSizes = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000513 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
514 const Type *Ty = IndVars[i].first->getType();
Reid Spencerabaa8ca2007-01-08 16:32:00 +0000515 DifferingSizes |=
516 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
517 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
Chris Lattner40bf8b42004-04-02 20:24:31 +0000518 LargestType = Ty;
Chris Lattner6148c022001-12-03 17:28:42 +0000519 }
520
Chris Lattner40bf8b42004-04-02 20:24:31 +0000521 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000522 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000523
Chris Lattner40bf8b42004-04-02 20:24:31 +0000524 // Now that we know the largest of of the induction variables in this loop,
525 // insert a canonical induction variable of the largest size.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000526 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000527 ++NumInserted;
528 Changed = true;
Chris Lattneree4f13a2007-01-07 01:14:12 +0000529 DOUT << "INDVARS: New CanIV: " << *IndVar;
Chris Lattner15cad752003-12-23 07:47:09 +0000530
Dan Gohmand19534a2007-06-15 14:38:12 +0000531 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Wojciech Matyjewicz90087212008-06-13 17:02:03 +0000532 IterationCount = SE->getTruncateOrZeroExtend(IterationCount, LargestType);
Chris Lattner9ba46c12006-09-21 05:12:20 +0000533 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
534 DeadInsts.insert(DI);
Dan Gohmand19534a2007-06-15 14:38:12 +0000535 }
Chris Lattner15cad752003-12-23 07:47:09 +0000536
Chris Lattner40bf8b42004-04-02 20:24:31 +0000537 // Now that we have a canonical induction variable, we can rewrite any
538 // recurrences in terms of the induction variable. Start with the auxillary
539 // induction variables, and recursively rewrite any of their uses.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000540 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner6148c022001-12-03 17:28:42 +0000541
Chris Lattner5d461d22004-04-21 22:22:01 +0000542 // If there were induction variables of other sizes, cast the primary
543 // induction variable to the right size for them, avoiding the need for the
544 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000545 if (DifferingSizes) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000546 SmallVector<unsigned,4> InsertedSizes;
547 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
548 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
549 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
Chris Lattneref60b2c2007-01-12 22:51:20 +0000550 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
551 == InsertedSizes.end()) {
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000552 PHINode *PN = IndVars[i].first;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000553 InsertedSizes.push_back(ithSize);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000554 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
555 InsertPt);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000556 Rewriter.addInsertedValue(New, SE->getSCEV(New));
Chris Lattneree4f13a2007-01-07 01:14:12 +0000557 DOUT << "INDVARS: Made trunc IV for " << *PN
558 << " NewVal = " << *New << "\n";
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000559 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000560 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000561 }
562
Chris Lattneree4f13a2007-01-07 01:14:12 +0000563 // Rewrite all induction variables in terms of the canonical induction
564 // variable.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000565 while (!IndVars.empty()) {
566 PHINode *PN = IndVars.back().first;
Dan Gohmand19534a2007-06-15 14:38:12 +0000567 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000568 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
569 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000570 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000571
Chris Lattner40bf8b42004-04-02 20:24:31 +0000572 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000573 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000574 DeadInsts.insert(PN);
575 IndVars.pop_back();
576 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000577 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000578 }
579
Chris Lattnerb4782d12004-04-22 15:12:36 +0000580#if 0
Chris Lattner1363e852004-04-21 23:36:08 +0000581 // Now replace all derived expressions in the loop body with simpler
582 // expressions.
Dan Gohman9b787632008-06-22 20:18:58 +0000583 for (LoopInfo::block_iterator I = L->block_begin(), E = L->block_end();
584 I != E; ++I) {
585 BasicBlock *BB = *I;
586 if (LI->getLoopFor(BB) == L) { // Not in a subloop...
Chris Lattner40bf8b42004-04-02 20:24:31 +0000587 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +0000588 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattner1363e852004-04-21 23:36:08 +0000589 !I->use_empty() &&
Chris Lattner40bf8b42004-04-02 20:24:31 +0000590 !Rewriter.isInsertedInstruction(I)) {
591 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000592 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattner1363e852004-04-21 23:36:08 +0000593 if (V != I) {
Chris Lattner6934a042007-02-11 01:23:03 +0000594 if (isa<Instruction>(V))
595 V->takeName(I);
Chris Lattner1363e852004-04-21 23:36:08 +0000596 I->replaceAllUsesWith(V);
597 DeadInsts.insert(I);
598 ++NumRemoved;
599 Changed = true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000600 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000601 }
Chris Lattner394437f2001-12-04 04:32:29 +0000602 }
Dan Gohman9b787632008-06-22 20:18:58 +0000603 }
Chris Lattnerb4782d12004-04-22 15:12:36 +0000604#endif
Chris Lattner1363e852004-04-21 23:36:08 +0000605
Chris Lattner1363e852004-04-21 23:36:08 +0000606 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Pateld22a8492008-09-09 21:41:07 +0000607 OptimizeCanonicalIVType(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000608 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000609 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000610}
Devang Pateld22a8492008-09-09 21:41:07 +0000611
612/// OptimizeCanonicalIVType - If loop induction variable is always
Devang Patel36a5bf82008-09-10 14:49:55 +0000613/// sign or zero extended then extend the type of the induction
Devang Pateld22a8492008-09-09 21:41:07 +0000614/// variable.
615void IndVarSimplify::OptimizeCanonicalIVType(Loop *L) {
616 PHINode *PH = L->getCanonicalInductionVariable();
617 if (!PH) return;
618
619 // Check loop iteration count.
620 SCEVHandle IC = SE->getIterationCount(L);
621 if (isa<SCEVCouldNotCompute>(IC)) return;
622 SCEVConstant *IterationCount = dyn_cast<SCEVConstant>(IC);
623 if (!IterationCount) return;
624
625 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
626 unsigned BackEdge = IncomingEdge^1;
627
628 // Check IV uses. If all IV uses are either SEXT or ZEXT (except
629 // IV increment instruction) then this IV is suitable for this
Devang Patel36a5bf82008-09-10 14:49:55 +0000630 // transformation.
631 bool isSEXT = false;
Devang Pateld22a8492008-09-09 21:41:07 +0000632 BinaryOperator *Incr = NULL;
Devang Patel36a5bf82008-09-10 14:49:55 +0000633 const Type *NewType = NULL;
Devang Pateld22a8492008-09-09 21:41:07 +0000634 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
635 UI != UE; ++UI) {
636 const Type *CandidateType = NULL;
637 if (ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
638 CandidateType = ZI->getDestTy();
639 else if (SExtInst *SI = dyn_cast<SExtInst>(UI)) {
640 CandidateType = SI->getDestTy();
Devang Patel36a5bf82008-09-10 14:49:55 +0000641 isSEXT = true;
Devang Pateld22a8492008-09-09 21:41:07 +0000642 }
643 else if ((Incr = dyn_cast<BinaryOperator>(UI))) {
644 // Validate IV increment instruction.
645 if (PH->getIncomingValue(BackEdge) == Incr)
646 continue;
647 }
648 if (!CandidateType) {
649 NewType = NULL;
650 break;
651 }
652 if (!NewType)
653 NewType = CandidateType;
654 else if (NewType != CandidateType) {
655 NewType = NULL;
656 break;
657 }
658 }
659
660 // IV uses are not suitable then avoid this transformation.
661 if (!NewType || !Incr)
662 return;
663
664 // IV increment instruction has two uses, one is loop exit condition
665 // and second is the IV (phi node) itself.
666 ICmpInst *Exit = NULL;
667 for(Value::use_iterator II = Incr->use_begin(), IE = Incr->use_end();
668 II != IE; ++II) {
669 if (PH == *II) continue;
670 Exit = dyn_cast<ICmpInst>(*II);
671 break;
672 }
673 if (!Exit) return;
674 ConstantInt *EV = dyn_cast<ConstantInt>(Exit->getOperand(0));
675 if (!EV)
676 EV = dyn_cast<ConstantInt>(Exit->getOperand(1));
677 if (!EV) return;
678
679 // Check iteration count max value to avoid loops that wrap around IV.
680 APInt ICount = IterationCount->getValue()->getValue();
681 if (ICount.isNegative()) return;
682 uint32_t BW = PH->getType()->getPrimitiveSizeInBits();
683 APInt Max = (isSEXT ? APInt::getSignedMaxValue(BW) : APInt::getMaxValue(BW));
684 if (ICount.getZExtValue() > Max.getZExtValue()) return;
685
686 // Extend IV type.
687
688 SCEVExpander Rewriter(*SE, *LI);
689 Value *NewIV = Rewriter.getOrInsertCanonicalInductionVariable(L,NewType);
690 PHINode *NewPH = cast<PHINode>(NewIV);
691 Instruction *NewIncr = cast<Instruction>(NewPH->getIncomingValue(BackEdge));
692
693 // Replace all SEXT or ZEXT uses.
694 SmallVector<Instruction *, 4> PHUses;
695 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
696 UI != UE; ++UI) {
697 Instruction *I = cast<Instruction>(UI);
698 PHUses.push_back(I);
699 }
700 while (!PHUses.empty()){
701 Instruction *Use = PHUses.back(); PHUses.pop_back();
702 if (Incr == Use) continue;
703
704 SE->deleteValueFromRecords(Use);
705 Use->replaceAllUsesWith(NewIV);
706 Use->eraseFromParent();
707 }
708
709 // Replace exit condition.
710 ConstantInt *NEV = ConstantInt::get(NewType, EV->getZExtValue());
711 Instruction *NE = new ICmpInst(Exit->getPredicate(),
712 NewIncr, NEV, "new.exit",
713 Exit->getParent()->getTerminator());
714 SE->deleteValueFromRecords(Exit);
715 Exit->replaceAllUsesWith(NE);
716 Exit->eraseFromParent();
717
718 // Remove old IV and increment instructions.
719 SE->deleteValueFromRecords(PH);
720 PH->removeIncomingValue((unsigned)0);
721 PH->removeIncomingValue((unsigned)0);
722 SE->deleteValueFromRecords(Incr);
723 Incr->eraseFromParent();
724}
725
Devang Patel58d43d42008-11-03 18:32:19 +0000726/// HandleFloatingPointIV - If the loop has floating induction variable
727/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000728/// For example,
729/// for(double i = 0; i < 10000; ++i)
730/// bar(i)
731/// is converted into
732/// for(int i = 0; i < 10000; ++i)
733/// bar((double)i);
734///
735void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
736 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel58d43d42008-11-03 18:32:19 +0000737
Devang Patel84e35152008-11-17 21:32:02 +0000738 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
739 unsigned BackEdge = IncomingEdge^1;
740
741 // Check incoming value.
742 ConstantFP *CZ = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
743 if (!CZ) return;
744 APFloat PHInit = CZ->getValueAPF();
745 if (!PHInit.isPosZero()) return;
746
747 // Check IV increment.
748 BinaryOperator *Incr =
749 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
750 if (!Incr) return;
751 if (Incr->getOpcode() != Instruction::Add) return;
752 ConstantFP *IncrValue = NULL;
753 unsigned IncrVIndex = 1;
754 if (Incr->getOperand(1) == PH)
755 IncrVIndex = 0;
756 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
757 if (!IncrValue) return;
758 APFloat IVAPF = IncrValue->getValueAPF();
759 APFloat One = APFloat(IVAPF.getSemantics(), 1);
760 if (!IVAPF.bitwiseIsEqual(One)) return;
761
762 // Check Incr uses.
763 Value::use_iterator IncrUse = Incr->use_begin();
764 Instruction *U1 = cast<Instruction>(IncrUse++);
765 if (IncrUse == Incr->use_end()) return;
766 Instruction *U2 = cast<Instruction>(IncrUse++);
767 if (IncrUse != Incr->use_end()) return;
768
769 // Find exit condition.
770 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
771 if (!EC)
772 EC = dyn_cast<FCmpInst>(U2);
773 if (!EC) return;
774
775 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
776 if (!BI->isConditional()) return;
777 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000778 }
Devang Patel58d43d42008-11-03 18:32:19 +0000779
Devang Patel84e35152008-11-17 21:32:02 +0000780 // Find exit value.
781 ConstantFP *EV = NULL;
782 unsigned EVIndex = 1;
783 if (EC->getOperand(1) == Incr)
784 EVIndex = 0;
785 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
786 if (!EV) return;
787 APFloat EVAPF = EV->getValueAPF();
788 if (EVAPF.isNegative()) return;
789
790 // Find corresponding integer exit value.
791 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
792 bool isExact = false;
793 if (EVAPF.convertToInteger(&intEV, 32, false, APFloat::rmTowardZero, &isExact)
794 != APFloat::opOK)
795 return;
796 if (!isExact) return;
797
798 // Find new predicate for integer comparison.
799 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
800 switch (EC->getPredicate()) {
801 case CmpInst::FCMP_OEQ:
802 case CmpInst::FCMP_UEQ:
803 NewPred = CmpInst::ICMP_EQ;
804 break;
805 case CmpInst::FCMP_OGT:
806 case CmpInst::FCMP_UGT:
807 NewPred = CmpInst::ICMP_UGT;
808 break;
809 case CmpInst::FCMP_OGE:
810 case CmpInst::FCMP_UGE:
811 NewPred = CmpInst::ICMP_UGE;
812 break;
813 case CmpInst::FCMP_OLT:
814 case CmpInst::FCMP_ULT:
815 NewPred = CmpInst::ICMP_ULT;
816 break;
817 case CmpInst::FCMP_OLE:
818 case CmpInst::FCMP_ULE:
819 NewPred = CmpInst::ICMP_ULE;
820 break;
821 default:
822 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000823 }
Devang Patel84e35152008-11-17 21:32:02 +0000824 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
825
826 // Insert new integer induction variable.
827 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
828 PH->getName()+".int", PH);
829 NewPHI->addIncoming(Constant::getNullValue(NewPHI->getType()),
830 PH->getIncomingBlock(IncomingEdge));
831
832 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
833 ConstantInt::get(Type::Int32Ty, 1),
834 Incr->getName()+".int", Incr);
835 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
836
837 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
838 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
839 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
840 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
841 EC->getParent()->getTerminator());
842
843 // Delete old, floating point, exit comparision instruction.
844 EC->replaceAllUsesWith(NewEC);
845 DeadInsts.insert(EC);
846
847 // Delete old, floating point, increment instruction.
848 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
849 DeadInsts.insert(Incr);
850
851 // Replace floating induction variable.
852 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
853 PH->getParent()->getFirstNonPHI());
854 PH->replaceAllUsesWith(Conv);
855 DeadInsts.insert(PH);
Devang Patel58d43d42008-11-03 18:32:19 +0000856}
857