blob: 641be5ce541447c5946cf021695682a473cf6a69 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// 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//
14// This transformation makes the following changes to each loop with an
15// 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).
37//
38//===----------------------------------------------------------------------===//
39
40#define DEBUG_TYPE "indvars"
41#include "llvm/Transforms/Scalar.h"
42#include "llvm/BasicBlock.h"
43#include "llvm/Constants.h"
44#include "llvm/Instructions.h"
45#include "llvm/Type.h"
46#include "llvm/Analysis/ScalarEvolutionExpander.h"
47#include "llvm/Analysis/LoopInfo.h"
48#include "llvm/Analysis/LoopPass.h"
49#include "llvm/Support/CFG.h"
50#include "llvm/Support/Compiler.h"
51#include "llvm/Support/Debug.h"
52#include "llvm/Support/GetElementPtrTypeIterator.h"
53#include "llvm/Transforms/Utils/Local.h"
54#include "llvm/Support/CommandLine.h"
55#include "llvm/ADT/SmallVector.h"
Dan Gohmancacd2012009-02-12 22:19:27 +000056#include "llvm/ADT/SetVector.h"
Chris Lattnerb25465e2008-11-16 07:17:51 +000057#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058#include "llvm/ADT/Statistic.h"
59using namespace llvm;
60
61STATISTIC(NumRemoved , "Number of aux indvars removed");
62STATISTIC(NumPointer , "Number of pointer indvars promoted");
63STATISTIC(NumInserted, "Number of canonical indvars added");
64STATISTIC(NumReplaced, "Number of exit values replaced");
65STATISTIC(NumLFTR , "Number of loop exit tests replaced");
66
67namespace {
68 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
69 LoopInfo *LI;
70 ScalarEvolution *SE;
71 bool Changed;
72 public:
73
74 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000075 IndVarSimplify() : LoopPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076
77 bool runOnLoop(Loop *L, LPPassManager &LPM);
78 bool doInitialization(Loop *L, LPPassManager &LPM);
79 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patele6a8d482007-09-10 18:08:23 +000080 AU.addRequired<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081 AU.addRequiredID(LCSSAID);
82 AU.addRequiredID(LoopSimplifyID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083 AU.addRequired<LoopInfo>();
84 AU.addPreservedID(LoopSimplifyID);
85 AU.addPreservedID(LCSSAID);
86 AU.setPreservesCFG();
87 }
88
89 private:
90
91 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattnerb25465e2008-11-16 07:17:51 +000092 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohman1247dc32009-02-17 15:57:39 +000093 void LinearFunctionTestReplace(Loop *L, SCEVHandle IterationCount,
94 Value *IndVar,
Dan Gohmancacd2012009-02-12 22:19:27 +000095 BasicBlock *ExitingBlock,
96 BranchInst *BI,
97 SCEVExpander &Rewriter);
Dan Gohmand8dc3bb2008-08-05 22:34:21 +000098 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099
Chris Lattnerb25465e2008-11-16 07:17:51 +0000100 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Patelbda43802008-09-09 21:41:07 +0000101
Devang Patelc8dac622008-11-17 21:32:02 +0000102 void HandleFloatingPointIV(Loop *L, PHINode *PH,
103 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000105}
106
Dan Gohman089efff2008-05-13 00:00:25 +0000107char IndVarSimplify::ID = 0;
108static RegisterPass<IndVarSimplify>
109X("indvars", "Canonicalize Induction Variables");
110
Daniel Dunbar163555a2008-10-22 23:32:42 +0000111Pass *llvm::createIndVarSimplifyPass() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000112 return new IndVarSimplify();
113}
114
115/// DeleteTriviallyDeadInstructions - If any of the instructions is the
116/// specified set are trivially dead, delete them and see if this makes any of
117/// their operands subsequently dead.
118void IndVarSimplify::
Chris Lattnerb25465e2008-11-16 07:17:51 +0000119DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120 while (!Insts.empty()) {
121 Instruction *I = *Insts.begin();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000122 Insts.erase(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 if (isInstructionTriviallyDead(I)) {
124 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
125 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
126 Insts.insert(U);
127 SE->deleteValueFromRecords(I);
128 DOUT << "INDVARS: Deleting: " << *I;
129 I->eraseFromParent();
130 Changed = true;
131 }
132 }
133}
134
135
136/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
137/// recurrence. If so, change it into an integer recurrence, permitting
138/// analysis by the SCEV routines.
139void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
140 BasicBlock *Preheader,
Chris Lattnerb25465e2008-11-16 07:17:51 +0000141 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
143 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
144 unsigned BackedgeIdx = PreheaderIdx^1;
145 if (GetElementPtrInst *GEPI =
146 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
147 if (GEPI->getOperand(0) == PN) {
148 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
149 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
150
151 // Okay, we found a pointer recurrence. Transform this pointer
152 // recurrence into an integer recurrence. Compute the value that gets
153 // added to the pointer at every iteration.
154 Value *AddedVal = GEPI->getOperand(1);
155
156 // Insert a new integer PHI node into the top of the block.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000157 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
158 PN->getName()+".rec", PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
160
161 // Create the new add instruction.
Gabor Greifa645dd32008-05-16 19:29:10 +0000162 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 GEPI->getName()+".rec", GEPI);
164 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
165
166 // Update the existing GEP to use the recurrence.
167 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
168
169 // Update the GEP to use the new recurrence we just inserted.
170 GEPI->setOperand(1, NewAdd);
171
172 // If the incoming value is a constant expr GEP, try peeling out the array
173 // 0 index if possible to make things simpler.
174 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
175 if (CE->getOpcode() == Instruction::GetElementPtr) {
176 unsigned NumOps = CE->getNumOperands();
177 assert(NumOps > 1 && "CE folding didn't work!");
178 if (CE->getOperand(NumOps-1)->isNullValue()) {
179 // Check to make sure the last index really is an array index.
180 gep_type_iterator GTI = gep_type_begin(CE);
181 for (unsigned i = 1, e = CE->getNumOperands()-1;
182 i != e; ++i, ++GTI)
183 /*empty*/;
184 if (isa<SequentialType>(*GTI)) {
185 // Pull the last index out of the constant expr GEP.
186 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
187 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
188 &CEIdxs[0],
189 CEIdxs.size());
David Greene393be882007-09-04 15:46:09 +0000190 Value *Idx[2];
191 Idx[0] = Constant::getNullValue(Type::Int32Ty);
192 Idx[1] = NewAdd;
Gabor Greifd6da1d02008-04-06 20:25:17 +0000193 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
David Greene393be882007-09-04 15:46:09 +0000194 NCE, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 GEPI->getName(), GEPI);
196 SE->deleteValueFromRecords(GEPI);
197 GEPI->replaceAllUsesWith(NGEPI);
198 GEPI->eraseFromParent();
199 GEPI = NGEPI;
200 }
201 }
202 }
203
204
205 // Finally, if there are any other users of the PHI node, we must
206 // insert a new GEP instruction that uses the pre-incremented version
207 // of the induction amount.
208 if (!PN->use_empty()) {
209 BasicBlock::iterator InsertPos = PN; ++InsertPos;
210 while (isa<PHINode>(InsertPos)) ++InsertPos;
211 Value *PreInc =
Gabor Greifd6da1d02008-04-06 20:25:17 +0000212 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
213 NewPhi, "", InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 PreInc->takeName(PN);
215 PN->replaceAllUsesWith(PreInc);
216 }
217
218 // Delete the old PHI for sure, and the GEP if its otherwise unused.
219 DeadInsts.insert(PN);
220
221 ++NumPointer;
222 Changed = true;
223 }
224}
225
226/// LinearFunctionTestReplace - This method rewrites the exit condition of the
227/// loop to be a canonical != comparison against the incremented loop induction
228/// variable. This pass is able to rewrite the exit tests of any loop where the
229/// SCEV analysis can determine a loop-invariant trip count of the loop, which
230/// is actually a much broader range than just linear tests.
Dan Gohmancacd2012009-02-12 22:19:27 +0000231void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
232 SCEVHandle IterationCount,
233 Value *IndVar,
234 BasicBlock *ExitingBlock,
235 BranchInst *BI,
236 SCEVExpander &Rewriter) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 // If the exiting block is not the same as the backedge block, we must compare
238 // against the preincremented value, otherwise we prefer to compare against
239 // the post-incremented value.
Dan Gohmancacd2012009-02-12 22:19:27 +0000240 Value *CmpIndVar;
241 if (ExitingBlock == L->getLoopLatch()) {
242 // What ScalarEvolution calls the "iteration count" is actually the
243 // number of times the branch is taken. Add one to get the number
244 // of times the branch is executed. If this addition may overflow,
245 // we have to be more pessimistic and cast the induction variable
246 // before doing the add.
247 SCEVHandle Zero = SE->getIntegerSCEV(0, IterationCount->getType());
248 SCEVHandle N =
249 SE->getAddExpr(IterationCount,
250 SE->getIntegerSCEV(1, IterationCount->getType()));
251 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
252 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
253 // No overflow. Cast the sum.
254 IterationCount = SE->getTruncateOrZeroExtend(N, IndVar->getType());
255 } else {
256 // Potential overflow. Cast before doing the add.
257 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
258 IndVar->getType());
259 IterationCount =
260 SE->getAddExpr(IterationCount,
261 SE->getIntegerSCEV(1, IndVar->getType()));
262 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264 // The IterationCount expression contains the number of times that the
265 // backedge actually branches to the loop header. This is one less than the
266 // number of times the loop executes, so add one to it.
Dan Gohmancacd2012009-02-12 22:19:27 +0000267 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 } else {
269 // We have to use the preincremented value...
Dan Gohmancacd2012009-02-12 22:19:27 +0000270 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
271 IndVar->getType());
272 CmpIndVar = IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274
275 // Expand the code for the iteration count into the preheader of the loop.
276 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmancacd2012009-02-12 22:19:27 +0000277 Value *ExitCnt = Rewriter.expandCodeFor(IterationCount,
278 Preheader->getTerminator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279
280 // Insert a new icmp_ne or icmp_eq instruction before the branch.
281 ICmpInst::Predicate Opcode;
282 if (L->contains(BI->getSuccessor(0)))
283 Opcode = ICmpInst::ICMP_NE;
284 else
285 Opcode = ICmpInst::ICMP_EQ;
286
Dan Gohmancacd2012009-02-12 22:19:27 +0000287 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
288 << " LHS:" << *CmpIndVar // includes a newline
289 << " op:\t"
Dan Gohman8555ff72009-02-14 02:26:50 +0000290 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohmancacd2012009-02-12 22:19:27 +0000291 << " RHS:\t" << *IterationCount << "\n";
292
293 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 BI->setCondition(Cond);
295 ++NumLFTR;
296 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297}
298
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299/// RewriteLoopExitValues - Check to see if this loop has a computable
300/// loop-invariant execution count. If so, this means that we can compute the
301/// final value of any expressions that are recurrent in the loop, and
302/// substitute the exit values from the loop into any instructions outside of
303/// the loop that use the final values of the current expressions.
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000304void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305 BasicBlock *Preheader = L->getLoopPreheader();
306
307 // Scan all of the instructions in the loop, looking at those that have
308 // extra-loop users and which are recurrences.
309 SCEVExpander Rewriter(*SE, *LI);
310
311 // We insert the code into the preheader of the loop if the loop contains
312 // multiple exit blocks, or in the exit block if there is exactly one.
313 BasicBlock *BlockToInsertInto;
Devang Patel02451fa2007-08-21 00:31:24 +0000314 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 L->getUniqueExitBlocks(ExitBlocks);
316 if (ExitBlocks.size() == 1)
317 BlockToInsertInto = ExitBlocks[0];
318 else
319 BlockToInsertInto = Preheader;
Dan Gohman514277c2008-05-23 21:05:58 +0000320 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000322 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323
Chris Lattnerb25465e2008-11-16 07:17:51 +0000324 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 std::map<Instruction*, Value*> ExitValues;
326
327 // Find all values that are computed inside the loop, but used outside of it.
328 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
329 // the exit blocks of the loop to find them.
330 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
331 BasicBlock *ExitBB = ExitBlocks[i];
332
333 // If there are no PHI nodes in this exit block, then no values defined
334 // inside the loop are used on this path, skip it.
335 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
336 if (!PN) continue;
337
338 unsigned NumPreds = PN->getNumIncomingValues();
339
340 // Iterate over all of the PHI nodes.
341 BasicBlock::iterator BBI = ExitBB->begin();
342 while ((PN = dyn_cast<PHINode>(BBI++))) {
343
344 // Iterate over all of the values in all the PHI nodes.
345 for (unsigned i = 0; i != NumPreds; ++i) {
346 // If the value being merged in is not integer or is not defined
347 // in the loop, skip it.
348 Value *InVal = PN->getIncomingValue(i);
349 if (!isa<Instruction>(InVal) ||
350 // SCEV only supports integer expressions for now.
351 !isa<IntegerType>(InVal->getType()))
352 continue;
353
354 // If this pred is for a subloop, not L itself, skip it.
355 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
356 continue; // The Block is in a subloop, skip it.
357
358 // Check that InVal is defined in the loop.
359 Instruction *Inst = cast<Instruction>(InVal);
360 if (!L->contains(Inst->getParent()))
361 continue;
362
363 // We require that this value either have a computable evolution or that
364 // the loop have a constant iteration count. In the case where the loop
365 // has a constant iteration count, we can sometimes force evaluation of
366 // the exit value through brute force.
367 SCEVHandle SH = SE->getSCEV(Inst);
368 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
369 continue; // Cannot get exit evolution for the loop value.
370
371 // Okay, this instruction has a user outside of the current loop
372 // and varies predictably *inside* the loop. Evaluate the value it
373 // contains when the loop exits, if possible.
374 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
375 if (isa<SCEVCouldNotCompute>(ExitValue) ||
376 !ExitValue->isLoopInvariant(L))
377 continue;
378
379 Changed = true;
380 ++NumReplaced;
381
382 // See if we already computed the exit value for the instruction, if so,
383 // just reuse it.
384 Value *&ExitVal = ExitValues[Inst];
385 if (!ExitVal)
386 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
387
388 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
389 << " LoopVal = " << *Inst << "\n";
390
391 PN->setIncomingValue(i, ExitVal);
392
393 // If this instruction is dead now, schedule it to be removed.
394 if (Inst->use_empty())
395 InstructionsToDelete.insert(Inst);
396
397 // See if this is a single-entry LCSSA PHI node. If so, we can (and
398 // have to) remove
399 // the PHI entirely. This is safe, because the NewVal won't be variant
400 // in the loop, so we don't need an LCSSA phi node anymore.
401 if (NumPreds == 1) {
402 SE->deleteValueFromRecords(PN);
403 PN->replaceAllUsesWith(ExitVal);
404 PN->eraseFromParent();
405 break;
406 }
407 }
408 }
409 }
410
411 DeleteTriviallyDeadInstructions(InstructionsToDelete);
412}
413
414bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
415
416 Changed = false;
417 // First step. Check to see if there are any trivial GEP pointer recurrences.
418 // If there are, change them into integer recurrences, permitting analysis by
419 // the SCEV routines.
420 //
421 BasicBlock *Header = L->getHeader();
422 BasicBlock *Preheader = L->getLoopPreheader();
423 SE = &LPM.getAnalysis<ScalarEvolution>();
424
Chris Lattnerb25465e2008-11-16 07:17:51 +0000425 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
427 PHINode *PN = cast<PHINode>(I);
428 if (isa<PointerType>(PN->getType()))
429 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Devang Patelc8dac622008-11-17 21:32:02 +0000430 else
431 HandleFloatingPointIV(L, PN, DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 }
433
434 if (!DeadInsts.empty())
435 DeleteTriviallyDeadInstructions(DeadInsts);
436
437 return Changed;
438}
439
Dan Gohmancacd2012009-02-12 22:19:27 +0000440/// getEffectiveIndvarType - Determine the widest type that the
441/// induction-variable PHINode Phi is cast to.
442///
443static const Type *getEffectiveIndvarType(const PHINode *Phi) {
444 const Type *Ty = Phi->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000445
Dan Gohmancacd2012009-02-12 22:19:27 +0000446 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
447 UI != UE; ++UI) {
448 const Type *CandidateType = NULL;
449 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
450 CandidateType = ZI->getDestTy();
451 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
452 CandidateType = SI->getDestTy();
453 if (CandidateType &&
454 CandidateType->getPrimitiveSizeInBits() >
455 Ty->getPrimitiveSizeInBits())
456 Ty = CandidateType;
457 }
458
459 return Ty;
460}
461
Dan Gohmancecc80f2009-02-14 02:31:09 +0000462/// TestOrigIVForWrap - Analyze the original induction variable
463/// in the loop to determine whether it would ever undergo signed
464/// or unsigned overflow.
Dan Gohmancacd2012009-02-12 22:19:27 +0000465///
466/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohmancecc80f2009-02-14 02:31:09 +0000467/// Perhaps this can be merged with ScalarEvolution::getIterationCount
468/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmancacd2012009-02-12 22:19:27 +0000469///
Dan Gohmancecc80f2009-02-14 02:31:09 +0000470static void TestOrigIVForWrap(const Loop *L,
471 const BranchInst *BI,
472 const Instruction *OrigCond,
473 bool &NoSignedWrap,
474 bool &NoUnsignedWrap) {
Dan Gohmancacd2012009-02-12 22:19:27 +0000475 // Verify that the loop is sane and find the exit condition.
476 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000477 if (!Cmp) return;
Dan Gohmancacd2012009-02-12 22:19:27 +0000478
Dan Gohmancecc80f2009-02-14 02:31:09 +0000479 const Value *CmpLHS = Cmp->getOperand(0);
480 const Value *CmpRHS = Cmp->getOperand(1);
481 const BasicBlock *TrueBB = BI->getSuccessor(0);
482 const BasicBlock *FalseBB = BI->getSuccessor(1);
483 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmancacd2012009-02-12 22:19:27 +0000484
Dan Gohmancecc80f2009-02-14 02:31:09 +0000485 // Canonicalize a constant to the RHS.
486 if (isa<ConstantInt>(CmpLHS)) {
487 Pred = ICmpInst::getSwappedPredicate(Pred);
488 std::swap(CmpLHS, CmpRHS);
489 }
490 // Canonicalize SLE to SLT.
491 if (Pred == ICmpInst::ICMP_SLE)
492 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
493 if (!CI->getValue().isMaxSignedValue()) {
494 CmpRHS = ConstantInt::get(CI->getValue() + 1);
495 Pred = ICmpInst::ICMP_SLT;
496 }
497 // Canonicalize SGT to SGE.
498 if (Pred == ICmpInst::ICMP_SGT)
499 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
500 if (!CI->getValue().isMaxSignedValue()) {
501 CmpRHS = ConstantInt::get(CI->getValue() + 1);
502 Pred = ICmpInst::ICMP_SGE;
503 }
504 // Canonicalize SGE to SLT.
505 if (Pred == ICmpInst::ICMP_SGE) {
506 std::swap(TrueBB, FalseBB);
507 Pred = ICmpInst::ICMP_SLT;
508 }
509 // Canonicalize ULE to ULT.
510 if (Pred == ICmpInst::ICMP_ULE)
511 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
512 if (!CI->getValue().isMaxValue()) {
513 CmpRHS = ConstantInt::get(CI->getValue() + 1);
514 Pred = ICmpInst::ICMP_ULT;
515 }
516 // Canonicalize UGT to UGE.
517 if (Pred == ICmpInst::ICMP_UGT)
518 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
519 if (!CI->getValue().isMaxValue()) {
520 CmpRHS = ConstantInt::get(CI->getValue() + 1);
521 Pred = ICmpInst::ICMP_UGE;
522 }
523 // Canonicalize UGE to ULT.
524 if (Pred == ICmpInst::ICMP_UGE) {
525 std::swap(TrueBB, FalseBB);
526 Pred = ICmpInst::ICMP_ULT;
527 }
528 // For now, analyze only LT loops for signed overflow.
529 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
530 return;
531
532 bool isSigned = Pred == ICmpInst::ICMP_SLT;
533
534 // Get the increment instruction. Look past casts if we will
Dan Gohmancacd2012009-02-12 22:19:27 +0000535 // be able to prove that the original induction variable doesn't
Dan Gohmancecc80f2009-02-14 02:31:09 +0000536 // undergo signed or unsigned overflow, respectively.
537 const Value *IncrVal = CmpLHS;
538 if (isSigned) {
539 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
540 if (!isa<ConstantInt>(CmpRHS) ||
541 !cast<ConstantInt>(CmpRHS)->getValue()
542 .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
543 return;
544 IncrVal = SI->getOperand(0);
545 }
546 } else {
547 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
548 if (!isa<ConstantInt>(CmpRHS) ||
549 !cast<ConstantInt>(CmpRHS)->getValue()
550 .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
551 return;
552 IncrVal = ZI->getOperand(0);
553 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000554 }
555
556 // For now, only analyze induction variables that have simple increments.
557 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
558 if (!IncrOp ||
559 IncrOp->getOpcode() != Instruction::Add ||
560 !isa<ConstantInt>(IncrOp->getOperand(1)) ||
561 !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
Dan Gohmancecc80f2009-02-14 02:31:09 +0000562 return;
Dan Gohmancacd2012009-02-12 22:19:27 +0000563
564 // Make sure the PHI looks like a normal IV.
565 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
566 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmancecc80f2009-02-14 02:31:09 +0000567 return;
Dan Gohmancacd2012009-02-12 22:19:27 +0000568 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
569 unsigned BackEdge = !IncomingEdge;
570 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
571 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmancecc80f2009-02-14 02:31:09 +0000572 return;
573 if (!L->contains(TrueBB))
574 return;
Dan Gohmancacd2012009-02-12 22:19:27 +0000575
576 // For now, only analyze loops with a constant start value, so that
Dan Gohmancecc80f2009-02-14 02:31:09 +0000577 // we can easily determine if the start value is not a maximum value
578 // which would wrap on the first iteration.
Dan Gohmancacd2012009-02-12 22:19:27 +0000579 const Value *InitialVal = PN->getIncomingValue(IncomingEdge);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000580 if (!isa<ConstantInt>(InitialVal))
581 return;
Dan Gohmancacd2012009-02-12 22:19:27 +0000582
Dan Gohmancecc80f2009-02-14 02:31:09 +0000583 // The original induction variable will start at some non-max value,
584 // it counts up by one, and the loop iterates only while it remans
585 // less than some value in the same type. As such, it will never wrap.
586 if (isSigned &&
587 !cast<ConstantInt>(InitialVal)->getValue().isMaxSignedValue())
588 NoSignedWrap = true;
589 else if (!isSigned &&
590 !cast<ConstantInt>(InitialVal)->getValue().isMaxValue())
591 NoUnsignedWrap = true;
Dan Gohmancacd2012009-02-12 22:19:27 +0000592}
593
594bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595 LI = &getAnalysis<LoopInfo>();
596 SE = &getAnalysis<ScalarEvolution>();
597
598 Changed = false;
Dan Gohmancacd2012009-02-12 22:19:27 +0000599 BasicBlock *Header = L->getHeader();
600 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000601 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmancacd2012009-02-12 22:19:27 +0000602
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603 // Verify the input to the pass in already in LCSSA form.
604 assert(L->isLCSSAForm());
605
606 // Check to see if this loop has a computable loop-invariant execution count.
607 // If so, this means that we can compute the final value of any expressions
608 // that are recurrent in the loop, and substitute the exit values from the
609 // loop into any instructions outside of the loop that use the final values of
610 // the current expressions.
611 //
612 SCEVHandle IterationCount = SE->getIterationCount(L);
613 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000614 RewriteLoopExitValues(L, IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615
616 // Next, analyze all of the induction variables in the loop, canonicalizing
617 // auxillary induction variables.
618 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
619
620 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
621 PHINode *PN = cast<PHINode>(I);
622 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
623 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohman173d9142009-02-14 02:25:19 +0000624 // FIXME: It is an extremely bad idea to indvar substitute anything more
625 // complex than affine induction variables. Doing so will put expensive
626 // polynomial evaluations inside of the loop, and the str reduction pass
627 // currently can only reduce affine polynomials. For now just disable
628 // indvar subst on anything more complex than an affine addrec.
629 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
630 if (AR->getLoop() == L && AR->isAffine())
631 IndVars.push_back(std::make_pair(PN, SCEV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 }
633 }
634
Dan Gohmancacd2012009-02-12 22:19:27 +0000635 // Compute the type of the largest recurrence expression, and collect
636 // the set of the types of the other recurrence expressions.
637 const Type *LargestType = 0;
638 SmallSetVector<const Type *, 4> SizesToInsert;
639 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
640 LargestType = IterationCount->getType();
641 SizesToInsert.insert(IterationCount->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000643 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
644 const PHINode *PN = IndVars[i].first;
645 SizesToInsert.insert(PN->getType());
646 const Type *EffTy = getEffectiveIndvarType(PN);
647 SizesToInsert.insert(EffTy);
648 if (!LargestType ||
649 EffTy->getPrimitiveSizeInBits() >
650 LargestType->getPrimitiveSizeInBits())
651 LargestType = EffTy;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 }
653
654 // Create a rewriter object which we'll use to transform the code with.
655 SCEVExpander Rewriter(*SE, *LI);
656
657 // Now that we know the largest of of the induction variables in this loop,
658 // insert a canonical induction variable of the largest size.
Dan Gohmancacd2012009-02-12 22:19:27 +0000659 Value *IndVar = 0;
660 if (!SizesToInsert.empty()) {
661 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
662 ++NumInserted;
663 Changed = true;
664 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665 }
666
Dan Gohmancacd2012009-02-12 22:19:27 +0000667 // If we have a trip count expression, rewrite the loop's exit condition
668 // using it. We can currently only handle loops with a single exit.
Dan Gohmancecc80f2009-02-14 02:31:09 +0000669 bool NoSignedWrap = false;
670 bool NoUnsignedWrap = false;
Dan Gohmancacd2012009-02-12 22:19:27 +0000671 if (!isa<SCEVCouldNotCompute>(IterationCount) && ExitingBlock)
672 // Can't rewrite non-branch yet.
673 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
674 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmancecc80f2009-02-14 02:31:09 +0000675 // Determine if the OrigIV will ever undergo overflow.
676 TestOrigIVForWrap(L, BI, OrigCond,
677 NoSignedWrap, NoUnsignedWrap);
Dan Gohmancacd2012009-02-12 22:19:27 +0000678
679 // We'll be replacing the original condition, so it'll be dead.
680 DeadInsts.insert(OrigCond);
681 }
682
683 LinearFunctionTestReplace(L, IterationCount, IndVar,
684 ExitingBlock, BI, Rewriter);
685 }
686
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687 // Now that we have a canonical induction variable, we can rewrite any
688 // recurrences in terms of the induction variable. Start with the auxillary
689 // induction variables, and recursively rewrite any of their uses.
Dan Gohman514277c2008-05-23 21:05:58 +0000690 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691
692 // If there were induction variables of other sizes, cast the primary
693 // induction variable to the right size for them, avoiding the need for the
694 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmancacd2012009-02-12 22:19:27 +0000695 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
696 const Type *Ty = SizesToInsert[i];
697 if (Ty != LargestType) {
698 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
699 Rewriter.addInsertedValue(New, SE->getSCEV(New));
700 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
701 << *New << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702 }
703 }
704
705 // Rewrite all induction variables in terms of the canonical induction
706 // variable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707 while (!IndVars.empty()) {
708 PHINode *PN = IndVars.back().first;
Dan Gohmanc71cac12009-02-17 00:10:53 +0000709 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
710 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
711 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000712 << " into = " << *NewVal << "\n";
713 NewVal->takeName(PN);
714
Dan Gohmancacd2012009-02-12 22:19:27 +0000715 /// If the new canonical induction variable is wider than the original,
716 /// and the original has uses that are casts to wider types, see if the
717 /// truncate and extend can be omitted.
Dan Gohmancecc80f2009-02-14 02:31:09 +0000718 if (PN->getType() != LargestType)
Dan Gohmancacd2012009-02-12 22:19:27 +0000719 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmancecc80f2009-02-14 02:31:09 +0000720 UI != UE; ++UI) {
721 if (isa<SExtInst>(UI) && NoSignedWrap) {
722 SCEVHandle ExtendedStart =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000723 SE->getSignExtendExpr(AR->getStart(), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000724 SCEVHandle ExtendedStep =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000725 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000726 SCEVHandle ExtendedAddRec =
727 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
728 if (LargestType != UI->getType())
729 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
730 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
Dan Gohmancacd2012009-02-12 22:19:27 +0000731 UI->replaceAllUsesWith(TruncIndVar);
732 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
733 DeadInsts.insert(DeadUse);
734 }
Dan Gohmancecc80f2009-02-14 02:31:09 +0000735 if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
736 SCEVHandle ExtendedStart =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000737 SE->getZeroExtendExpr(AR->getStart(), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000738 SCEVHandle ExtendedStep =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000739 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000740 SCEVHandle ExtendedAddRec =
741 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
742 if (LargestType != UI->getType())
743 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
744 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
745 UI->replaceAllUsesWith(TruncIndVar);
746 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
747 DeadInsts.insert(DeadUse);
748 }
749 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000750
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 // Replace the old PHI Node with the inserted computation.
752 PN->replaceAllUsesWith(NewVal);
753 DeadInsts.insert(PN);
754 IndVars.pop_back();
755 ++NumRemoved;
756 Changed = true;
757 }
758
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759 DeleteTriviallyDeadInstructions(DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760 assert(L->isLCSSAForm());
761 return Changed;
762}
Devang Patelbda43802008-09-09 21:41:07 +0000763
Devang Patelb8ccf572008-11-18 00:40:02 +0000764/// Return true if it is OK to use SIToFPInst for an inducation variable
765/// with given inital and exit values.
766static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
767 uint64_t intIV, uint64_t intEV) {
768
769 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
770 return true;
771
772 // If the iteration range can be handled by SIToFPInst then use it.
773 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendlingb9a5a682008-11-18 10:57:27 +0000774 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patelb8ccf572008-11-18 00:40:02 +0000775 return true;
776
777 return false;
778}
779
780/// convertToInt - Convert APF to an integer, if possible.
Devang Patele2ba01d2008-11-17 23:27:13 +0000781static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
782
783 bool isExact = false;
Evan Cheng30e65f62008-11-26 01:11:57 +0000784 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
785 return false;
Devang Patele2ba01d2008-11-17 23:27:13 +0000786 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
787 APFloat::rmTowardZero, &isExact)
788 != APFloat::opOK)
789 return false;
790 if (!isExact)
791 return false;
792 return true;
793
794}
795
Devang Patel7ca23c92008-11-03 18:32:19 +0000796/// HandleFloatingPointIV - If the loop has floating induction variable
797/// then insert corresponding integer induction variable if possible.
Devang Patelc8dac622008-11-17 21:32:02 +0000798/// For example,
799/// for(double i = 0; i < 10000; ++i)
800/// bar(i)
801/// is converted into
802/// for(int i = 0; i < 10000; ++i)
803/// bar((double)i);
804///
805void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
806 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel7ca23c92008-11-03 18:32:19 +0000807
Devang Patelc8dac622008-11-17 21:32:02 +0000808 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
809 unsigned BackEdge = IncomingEdge^1;
810
811 // Check incoming value.
Devang Patele2ba01d2008-11-17 23:27:13 +0000812 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
813 if (!InitValue) return;
814 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
815 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
816 return;
817
818 // Check IV increment. Reject this PH if increement operation is not
819 // an add or increment value can not be represented by an integer.
Devang Patelc8dac622008-11-17 21:32:02 +0000820 BinaryOperator *Incr =
821 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
822 if (!Incr) return;
823 if (Incr->getOpcode() != Instruction::Add) return;
824 ConstantFP *IncrValue = NULL;
825 unsigned IncrVIndex = 1;
826 if (Incr->getOperand(1) == PH)
827 IncrVIndex = 0;
828 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
829 if (!IncrValue) return;
Devang Patele2ba01d2008-11-17 23:27:13 +0000830 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
831 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
832 return;
Devang Patelc8dac622008-11-17 21:32:02 +0000833
Devang Patele2ba01d2008-11-17 23:27:13 +0000834 // Check Incr uses. One user is PH and the other users is exit condition used
835 // by the conditional terminator.
Devang Patelc8dac622008-11-17 21:32:02 +0000836 Value::use_iterator IncrUse = Incr->use_begin();
837 Instruction *U1 = cast<Instruction>(IncrUse++);
838 if (IncrUse == Incr->use_end()) return;
839 Instruction *U2 = cast<Instruction>(IncrUse++);
840 if (IncrUse != Incr->use_end()) return;
841
842 // Find exit condition.
843 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
844 if (!EC)
845 EC = dyn_cast<FCmpInst>(U2);
846 if (!EC) return;
847
848 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
849 if (!BI->isConditional()) return;
850 if (BI->getCondition() != EC) return;
Devang Patel7ca23c92008-11-03 18:32:19 +0000851 }
Devang Patel7ca23c92008-11-03 18:32:19 +0000852
Devang Patele2ba01d2008-11-17 23:27:13 +0000853 // Find exit value. If exit value can not be represented as an interger then
854 // do not handle this floating point PH.
Devang Patelc8dac622008-11-17 21:32:02 +0000855 ConstantFP *EV = NULL;
856 unsigned EVIndex = 1;
857 if (EC->getOperand(1) == Incr)
858 EVIndex = 0;
859 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
860 if (!EV) return;
Devang Patelc8dac622008-11-17 21:32:02 +0000861 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patele2ba01d2008-11-17 23:27:13 +0000862 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patelc8dac622008-11-17 21:32:02 +0000863 return;
Devang Patelc8dac622008-11-17 21:32:02 +0000864
865 // Find new predicate for integer comparison.
866 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
867 switch (EC->getPredicate()) {
868 case CmpInst::FCMP_OEQ:
869 case CmpInst::FCMP_UEQ:
870 NewPred = CmpInst::ICMP_EQ;
871 break;
872 case CmpInst::FCMP_OGT:
873 case CmpInst::FCMP_UGT:
874 NewPred = CmpInst::ICMP_UGT;
875 break;
876 case CmpInst::FCMP_OGE:
877 case CmpInst::FCMP_UGE:
878 NewPred = CmpInst::ICMP_UGE;
879 break;
880 case CmpInst::FCMP_OLT:
881 case CmpInst::FCMP_ULT:
882 NewPred = CmpInst::ICMP_ULT;
883 break;
884 case CmpInst::FCMP_OLE:
885 case CmpInst::FCMP_ULE:
886 NewPred = CmpInst::ICMP_ULE;
887 break;
888 default:
889 break;
Devang Patel7ca23c92008-11-03 18:32:19 +0000890 }
Devang Patelc8dac622008-11-17 21:32:02 +0000891 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
892
893 // Insert new integer induction variable.
894 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
895 PH->getName()+".int", PH);
Devang Patele2ba01d2008-11-17 23:27:13 +0000896 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000897 PH->getIncomingBlock(IncomingEdge));
898
899 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
Devang Patele2ba01d2008-11-17 23:27:13 +0000900 ConstantInt::get(Type::Int32Ty,
901 newIncrValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000902 Incr->getName()+".int", Incr);
903 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
904
905 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
906 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
907 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
908 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
909 EC->getParent()->getTerminator());
910
911 // Delete old, floating point, exit comparision instruction.
912 EC->replaceAllUsesWith(NewEC);
913 DeadInsts.insert(EC);
914
915 // Delete old, floating point, increment instruction.
916 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
917 DeadInsts.insert(Incr);
918
Devang Patelb8ccf572008-11-18 00:40:02 +0000919 // Replace floating induction variable. Give SIToFPInst preference over
920 // UIToFPInst because it is faster on platforms that are widely used.
921 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Devang Patele2ba01d2008-11-17 23:27:13 +0000922 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
923 PH->getParent()->getFirstNonPHI());
924 PH->replaceAllUsesWith(Conv);
925 } else {
926 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
927 PH->getParent()->getFirstNonPHI());
928 PH->replaceAllUsesWith(Conv);
929 }
Devang Patelc8dac622008-11-17 21:32:02 +0000930 DeadInsts.insert(PH);
Devang Patel7ca23c92008-11-03 18:32:19 +0000931}
932