blob: fabbf6e19e58e0b5a1dff6f74f9f4c07a705b60e [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 LI = &getAnalysis<LoopInfo>();
450 SE = &getAnalysis<ScalarEvolution>();
451
452 Changed = false;
453 BasicBlock *Header = L->getHeader();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000454 SmallPtrSet<Instruction*, 16> DeadInsts;
Devang Patel5ee99972007-03-07 06:39:01 +0000455
Chris Lattner9caed542007-03-04 01:00:28 +0000456 // Verify the input to the pass in already in LCSSA form.
457 assert(L->isLCSSAForm());
458
Chris Lattner40bf8b42004-04-02 20:24:31 +0000459 // Check to see if this loop has a computable loop-invariant execution count.
460 // If so, this means that we can compute the final value of any expressions
461 // that are recurrent in the loop, and substitute the exit values from the
462 // loop into any instructions outside of the loop that use the final values of
463 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000464 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000465 SCEVHandle IterationCount = SE->getIterationCount(L);
466 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohman5a6c4482008-08-05 22:34:21 +0000467 RewriteLoopExitValues(L, IterationCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000468
Chris Lattner40bf8b42004-04-02 20:24:31 +0000469 // Next, analyze all of the induction variables in the loop, canonicalizing
470 // auxillary induction variables.
471 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
472
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000473 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
474 PHINode *PN = cast<PHINode>(I);
Chris Lattner42a75512007-01-15 02:27:26 +0000475 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattner40bf8b42004-04-02 20:24:31 +0000476 SCEVHandle SCEV = SE->getSCEV(PN);
477 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000478 // FIXME: It is an extremely bad idea to indvar substitute anything more
479 // complex than affine induction variables. Doing so will put expensive
480 // polynomial evaluations inside of the loop, and the str reduction pass
481 // currently can only reduce affine polynomials. For now just disable
482 // indvar subst on anything more complex than an affine addrec.
Chris Lattner595ee7e2004-07-26 02:47:12 +0000483 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000484 if (AR->isAffine())
Chris Lattner595ee7e2004-07-26 02:47:12 +0000485 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000486 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000487 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000488
489 // If there are no induction variables in the loop, there is nothing more to
490 // do.
Chris Lattnerf50af082004-04-17 18:08:33 +0000491 if (IndVars.empty()) {
492 // Actually, if we know how many times the loop iterates, lets insert a
493 // canonical induction variable to help subsequent passes.
494 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner4a7553e2004-04-23 21:29:48 +0000495 SCEVExpander Rewriter(*SE, *LI);
496 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattnerf50af082004-04-17 18:08:33 +0000497 IterationCount->getType());
Chris Lattner9ba46c12006-09-21 05:12:20 +0000498 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
499 Rewriter)) {
Chris Lattner1a6111f2008-11-16 07:17:51 +0000500 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9ba46c12006-09-21 05:12:20 +0000501 InstructionsToDelete.insert(I);
502 DeleteTriviallyDeadInstructions(InstructionsToDelete);
503 }
Chris Lattnerf50af082004-04-17 18:08:33 +0000504 }
Devang Patel5ee99972007-03-07 06:39:01 +0000505 return Changed;
Chris Lattnerf50af082004-04-17 18:08:33 +0000506 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000507
508 // Compute the type of the largest recurrence expression.
Chris Lattner6148c022001-12-03 17:28:42 +0000509 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000510 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000511 bool DifferingSizes = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000512 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
513 const Type *Ty = IndVars[i].first->getType();
Reid Spencerabaa8ca2007-01-08 16:32:00 +0000514 DifferingSizes |=
515 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
516 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
Chris Lattner40bf8b42004-04-02 20:24:31 +0000517 LargestType = Ty;
Chris Lattner6148c022001-12-03 17:28:42 +0000518 }
519
Chris Lattner40bf8b42004-04-02 20:24:31 +0000520 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000521 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000522
Chris Lattner40bf8b42004-04-02 20:24:31 +0000523 // Now that we know the largest of of the induction variables in this loop,
524 // insert a canonical induction variable of the largest size.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000525 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000526 ++NumInserted;
527 Changed = true;
Chris Lattneree4f13a2007-01-07 01:14:12 +0000528 DOUT << "INDVARS: New CanIV: " << *IndVar;
Chris Lattner15cad752003-12-23 07:47:09 +0000529
Dan Gohmand19534a2007-06-15 14:38:12 +0000530 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Wojciech Matyjewicz90087212008-06-13 17:02:03 +0000531 IterationCount = SE->getTruncateOrZeroExtend(IterationCount, LargestType);
Chris Lattner9ba46c12006-09-21 05:12:20 +0000532 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
533 DeadInsts.insert(DI);
Dan Gohmand19534a2007-06-15 14:38:12 +0000534 }
Chris Lattner15cad752003-12-23 07:47:09 +0000535
Chris Lattner40bf8b42004-04-02 20:24:31 +0000536 // Now that we have a canonical induction variable, we can rewrite any
537 // recurrences in terms of the induction variable. Start with the auxillary
538 // induction variables, and recursively rewrite any of their uses.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000539 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner6148c022001-12-03 17:28:42 +0000540
Chris Lattner5d461d22004-04-21 22:22:01 +0000541 // If there were induction variables of other sizes, cast the primary
542 // induction variable to the right size for them, avoiding the need for the
543 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000544 if (DifferingSizes) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000545 SmallVector<unsigned,4> InsertedSizes;
546 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
547 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
548 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
Chris Lattneref60b2c2007-01-12 22:51:20 +0000549 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
550 == InsertedSizes.end()) {
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000551 PHINode *PN = IndVars[i].first;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000552 InsertedSizes.push_back(ithSize);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000553 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
554 InsertPt);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000555 Rewriter.addInsertedValue(New, SE->getSCEV(New));
Chris Lattneree4f13a2007-01-07 01:14:12 +0000556 DOUT << "INDVARS: Made trunc IV for " << *PN
557 << " NewVal = " << *New << "\n";
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000558 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000559 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000560 }
561
Chris Lattneree4f13a2007-01-07 01:14:12 +0000562 // Rewrite all induction variables in terms of the canonical induction
563 // variable.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000564 while (!IndVars.empty()) {
565 PHINode *PN = IndVars.back().first;
Dan Gohmand19534a2007-06-15 14:38:12 +0000566 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000567 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
568 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000569 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000570
Chris Lattner40bf8b42004-04-02 20:24:31 +0000571 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000572 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000573 DeadInsts.insert(PN);
574 IndVars.pop_back();
575 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000576 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000577 }
578
Chris Lattnerb4782d12004-04-22 15:12:36 +0000579#if 0
Chris Lattner1363e852004-04-21 23:36:08 +0000580 // Now replace all derived expressions in the loop body with simpler
581 // expressions.
Dan Gohman9b787632008-06-22 20:18:58 +0000582 for (LoopInfo::block_iterator I = L->block_begin(), E = L->block_end();
583 I != E; ++I) {
584 BasicBlock *BB = *I;
585 if (LI->getLoopFor(BB) == L) { // Not in a subloop...
Chris Lattner40bf8b42004-04-02 20:24:31 +0000586 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +0000587 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattner1363e852004-04-21 23:36:08 +0000588 !I->use_empty() &&
Chris Lattner40bf8b42004-04-02 20:24:31 +0000589 !Rewriter.isInsertedInstruction(I)) {
590 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000591 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattner1363e852004-04-21 23:36:08 +0000592 if (V != I) {
Chris Lattner6934a042007-02-11 01:23:03 +0000593 if (isa<Instruction>(V))
594 V->takeName(I);
Chris Lattner1363e852004-04-21 23:36:08 +0000595 I->replaceAllUsesWith(V);
596 DeadInsts.insert(I);
597 ++NumRemoved;
598 Changed = true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000599 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000600 }
Chris Lattner394437f2001-12-04 04:32:29 +0000601 }
Dan Gohman9b787632008-06-22 20:18:58 +0000602 }
Chris Lattnerb4782d12004-04-22 15:12:36 +0000603#endif
Chris Lattner1363e852004-04-21 23:36:08 +0000604
Chris Lattner1363e852004-04-21 23:36:08 +0000605 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Pateld22a8492008-09-09 21:41:07 +0000606 OptimizeCanonicalIVType(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000607 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000608 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000609}
Devang Pateld22a8492008-09-09 21:41:07 +0000610
611/// OptimizeCanonicalIVType - If loop induction variable is always
Devang Patel36a5bf82008-09-10 14:49:55 +0000612/// sign or zero extended then extend the type of the induction
Devang Pateld22a8492008-09-09 21:41:07 +0000613/// variable.
614void IndVarSimplify::OptimizeCanonicalIVType(Loop *L) {
615 PHINode *PH = L->getCanonicalInductionVariable();
616 if (!PH) return;
617
618 // Check loop iteration count.
619 SCEVHandle IC = SE->getIterationCount(L);
620 if (isa<SCEVCouldNotCompute>(IC)) return;
621 SCEVConstant *IterationCount = dyn_cast<SCEVConstant>(IC);
622 if (!IterationCount) return;
623
624 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
625 unsigned BackEdge = IncomingEdge^1;
626
627 // Check IV uses. If all IV uses are either SEXT or ZEXT (except
628 // IV increment instruction) then this IV is suitable for this
Devang Patel36a5bf82008-09-10 14:49:55 +0000629 // transformation.
630 bool isSEXT = false;
Devang Pateld22a8492008-09-09 21:41:07 +0000631 BinaryOperator *Incr = NULL;
Devang Patel36a5bf82008-09-10 14:49:55 +0000632 const Type *NewType = NULL;
Devang Pateld22a8492008-09-09 21:41:07 +0000633 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
634 UI != UE; ++UI) {
635 const Type *CandidateType = NULL;
636 if (ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
637 CandidateType = ZI->getDestTy();
638 else if (SExtInst *SI = dyn_cast<SExtInst>(UI)) {
639 CandidateType = SI->getDestTy();
Devang Patel36a5bf82008-09-10 14:49:55 +0000640 isSEXT = true;
Devang Pateld22a8492008-09-09 21:41:07 +0000641 }
642 else if ((Incr = dyn_cast<BinaryOperator>(UI))) {
643 // Validate IV increment instruction.
644 if (PH->getIncomingValue(BackEdge) == Incr)
645 continue;
646 }
647 if (!CandidateType) {
648 NewType = NULL;
649 break;
650 }
651 if (!NewType)
652 NewType = CandidateType;
653 else if (NewType != CandidateType) {
654 NewType = NULL;
655 break;
656 }
657 }
658
659 // IV uses are not suitable then avoid this transformation.
660 if (!NewType || !Incr)
661 return;
662
663 // IV increment instruction has two uses, one is loop exit condition
664 // and second is the IV (phi node) itself.
665 ICmpInst *Exit = NULL;
666 for(Value::use_iterator II = Incr->use_begin(), IE = Incr->use_end();
667 II != IE; ++II) {
668 if (PH == *II) continue;
669 Exit = dyn_cast<ICmpInst>(*II);
670 break;
671 }
672 if (!Exit) return;
673 ConstantInt *EV = dyn_cast<ConstantInt>(Exit->getOperand(0));
674 if (!EV)
675 EV = dyn_cast<ConstantInt>(Exit->getOperand(1));
676 if (!EV) return;
677
678 // Check iteration count max value to avoid loops that wrap around IV.
679 APInt ICount = IterationCount->getValue()->getValue();
680 if (ICount.isNegative()) return;
681 uint32_t BW = PH->getType()->getPrimitiveSizeInBits();
682 APInt Max = (isSEXT ? APInt::getSignedMaxValue(BW) : APInt::getMaxValue(BW));
683 if (ICount.getZExtValue() > Max.getZExtValue()) return;
684
685 // Extend IV type.
686
687 SCEVExpander Rewriter(*SE, *LI);
688 Value *NewIV = Rewriter.getOrInsertCanonicalInductionVariable(L,NewType);
689 PHINode *NewPH = cast<PHINode>(NewIV);
690 Instruction *NewIncr = cast<Instruction>(NewPH->getIncomingValue(BackEdge));
691
692 // Replace all SEXT or ZEXT uses.
693 SmallVector<Instruction *, 4> PHUses;
694 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
695 UI != UE; ++UI) {
696 Instruction *I = cast<Instruction>(UI);
697 PHUses.push_back(I);
698 }
699 while (!PHUses.empty()){
700 Instruction *Use = PHUses.back(); PHUses.pop_back();
701 if (Incr == Use) continue;
702
703 SE->deleteValueFromRecords(Use);
704 Use->replaceAllUsesWith(NewIV);
705 Use->eraseFromParent();
706 }
707
708 // Replace exit condition.
709 ConstantInt *NEV = ConstantInt::get(NewType, EV->getZExtValue());
710 Instruction *NE = new ICmpInst(Exit->getPredicate(),
711 NewIncr, NEV, "new.exit",
712 Exit->getParent()->getTerminator());
713 SE->deleteValueFromRecords(Exit);
714 Exit->replaceAllUsesWith(NE);
715 Exit->eraseFromParent();
716
717 // Remove old IV and increment instructions.
718 SE->deleteValueFromRecords(PH);
719 PH->removeIncomingValue((unsigned)0);
720 PH->removeIncomingValue((unsigned)0);
721 SE->deleteValueFromRecords(Incr);
722 Incr->eraseFromParent();
723}
724
Devang Patel13877bf2008-11-18 00:40:02 +0000725/// Return true if it is OK to use SIToFPInst for an inducation variable
726/// with given inital and exit values.
727static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
728 uint64_t intIV, uint64_t intEV) {
729
730 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
731 return true;
732
733 // If the iteration range can be handled by SIToFPInst then use it.
734 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendling9bef7062008-11-18 10:57:27 +0000735 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000736 return true;
737
738 return false;
739}
740
741/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000742static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
743
744 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000745 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
746 return false;
Devang Patelcd402332008-11-17 23:27:13 +0000747 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
748 APFloat::rmTowardZero, &isExact)
749 != APFloat::opOK)
750 return false;
751 if (!isExact)
752 return false;
753 return true;
754
755}
756
Devang Patel58d43d42008-11-03 18:32:19 +0000757/// HandleFloatingPointIV - If the loop has floating induction variable
758/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000759/// For example,
760/// for(double i = 0; i < 10000; ++i)
761/// bar(i)
762/// is converted into
763/// for(int i = 0; i < 10000; ++i)
764/// bar((double)i);
765///
766void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
767 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel58d43d42008-11-03 18:32:19 +0000768
Devang Patel84e35152008-11-17 21:32:02 +0000769 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
770 unsigned BackEdge = IncomingEdge^1;
771
772 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000773 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
774 if (!InitValue) return;
775 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
776 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
777 return;
778
779 // Check IV increment. Reject this PH if increement operation is not
780 // an add or increment value can not be represented by an integer.
Devang Patel84e35152008-11-17 21:32:02 +0000781 BinaryOperator *Incr =
782 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
783 if (!Incr) return;
784 if (Incr->getOpcode() != Instruction::Add) return;
785 ConstantFP *IncrValue = NULL;
786 unsigned IncrVIndex = 1;
787 if (Incr->getOperand(1) == PH)
788 IncrVIndex = 0;
789 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
790 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000791 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
792 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
793 return;
Devang Patel84e35152008-11-17 21:32:02 +0000794
Devang Patelcd402332008-11-17 23:27:13 +0000795 // Check Incr uses. One user is PH and the other users is exit condition used
796 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000797 Value::use_iterator IncrUse = Incr->use_begin();
798 Instruction *U1 = cast<Instruction>(IncrUse++);
799 if (IncrUse == Incr->use_end()) return;
800 Instruction *U2 = cast<Instruction>(IncrUse++);
801 if (IncrUse != Incr->use_end()) return;
802
803 // Find exit condition.
804 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
805 if (!EC)
806 EC = dyn_cast<FCmpInst>(U2);
807 if (!EC) return;
808
809 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
810 if (!BI->isConditional()) return;
811 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000812 }
Devang Patel58d43d42008-11-03 18:32:19 +0000813
Devang Patelcd402332008-11-17 23:27:13 +0000814 // Find exit value. If exit value can not be represented as an interger then
815 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000816 ConstantFP *EV = NULL;
817 unsigned EVIndex = 1;
818 if (EC->getOperand(1) == Incr)
819 EVIndex = 0;
820 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
821 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000822 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000823 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000824 return;
Devang Patel84e35152008-11-17 21:32:02 +0000825
826 // Find new predicate for integer comparison.
827 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
828 switch (EC->getPredicate()) {
829 case CmpInst::FCMP_OEQ:
830 case CmpInst::FCMP_UEQ:
831 NewPred = CmpInst::ICMP_EQ;
832 break;
833 case CmpInst::FCMP_OGT:
834 case CmpInst::FCMP_UGT:
835 NewPred = CmpInst::ICMP_UGT;
836 break;
837 case CmpInst::FCMP_OGE:
838 case CmpInst::FCMP_UGE:
839 NewPred = CmpInst::ICMP_UGE;
840 break;
841 case CmpInst::FCMP_OLT:
842 case CmpInst::FCMP_ULT:
843 NewPred = CmpInst::ICMP_ULT;
844 break;
845 case CmpInst::FCMP_OLE:
846 case CmpInst::FCMP_ULE:
847 NewPred = CmpInst::ICMP_ULE;
848 break;
849 default:
850 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000851 }
Devang Patel84e35152008-11-17 21:32:02 +0000852 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
853
854 // Insert new integer induction variable.
855 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
856 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +0000857 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000858 PH->getIncomingBlock(IncomingEdge));
859
860 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
Devang Patelcd402332008-11-17 23:27:13 +0000861 ConstantInt::get(Type::Int32Ty,
862 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000863 Incr->getName()+".int", Incr);
864 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
865
866 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
867 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
868 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
869 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
870 EC->getParent()->getTerminator());
871
872 // Delete old, floating point, exit comparision instruction.
873 EC->replaceAllUsesWith(NewEC);
874 DeadInsts.insert(EC);
875
876 // Delete old, floating point, increment instruction.
877 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
878 DeadInsts.insert(Incr);
879
Devang Patel13877bf2008-11-18 00:40:02 +0000880 // Replace floating induction variable. Give SIToFPInst preference over
881 // UIToFPInst because it is faster on platforms that are widely used.
882 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Devang Patelcd402332008-11-17 23:27:13 +0000883 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
884 PH->getParent()->getFirstNonPHI());
885 PH->replaceAllUsesWith(Conv);
886 } else {
887 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
888 PH->getParent()->getFirstNonPHI());
889 PH->replaceAllUsesWith(Conv);
890 }
Devang Patel84e35152008-11-17 21:32:02 +0000891 DeadInsts.insert(PH);
Devang Patel58d43d42008-11-03 18:32:19 +0000892}
893