blob: 4cfe3595beeaa2d075ec7b9dbe1263e410affe22 [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
Dan Gohmanf3a060a2009-02-17 20:49:49 +000077 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
78
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079 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
Dan Gohmanf3a060a2009-02-17 20:49:49 +000091 void RewriteNonIntegerIVs(Loop *L);
92
Dan Gohmanf17a25c2007-07-18 16:29:46 +000093 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattnerb25465e2008-11-16 07:17:51 +000094 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohman1247dc32009-02-17 15:57:39 +000095 void LinearFunctionTestReplace(Loop *L, SCEVHandle IterationCount,
96 Value *IndVar,
Dan Gohmancacd2012009-02-12 22:19:27 +000097 BasicBlock *ExitingBlock,
98 BranchInst *BI,
99 SCEVExpander &Rewriter);
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000100 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101
Chris Lattnerb25465e2008-11-16 07:17:51 +0000102 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Patelbda43802008-09-09 21:41:07 +0000103
Dan Gohman963fc812009-02-17 19:13:57 +0000104 void HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patelc8dac622008-11-17 21:32:02 +0000105 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107}
108
Dan Gohman089efff2008-05-13 00:00:25 +0000109char IndVarSimplify::ID = 0;
110static RegisterPass<IndVarSimplify>
111X("indvars", "Canonicalize Induction Variables");
112
Daniel Dunbar163555a2008-10-22 23:32:42 +0000113Pass *llvm::createIndVarSimplifyPass() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 return new IndVarSimplify();
115}
116
117/// DeleteTriviallyDeadInstructions - If any of the instructions is the
118/// specified set are trivially dead, delete them and see if this makes any of
119/// their operands subsequently dead.
120void IndVarSimplify::
Chris Lattnerb25465e2008-11-16 07:17:51 +0000121DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122 while (!Insts.empty()) {
123 Instruction *I = *Insts.begin();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000124 Insts.erase(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125 if (isInstructionTriviallyDead(I)) {
126 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
127 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
128 Insts.insert(U);
129 SE->deleteValueFromRecords(I);
130 DOUT << "INDVARS: Deleting: " << *I;
131 I->eraseFromParent();
132 Changed = true;
133 }
134 }
135}
136
137
138/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
139/// recurrence. If so, change it into an integer recurrence, permitting
140/// analysis by the SCEV routines.
141void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
142 BasicBlock *Preheader,
Chris Lattnerb25465e2008-11-16 07:17:51 +0000143 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
145 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
146 unsigned BackedgeIdx = PreheaderIdx^1;
147 if (GetElementPtrInst *GEPI =
148 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
149 if (GEPI->getOperand(0) == PN) {
150 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
151 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
Dan Gohman963fc812009-02-17 19:13:57 +0000152
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 // Okay, we found a pointer recurrence. Transform this pointer
154 // recurrence into an integer recurrence. Compute the value that gets
155 // added to the pointer at every iteration.
156 Value *AddedVal = GEPI->getOperand(1);
157
158 // Insert a new integer PHI node into the top of the block.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000159 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
160 PN->getName()+".rec", PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
162
163 // Create the new add instruction.
Gabor Greifa645dd32008-05-16 19:29:10 +0000164 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165 GEPI->getName()+".rec", GEPI);
166 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
167
168 // Update the existing GEP to use the recurrence.
169 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
170
171 // Update the GEP to use the new recurrence we just inserted.
172 GEPI->setOperand(1, NewAdd);
173
174 // If the incoming value is a constant expr GEP, try peeling out the array
175 // 0 index if possible to make things simpler.
176 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
177 if (CE->getOpcode() == Instruction::GetElementPtr) {
178 unsigned NumOps = CE->getNumOperands();
179 assert(NumOps > 1 && "CE folding didn't work!");
180 if (CE->getOperand(NumOps-1)->isNullValue()) {
181 // Check to make sure the last index really is an array index.
182 gep_type_iterator GTI = gep_type_begin(CE);
183 for (unsigned i = 1, e = CE->getNumOperands()-1;
184 i != e; ++i, ++GTI)
185 /*empty*/;
186 if (isa<SequentialType>(*GTI)) {
187 // Pull the last index out of the constant expr GEP.
188 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
189 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
190 &CEIdxs[0],
191 CEIdxs.size());
David Greene393be882007-09-04 15:46:09 +0000192 Value *Idx[2];
193 Idx[0] = Constant::getNullValue(Type::Int32Ty);
194 Idx[1] = NewAdd;
Gabor Greifd6da1d02008-04-06 20:25:17 +0000195 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
Dan Gohman963fc812009-02-17 19:13:57 +0000196 NCE, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 GEPI->getName(), GEPI);
198 SE->deleteValueFromRecords(GEPI);
199 GEPI->replaceAllUsesWith(NGEPI);
200 GEPI->eraseFromParent();
201 GEPI = NGEPI;
202 }
203 }
204 }
205
206
207 // Finally, if there are any other users of the PHI node, we must
208 // insert a new GEP instruction that uses the pre-incremented version
209 // of the induction amount.
210 if (!PN->use_empty()) {
211 BasicBlock::iterator InsertPos = PN; ++InsertPos;
212 while (isa<PHINode>(InsertPos)) ++InsertPos;
213 Value *PreInc =
Gabor Greifd6da1d02008-04-06 20:25:17 +0000214 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
215 NewPhi, "", InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 PreInc->takeName(PN);
217 PN->replaceAllUsesWith(PreInc);
218 }
219
220 // Delete the old PHI for sure, and the GEP if its otherwise unused.
221 DeadInsts.insert(PN);
222
223 ++NumPointer;
224 Changed = true;
225 }
226}
227
228/// LinearFunctionTestReplace - This method rewrites the exit condition of the
229/// loop to be a canonical != comparison against the incremented loop induction
230/// variable. This pass is able to rewrite the exit tests of any loop where the
231/// SCEV analysis can determine a loop-invariant trip count of the loop, which
232/// is actually a much broader range than just linear tests.
Dan Gohmancacd2012009-02-12 22:19:27 +0000233void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
234 SCEVHandle IterationCount,
235 Value *IndVar,
236 BasicBlock *ExitingBlock,
237 BranchInst *BI,
238 SCEVExpander &Rewriter) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 // If the exiting block is not the same as the backedge block, we must compare
240 // against the preincremented value, otherwise we prefer to compare against
241 // the post-incremented value.
Dan Gohmancacd2012009-02-12 22:19:27 +0000242 Value *CmpIndVar;
243 if (ExitingBlock == L->getLoopLatch()) {
244 // What ScalarEvolution calls the "iteration count" is actually the
245 // number of times the branch is taken. Add one to get the number
246 // of times the branch is executed. If this addition may overflow,
247 // we have to be more pessimistic and cast the induction variable
248 // before doing the add.
249 SCEVHandle Zero = SE->getIntegerSCEV(0, IterationCount->getType());
250 SCEVHandle N =
251 SE->getAddExpr(IterationCount,
252 SE->getIntegerSCEV(1, IterationCount->getType()));
253 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
254 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
255 // No overflow. Cast the sum.
256 IterationCount = SE->getTruncateOrZeroExtend(N, IndVar->getType());
257 } else {
258 // Potential overflow. Cast before doing the add.
259 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
260 IndVar->getType());
261 IterationCount =
262 SE->getAddExpr(IterationCount,
263 SE->getIntegerSCEV(1, IndVar->getType()));
264 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266 // The IterationCount expression contains the number of times that the
267 // backedge actually branches to the loop header. This is one less than the
268 // number of times the loop executes, so add one to it.
Dan Gohmancacd2012009-02-12 22:19:27 +0000269 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 } else {
271 // We have to use the preincremented value...
Dan Gohmancacd2012009-02-12 22:19:27 +0000272 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
273 IndVar->getType());
274 CmpIndVar = IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276
277 // Expand the code for the iteration count into the preheader of the loop.
278 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmancacd2012009-02-12 22:19:27 +0000279 Value *ExitCnt = Rewriter.expandCodeFor(IterationCount,
280 Preheader->getTerminator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281
282 // Insert a new icmp_ne or icmp_eq instruction before the branch.
283 ICmpInst::Predicate Opcode;
284 if (L->contains(BI->getSuccessor(0)))
285 Opcode = ICmpInst::ICMP_NE;
286 else
287 Opcode = ICmpInst::ICMP_EQ;
288
Dan Gohmancacd2012009-02-12 22:19:27 +0000289 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
290 << " LHS:" << *CmpIndVar // includes a newline
291 << " op:\t"
Dan Gohman8555ff72009-02-14 02:26:50 +0000292 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohmancacd2012009-02-12 22:19:27 +0000293 << " RHS:\t" << *IterationCount << "\n";
294
295 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 BI->setCondition(Cond);
297 ++NumLFTR;
298 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299}
300
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301/// RewriteLoopExitValues - Check to see if this loop has a computable
302/// loop-invariant execution count. If so, this means that we can compute the
303/// final value of any expressions that are recurrent in the loop, and
304/// substitute the exit values from the loop into any instructions outside of
305/// the loop that use the final values of the current expressions.
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000306void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 BasicBlock *Preheader = L->getLoopPreheader();
308
309 // Scan all of the instructions in the loop, looking at those that have
310 // extra-loop users and which are recurrences.
311 SCEVExpander Rewriter(*SE, *LI);
312
313 // We insert the code into the preheader of the loop if the loop contains
314 // multiple exit blocks, or in the exit block if there is exactly one.
315 BasicBlock *BlockToInsertInto;
Devang Patel02451fa2007-08-21 00:31:24 +0000316 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 L->getUniqueExitBlocks(ExitBlocks);
318 if (ExitBlocks.size() == 1)
319 BlockToInsertInto = ExitBlocks[0];
320 else
321 BlockToInsertInto = Preheader;
Dan Gohman514277c2008-05-23 21:05:58 +0000322 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000324 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325
Chris Lattnerb25465e2008-11-16 07:17:51 +0000326 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327 std::map<Instruction*, Value*> ExitValues;
328
329 // Find all values that are computed inside the loop, but used outside of it.
330 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
331 // the exit blocks of the loop to find them.
332 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
333 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohman963fc812009-02-17 19:13:57 +0000334
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 // If there are no PHI nodes in this exit block, then no values defined
336 // inside the loop are used on this path, skip it.
337 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
338 if (!PN) continue;
Dan Gohman963fc812009-02-17 19:13:57 +0000339
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohman963fc812009-02-17 19:13:57 +0000341
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 // Iterate over all of the PHI nodes.
343 BasicBlock::iterator BBI = ExitBB->begin();
344 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohman963fc812009-02-17 19:13:57 +0000345
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 // Iterate over all of the values in all the PHI nodes.
347 for (unsigned i = 0; i != NumPreds; ++i) {
348 // If the value being merged in is not integer or is not defined
349 // in the loop, skip it.
350 Value *InVal = PN->getIncomingValue(i);
351 if (!isa<Instruction>(InVal) ||
352 // SCEV only supports integer expressions for now.
353 !isa<IntegerType>(InVal->getType()))
354 continue;
355
356 // If this pred is for a subloop, not L itself, skip it.
Dan Gohman963fc812009-02-17 19:13:57 +0000357 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358 continue; // The Block is in a subloop, skip it.
359
360 // Check that InVal is defined in the loop.
361 Instruction *Inst = cast<Instruction>(InVal);
362 if (!L->contains(Inst->getParent()))
363 continue;
Dan Gohman963fc812009-02-17 19:13:57 +0000364
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365 // We require that this value either have a computable evolution or that
366 // the loop have a constant iteration count. In the case where the loop
367 // has a constant iteration count, we can sometimes force evaluation of
368 // the exit value through brute force.
369 SCEVHandle SH = SE->getSCEV(Inst);
370 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
371 continue; // Cannot get exit evolution for the loop value.
Dan Gohman963fc812009-02-17 19:13:57 +0000372
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000373 // Okay, this instruction has a user outside of the current loop
374 // and varies predictably *inside* the loop. Evaluate the value it
375 // contains when the loop exits, if possible.
376 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
377 if (isa<SCEVCouldNotCompute>(ExitValue) ||
378 !ExitValue->isLoopInvariant(L))
379 continue;
380
381 Changed = true;
382 ++NumReplaced;
Dan Gohman963fc812009-02-17 19:13:57 +0000383
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 // See if we already computed the exit value for the instruction, if so,
385 // just reuse it.
386 Value *&ExitVal = ExitValues[Inst];
387 if (!ExitVal)
388 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Dan Gohman963fc812009-02-17 19:13:57 +0000389
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
391 << " LoopVal = " << *Inst << "\n";
392
393 PN->setIncomingValue(i, ExitVal);
Dan Gohman963fc812009-02-17 19:13:57 +0000394
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395 // If this instruction is dead now, schedule it to be removed.
396 if (Inst->use_empty())
397 InstructionsToDelete.insert(Inst);
Dan Gohman963fc812009-02-17 19:13:57 +0000398
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 // See if this is a single-entry LCSSA PHI node. If so, we can (and
400 // have to) remove
401 // the PHI entirely. This is safe, because the NewVal won't be variant
402 // in the loop, so we don't need an LCSSA phi node anymore.
403 if (NumPreds == 1) {
404 SE->deleteValueFromRecords(PN);
405 PN->replaceAllUsesWith(ExitVal);
406 PN->eraseFromParent();
407 break;
408 }
409 }
410 }
411 }
Dan Gohman963fc812009-02-17 19:13:57 +0000412
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413 DeleteTriviallyDeadInstructions(InstructionsToDelete);
414}
415
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000416void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417 // 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();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423
Chris Lattnerb25465e2008-11-16 07:17:51 +0000424 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
426 PHINode *PN = cast<PHINode>(I);
427 if (isa<PointerType>(PN->getType()))
428 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Devang Patelc8dac622008-11-17 21:32:02 +0000429 else
430 HandleFloatingPointIV(L, PN, DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 }
432
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000433 // If the loop previously had a pointer or floating-point IV, ScalarEvolution
434 // may not have been able to compute a trip count. Now that we've done some
435 // re-writing, the trip count may be computable.
436 if (Changed)
437 SE->forgetLoopIterationCount(L);
438
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439 if (!DeadInsts.empty())
440 DeleteTriviallyDeadInstructions(DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441}
442
Dan Gohmancacd2012009-02-12 22:19:27 +0000443/// getEffectiveIndvarType - Determine the widest type that the
444/// induction-variable PHINode Phi is cast to.
445///
446static const Type *getEffectiveIndvarType(const PHINode *Phi) {
447 const Type *Ty = Phi->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448
Dan Gohmancacd2012009-02-12 22:19:27 +0000449 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
450 UI != UE; ++UI) {
451 const Type *CandidateType = NULL;
452 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
453 CandidateType = ZI->getDestTy();
454 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
455 CandidateType = SI->getDestTy();
456 if (CandidateType &&
457 CandidateType->getPrimitiveSizeInBits() >
458 Ty->getPrimitiveSizeInBits())
459 Ty = CandidateType;
460 }
461
462 return Ty;
463}
464
Dan Gohmancecc80f2009-02-14 02:31:09 +0000465/// TestOrigIVForWrap - Analyze the original induction variable
466/// in the loop to determine whether it would ever undergo signed
467/// or unsigned overflow.
Dan Gohmancacd2012009-02-12 22:19:27 +0000468///
469/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohmancecc80f2009-02-14 02:31:09 +0000470/// Perhaps this can be merged with ScalarEvolution::getIterationCount
471/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmancacd2012009-02-12 22:19:27 +0000472///
Dan Gohmancecc80f2009-02-14 02:31:09 +0000473static void TestOrigIVForWrap(const Loop *L,
474 const BranchInst *BI,
475 const Instruction *OrigCond,
476 bool &NoSignedWrap,
477 bool &NoUnsignedWrap) {
Dan Gohmancacd2012009-02-12 22:19:27 +0000478 // Verify that the loop is sane and find the exit condition.
479 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000480 if (!Cmp) return;
Dan Gohmancacd2012009-02-12 22:19:27 +0000481
Dan Gohmancecc80f2009-02-14 02:31:09 +0000482 const Value *CmpLHS = Cmp->getOperand(0);
483 const Value *CmpRHS = Cmp->getOperand(1);
484 const BasicBlock *TrueBB = BI->getSuccessor(0);
485 const BasicBlock *FalseBB = BI->getSuccessor(1);
486 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmancacd2012009-02-12 22:19:27 +0000487
Dan Gohmancecc80f2009-02-14 02:31:09 +0000488 // Canonicalize a constant to the RHS.
489 if (isa<ConstantInt>(CmpLHS)) {
490 Pred = ICmpInst::getSwappedPredicate(Pred);
491 std::swap(CmpLHS, CmpRHS);
492 }
493 // Canonicalize SLE to SLT.
494 if (Pred == ICmpInst::ICMP_SLE)
495 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
496 if (!CI->getValue().isMaxSignedValue()) {
497 CmpRHS = ConstantInt::get(CI->getValue() + 1);
498 Pred = ICmpInst::ICMP_SLT;
499 }
500 // Canonicalize SGT to SGE.
501 if (Pred == ICmpInst::ICMP_SGT)
502 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
503 if (!CI->getValue().isMaxSignedValue()) {
504 CmpRHS = ConstantInt::get(CI->getValue() + 1);
505 Pred = ICmpInst::ICMP_SGE;
506 }
507 // Canonicalize SGE to SLT.
508 if (Pred == ICmpInst::ICMP_SGE) {
509 std::swap(TrueBB, FalseBB);
510 Pred = ICmpInst::ICMP_SLT;
511 }
512 // Canonicalize ULE to ULT.
513 if (Pred == ICmpInst::ICMP_ULE)
514 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
515 if (!CI->getValue().isMaxValue()) {
516 CmpRHS = ConstantInt::get(CI->getValue() + 1);
517 Pred = ICmpInst::ICMP_ULT;
518 }
519 // Canonicalize UGT to UGE.
520 if (Pred == ICmpInst::ICMP_UGT)
521 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
522 if (!CI->getValue().isMaxValue()) {
523 CmpRHS = ConstantInt::get(CI->getValue() + 1);
524 Pred = ICmpInst::ICMP_UGE;
525 }
526 // Canonicalize UGE to ULT.
527 if (Pred == ICmpInst::ICMP_UGE) {
528 std::swap(TrueBB, FalseBB);
529 Pred = ICmpInst::ICMP_ULT;
530 }
531 // For now, analyze only LT loops for signed overflow.
532 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
533 return;
534
535 bool isSigned = Pred == ICmpInst::ICMP_SLT;
536
537 // Get the increment instruction. Look past casts if we will
Dan Gohmancacd2012009-02-12 22:19:27 +0000538 // be able to prove that the original induction variable doesn't
Dan Gohmancecc80f2009-02-14 02:31:09 +0000539 // undergo signed or unsigned overflow, respectively.
540 const Value *IncrVal = CmpLHS;
541 if (isSigned) {
542 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
543 if (!isa<ConstantInt>(CmpRHS) ||
544 !cast<ConstantInt>(CmpRHS)->getValue()
545 .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
546 return;
547 IncrVal = SI->getOperand(0);
548 }
549 } else {
550 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
551 if (!isa<ConstantInt>(CmpRHS) ||
552 !cast<ConstantInt>(CmpRHS)->getValue()
553 .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
554 return;
555 IncrVal = ZI->getOperand(0);
556 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000557 }
558
559 // For now, only analyze induction variables that have simple increments.
560 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
561 if (!IncrOp ||
562 IncrOp->getOpcode() != Instruction::Add ||
563 !isa<ConstantInt>(IncrOp->getOperand(1)) ||
564 !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
Dan Gohmancecc80f2009-02-14 02:31:09 +0000565 return;
Dan Gohmancacd2012009-02-12 22:19:27 +0000566
567 // Make sure the PHI looks like a normal IV.
568 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
569 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmancecc80f2009-02-14 02:31:09 +0000570 return;
Dan Gohmancacd2012009-02-12 22:19:27 +0000571 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
572 unsigned BackEdge = !IncomingEdge;
573 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
574 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmancecc80f2009-02-14 02:31:09 +0000575 return;
576 if (!L->contains(TrueBB))
577 return;
Dan Gohmancacd2012009-02-12 22:19:27 +0000578
579 // For now, only analyze loops with a constant start value, so that
Dan Gohmancecc80f2009-02-14 02:31:09 +0000580 // we can easily determine if the start value is not a maximum value
581 // which would wrap on the first iteration.
Dan Gohmancacd2012009-02-12 22:19:27 +0000582 const Value *InitialVal = PN->getIncomingValue(IncomingEdge);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000583 if (!isa<ConstantInt>(InitialVal))
584 return;
Dan Gohmancacd2012009-02-12 22:19:27 +0000585
Dan Gohmancecc80f2009-02-14 02:31:09 +0000586 // The original induction variable will start at some non-max value,
587 // it counts up by one, and the loop iterates only while it remans
588 // less than some value in the same type. As such, it will never wrap.
589 if (isSigned &&
590 !cast<ConstantInt>(InitialVal)->getValue().isMaxSignedValue())
591 NoSignedWrap = true;
592 else if (!isSigned &&
593 !cast<ConstantInt>(InitialVal)->getValue().isMaxValue())
594 NoUnsignedWrap = true;
Dan Gohmancacd2012009-02-12 22:19:27 +0000595}
596
597bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000598 LI = &getAnalysis<LoopInfo>();
599 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600 Changed = false;
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000601
602 // If there are any floating-point or pointer recurrences, attempt to
603 // transform them to use integer recurrences.
604 RewriteNonIntegerIVs(L);
605
Dan Gohmancacd2012009-02-12 22:19:27 +0000606 BasicBlock *Header = L->getHeader();
607 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000608 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmancacd2012009-02-12 22:19:27 +0000609
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610 // Verify the input to the pass in already in LCSSA form.
611 assert(L->isLCSSAForm());
612
613 // Check to see if this loop has a computable loop-invariant execution count.
614 // If so, this means that we can compute the final value of any expressions
615 // that are recurrent in the loop, and substitute the exit values from the
616 // loop into any instructions outside of the loop that use the final values of
617 // the current expressions.
618 //
619 SCEVHandle IterationCount = SE->getIterationCount(L);
620 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000621 RewriteLoopExitValues(L, IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622
623 // Next, analyze all of the induction variables in the loop, canonicalizing
624 // auxillary induction variables.
625 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
626
627 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
628 PHINode *PN = cast<PHINode>(I);
629 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
630 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohman173d9142009-02-14 02:25:19 +0000631 // FIXME: It is an extremely bad idea to indvar substitute anything more
632 // complex than affine induction variables. Doing so will put expensive
633 // polynomial evaluations inside of the loop, and the str reduction pass
634 // currently can only reduce affine polynomials. For now just disable
635 // indvar subst on anything more complex than an affine addrec.
636 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
637 if (AR->getLoop() == L && AR->isAffine())
638 IndVars.push_back(std::make_pair(PN, SCEV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639 }
640 }
641
Dan Gohmancacd2012009-02-12 22:19:27 +0000642 // Compute the type of the largest recurrence expression, and collect
643 // the set of the types of the other recurrence expressions.
644 const Type *LargestType = 0;
645 SmallSetVector<const Type *, 4> SizesToInsert;
646 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
647 LargestType = IterationCount->getType();
648 SizesToInsert.insert(IterationCount->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000649 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000650 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
651 const PHINode *PN = IndVars[i].first;
652 SizesToInsert.insert(PN->getType());
653 const Type *EffTy = getEffectiveIndvarType(PN);
654 SizesToInsert.insert(EffTy);
655 if (!LargestType ||
656 EffTy->getPrimitiveSizeInBits() >
657 LargestType->getPrimitiveSizeInBits())
658 LargestType = EffTy;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659 }
660
661 // Create a rewriter object which we'll use to transform the code with.
662 SCEVExpander Rewriter(*SE, *LI);
663
664 // Now that we know the largest of of the induction variables in this loop,
665 // insert a canonical induction variable of the largest size.
Dan Gohmancacd2012009-02-12 22:19:27 +0000666 Value *IndVar = 0;
667 if (!SizesToInsert.empty()) {
668 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
669 ++NumInserted;
670 Changed = true;
671 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000672 }
673
Dan Gohmancacd2012009-02-12 22:19:27 +0000674 // If we have a trip count expression, rewrite the loop's exit condition
675 // using it. We can currently only handle loops with a single exit.
Dan Gohmancecc80f2009-02-14 02:31:09 +0000676 bool NoSignedWrap = false;
677 bool NoUnsignedWrap = false;
Dan Gohmancacd2012009-02-12 22:19:27 +0000678 if (!isa<SCEVCouldNotCompute>(IterationCount) && ExitingBlock)
679 // Can't rewrite non-branch yet.
680 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
681 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmancecc80f2009-02-14 02:31:09 +0000682 // Determine if the OrigIV will ever undergo overflow.
683 TestOrigIVForWrap(L, BI, OrigCond,
684 NoSignedWrap, NoUnsignedWrap);
Dan Gohmancacd2012009-02-12 22:19:27 +0000685
686 // We'll be replacing the original condition, so it'll be dead.
687 DeadInsts.insert(OrigCond);
688 }
689
690 LinearFunctionTestReplace(L, IterationCount, IndVar,
691 ExitingBlock, BI, Rewriter);
692 }
693
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 // Now that we have a canonical induction variable, we can rewrite any
695 // recurrences in terms of the induction variable. Start with the auxillary
696 // induction variables, and recursively rewrite any of their uses.
Dan Gohman514277c2008-05-23 21:05:58 +0000697 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698
699 // If there were induction variables of other sizes, cast the primary
700 // induction variable to the right size for them, avoiding the need for the
701 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmancacd2012009-02-12 22:19:27 +0000702 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
703 const Type *Ty = SizesToInsert[i];
704 if (Ty != LargestType) {
705 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
706 Rewriter.addInsertedValue(New, SE->getSCEV(New));
707 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
708 << *New << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709 }
710 }
711
712 // Rewrite all induction variables in terms of the canonical induction
713 // variable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 while (!IndVars.empty()) {
715 PHINode *PN = IndVars.back().first;
Dan Gohmanc71cac12009-02-17 00:10:53 +0000716 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
717 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
718 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719 << " into = " << *NewVal << "\n";
720 NewVal->takeName(PN);
721
Dan Gohmancacd2012009-02-12 22:19:27 +0000722 /// If the new canonical induction variable is wider than the original,
723 /// and the original has uses that are casts to wider types, see if the
724 /// truncate and extend can be omitted.
Dan Gohmancecc80f2009-02-14 02:31:09 +0000725 if (PN->getType() != LargestType)
Dan Gohmancacd2012009-02-12 22:19:27 +0000726 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmancecc80f2009-02-14 02:31:09 +0000727 UI != UE; ++UI) {
728 if (isa<SExtInst>(UI) && NoSignedWrap) {
729 SCEVHandle ExtendedStart =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000730 SE->getSignExtendExpr(AR->getStart(), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000731 SCEVHandle ExtendedStep =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000732 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000733 SCEVHandle ExtendedAddRec =
734 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
735 if (LargestType != UI->getType())
736 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
737 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
Dan Gohmancacd2012009-02-12 22:19:27 +0000738 UI->replaceAllUsesWith(TruncIndVar);
739 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
740 DeadInsts.insert(DeadUse);
741 }
Dan Gohmancecc80f2009-02-14 02:31:09 +0000742 if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
743 SCEVHandle ExtendedStart =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000744 SE->getZeroExtendExpr(AR->getStart(), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000745 SCEVHandle ExtendedStep =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000746 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000747 SCEVHandle ExtendedAddRec =
748 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
749 if (LargestType != UI->getType())
750 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
751 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
752 UI->replaceAllUsesWith(TruncIndVar);
753 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
754 DeadInsts.insert(DeadUse);
755 }
756 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000757
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 // Replace the old PHI Node with the inserted computation.
759 PN->replaceAllUsesWith(NewVal);
760 DeadInsts.insert(PN);
761 IndVars.pop_back();
762 ++NumRemoved;
763 Changed = true;
764 }
765
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766 DeleteTriviallyDeadInstructions(DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 assert(L->isLCSSAForm());
768 return Changed;
769}
Devang Patelbda43802008-09-09 21:41:07 +0000770
Devang Patelb8ccf572008-11-18 00:40:02 +0000771/// Return true if it is OK to use SIToFPInst for an inducation variable
772/// with given inital and exit values.
773static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
774 uint64_t intIV, uint64_t intEV) {
775
Dan Gohman963fc812009-02-17 19:13:57 +0000776 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patelb8ccf572008-11-18 00:40:02 +0000777 return true;
778
779 // If the iteration range can be handled by SIToFPInst then use it.
780 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendlingb9a5a682008-11-18 10:57:27 +0000781 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patelb8ccf572008-11-18 00:40:02 +0000782 return true;
Dan Gohman963fc812009-02-17 19:13:57 +0000783
Devang Patelb8ccf572008-11-18 00:40:02 +0000784 return false;
785}
786
787/// convertToInt - Convert APF to an integer, if possible.
Devang Patele2ba01d2008-11-17 23:27:13 +0000788static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
789
790 bool isExact = false;
Evan Cheng30e65f62008-11-26 01:11:57 +0000791 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
792 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000793 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patele2ba01d2008-11-17 23:27:13 +0000794 APFloat::rmTowardZero, &isExact)
795 != APFloat::opOK)
796 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000797 if (!isExact)
Devang Patele2ba01d2008-11-17 23:27:13 +0000798 return false;
799 return true;
800
801}
802
Devang Patel7ca23c92008-11-03 18:32:19 +0000803/// HandleFloatingPointIV - If the loop has floating induction variable
804/// then insert corresponding integer induction variable if possible.
Devang Patelc8dac622008-11-17 21:32:02 +0000805/// For example,
806/// for(double i = 0; i < 10000; ++i)
807/// bar(i)
808/// is converted into
809/// for(int i = 0; i < 10000; ++i)
810/// bar((double)i);
811///
Dan Gohman963fc812009-02-17 19:13:57 +0000812void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patelc8dac622008-11-17 21:32:02 +0000813 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel7ca23c92008-11-03 18:32:19 +0000814
Devang Patelc8dac622008-11-17 21:32:02 +0000815 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
816 unsigned BackEdge = IncomingEdge^1;
Dan Gohman963fc812009-02-17 19:13:57 +0000817
Devang Patelc8dac622008-11-17 21:32:02 +0000818 // Check incoming value.
Devang Patele2ba01d2008-11-17 23:27:13 +0000819 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
820 if (!InitValue) return;
821 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
822 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
823 return;
824
825 // Check IV increment. Reject this PH if increement operation is not
826 // an add or increment value can not be represented by an integer.
Dan Gohman963fc812009-02-17 19:13:57 +0000827 BinaryOperator *Incr =
Devang Patelc8dac622008-11-17 21:32:02 +0000828 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
829 if (!Incr) return;
830 if (Incr->getOpcode() != Instruction::Add) return;
831 ConstantFP *IncrValue = NULL;
832 unsigned IncrVIndex = 1;
833 if (Incr->getOperand(1) == PH)
834 IncrVIndex = 0;
835 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
836 if (!IncrValue) return;
Devang Patele2ba01d2008-11-17 23:27:13 +0000837 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
838 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
839 return;
Dan Gohman963fc812009-02-17 19:13:57 +0000840
Devang Patele2ba01d2008-11-17 23:27:13 +0000841 // Check Incr uses. One user is PH and the other users is exit condition used
842 // by the conditional terminator.
Devang Patelc8dac622008-11-17 21:32:02 +0000843 Value::use_iterator IncrUse = Incr->use_begin();
844 Instruction *U1 = cast<Instruction>(IncrUse++);
845 if (IncrUse == Incr->use_end()) return;
846 Instruction *U2 = cast<Instruction>(IncrUse++);
847 if (IncrUse != Incr->use_end()) return;
Dan Gohman963fc812009-02-17 19:13:57 +0000848
Devang Patelc8dac622008-11-17 21:32:02 +0000849 // Find exit condition.
850 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
851 if (!EC)
852 EC = dyn_cast<FCmpInst>(U2);
853 if (!EC) return;
854
855 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
856 if (!BI->isConditional()) return;
857 if (BI->getCondition() != EC) return;
Devang Patel7ca23c92008-11-03 18:32:19 +0000858 }
Devang Patel7ca23c92008-11-03 18:32:19 +0000859
Devang Patele2ba01d2008-11-17 23:27:13 +0000860 // Find exit value. If exit value can not be represented as an interger then
861 // do not handle this floating point PH.
Devang Patelc8dac622008-11-17 21:32:02 +0000862 ConstantFP *EV = NULL;
863 unsigned EVIndex = 1;
864 if (EC->getOperand(1) == Incr)
865 EVIndex = 0;
866 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
867 if (!EV) return;
Devang Patelc8dac622008-11-17 21:32:02 +0000868 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patele2ba01d2008-11-17 23:27:13 +0000869 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patelc8dac622008-11-17 21:32:02 +0000870 return;
Dan Gohman963fc812009-02-17 19:13:57 +0000871
Devang Patelc8dac622008-11-17 21:32:02 +0000872 // Find new predicate for integer comparison.
873 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
874 switch (EC->getPredicate()) {
875 case CmpInst::FCMP_OEQ:
876 case CmpInst::FCMP_UEQ:
877 NewPred = CmpInst::ICMP_EQ;
878 break;
879 case CmpInst::FCMP_OGT:
880 case CmpInst::FCMP_UGT:
881 NewPred = CmpInst::ICMP_UGT;
882 break;
883 case CmpInst::FCMP_OGE:
884 case CmpInst::FCMP_UGE:
885 NewPred = CmpInst::ICMP_UGE;
886 break;
887 case CmpInst::FCMP_OLT:
888 case CmpInst::FCMP_ULT:
889 NewPred = CmpInst::ICMP_ULT;
890 break;
891 case CmpInst::FCMP_OLE:
892 case CmpInst::FCMP_ULE:
893 NewPred = CmpInst::ICMP_ULE;
894 break;
895 default:
896 break;
Devang Patel7ca23c92008-11-03 18:32:19 +0000897 }
Devang Patelc8dac622008-11-17 21:32:02 +0000898 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohman963fc812009-02-17 19:13:57 +0000899
Devang Patelc8dac622008-11-17 21:32:02 +0000900 // Insert new integer induction variable.
901 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
902 PH->getName()+".int", PH);
Devang Patele2ba01d2008-11-17 23:27:13 +0000903 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000904 PH->getIncomingBlock(IncomingEdge));
905
Dan Gohman963fc812009-02-17 19:13:57 +0000906 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
907 ConstantInt::get(Type::Int32Ty,
Devang Patele2ba01d2008-11-17 23:27:13 +0000908 newIncrValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000909 Incr->getName()+".int", Incr);
910 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
911
912 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
913 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
914 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
Dan Gohman963fc812009-02-17 19:13:57 +0000915 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patelc8dac622008-11-17 21:32:02 +0000916 EC->getParent()->getTerminator());
Dan Gohman963fc812009-02-17 19:13:57 +0000917
Devang Patelc8dac622008-11-17 21:32:02 +0000918 // Delete old, floating point, exit comparision instruction.
919 EC->replaceAllUsesWith(NewEC);
920 DeadInsts.insert(EC);
Dan Gohman963fc812009-02-17 19:13:57 +0000921
Devang Patelc8dac622008-11-17 21:32:02 +0000922 // Delete old, floating point, increment instruction.
923 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
924 DeadInsts.insert(Incr);
Dan Gohman963fc812009-02-17 19:13:57 +0000925
Devang Patelb8ccf572008-11-18 00:40:02 +0000926 // Replace floating induction variable. Give SIToFPInst preference over
927 // UIToFPInst because it is faster on platforms that are widely used.
928 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Dan Gohman963fc812009-02-17 19:13:57 +0000929 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patele2ba01d2008-11-17 23:27:13 +0000930 PH->getParent()->getFirstNonPHI());
931 PH->replaceAllUsesWith(Conv);
932 } else {
Dan Gohman963fc812009-02-17 19:13:57 +0000933 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patele2ba01d2008-11-17 23:27:13 +0000934 PH->getParent()->getFirstNonPHI());
935 PH->replaceAllUsesWith(Conv);
936 }
Devang Patelc8dac622008-11-17 21:32:02 +0000937 DeadInsts.insert(PH);
Devang Patel7ca23c92008-11-03 18:32:19 +0000938}
939