blob: c496c57836f37af7b546b0391ca27999fc3b56b9 [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
Dan Gohmana730da32009-02-18 00:52:00 +0000466/// that controls the loop's iteration to determine whether it
467/// would ever undergo signed or unsigned overflow.
468///
469/// In addition to setting the NoSignedWrap and NoUnsignedWrap
470/// variables, return the PHI for this induction variable.
Dan Gohmancacd2012009-02-12 22:19:27 +0000471///
472/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohmancecc80f2009-02-14 02:31:09 +0000473/// Perhaps this can be merged with ScalarEvolution::getIterationCount
474/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmancacd2012009-02-12 22:19:27 +0000475///
Dan Gohmana730da32009-02-18 00:52:00 +0000476static const PHINode *TestOrigIVForWrap(const Loop *L,
477 const BranchInst *BI,
478 const Instruction *OrigCond,
479 bool &NoSignedWrap,
480 bool &NoUnsignedWrap) {
Dan Gohmancacd2012009-02-12 22:19:27 +0000481 // Verify that the loop is sane and find the exit condition.
482 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmana730da32009-02-18 00:52:00 +0000483 if (!Cmp) return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000484
Dan Gohmancecc80f2009-02-14 02:31:09 +0000485 const Value *CmpLHS = Cmp->getOperand(0);
486 const Value *CmpRHS = Cmp->getOperand(1);
487 const BasicBlock *TrueBB = BI->getSuccessor(0);
488 const BasicBlock *FalseBB = BI->getSuccessor(1);
489 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmancacd2012009-02-12 22:19:27 +0000490
Dan Gohmancecc80f2009-02-14 02:31:09 +0000491 // Canonicalize a constant to the RHS.
492 if (isa<ConstantInt>(CmpLHS)) {
493 Pred = ICmpInst::getSwappedPredicate(Pred);
494 std::swap(CmpLHS, CmpRHS);
495 }
496 // Canonicalize SLE to SLT.
497 if (Pred == ICmpInst::ICMP_SLE)
498 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
499 if (!CI->getValue().isMaxSignedValue()) {
500 CmpRHS = ConstantInt::get(CI->getValue() + 1);
501 Pred = ICmpInst::ICMP_SLT;
502 }
503 // Canonicalize SGT to SGE.
504 if (Pred == ICmpInst::ICMP_SGT)
505 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
506 if (!CI->getValue().isMaxSignedValue()) {
507 CmpRHS = ConstantInt::get(CI->getValue() + 1);
508 Pred = ICmpInst::ICMP_SGE;
509 }
510 // Canonicalize SGE to SLT.
511 if (Pred == ICmpInst::ICMP_SGE) {
512 std::swap(TrueBB, FalseBB);
513 Pred = ICmpInst::ICMP_SLT;
514 }
515 // Canonicalize ULE to ULT.
516 if (Pred == ICmpInst::ICMP_ULE)
517 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
518 if (!CI->getValue().isMaxValue()) {
519 CmpRHS = ConstantInt::get(CI->getValue() + 1);
520 Pred = ICmpInst::ICMP_ULT;
521 }
522 // Canonicalize UGT to UGE.
523 if (Pred == ICmpInst::ICMP_UGT)
524 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
525 if (!CI->getValue().isMaxValue()) {
526 CmpRHS = ConstantInt::get(CI->getValue() + 1);
527 Pred = ICmpInst::ICMP_UGE;
528 }
529 // Canonicalize UGE to ULT.
530 if (Pred == ICmpInst::ICMP_UGE) {
531 std::swap(TrueBB, FalseBB);
532 Pred = ICmpInst::ICMP_ULT;
533 }
534 // For now, analyze only LT loops for signed overflow.
535 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
Dan Gohmana730da32009-02-18 00:52:00 +0000536 return 0;
Dan Gohmancecc80f2009-02-14 02:31:09 +0000537
538 bool isSigned = Pred == ICmpInst::ICMP_SLT;
539
540 // Get the increment instruction. Look past casts if we will
Dan Gohmancacd2012009-02-12 22:19:27 +0000541 // be able to prove that the original induction variable doesn't
Dan Gohmancecc80f2009-02-14 02:31:09 +0000542 // undergo signed or unsigned overflow, respectively.
543 const Value *IncrVal = CmpLHS;
544 if (isSigned) {
545 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
546 if (!isa<ConstantInt>(CmpRHS) ||
547 !cast<ConstantInt>(CmpRHS)->getValue()
548 .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
Dan Gohmana730da32009-02-18 00:52:00 +0000549 return 0;
Dan Gohmancecc80f2009-02-14 02:31:09 +0000550 IncrVal = SI->getOperand(0);
551 }
552 } else {
553 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
554 if (!isa<ConstantInt>(CmpRHS) ||
555 !cast<ConstantInt>(CmpRHS)->getValue()
556 .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
Dan Gohmana730da32009-02-18 00:52:00 +0000557 return 0;
Dan Gohmancecc80f2009-02-14 02:31:09 +0000558 IncrVal = ZI->getOperand(0);
559 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000560 }
561
562 // For now, only analyze induction variables that have simple increments.
563 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
564 if (!IncrOp ||
565 IncrOp->getOpcode() != Instruction::Add ||
566 !isa<ConstantInt>(IncrOp->getOperand(1)) ||
567 !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
Dan Gohmana730da32009-02-18 00:52:00 +0000568 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000569
570 // Make sure the PHI looks like a normal IV.
571 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
572 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmana730da32009-02-18 00:52:00 +0000573 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000574 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
575 unsigned BackEdge = !IncomingEdge;
576 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
577 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmana730da32009-02-18 00:52:00 +0000578 return 0;
Dan Gohmancecc80f2009-02-14 02:31:09 +0000579 if (!L->contains(TrueBB))
Dan Gohmana730da32009-02-18 00:52:00 +0000580 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000581
582 // For now, only analyze loops with a constant start value, so that
Dan Gohmancecc80f2009-02-14 02:31:09 +0000583 // we can easily determine if the start value is not a maximum value
584 // which would wrap on the first iteration.
Dan Gohmancacd2012009-02-12 22:19:27 +0000585 const Value *InitialVal = PN->getIncomingValue(IncomingEdge);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000586 if (!isa<ConstantInt>(InitialVal))
Dan Gohmana730da32009-02-18 00:52:00 +0000587 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000588
Dan Gohmancecc80f2009-02-14 02:31:09 +0000589 // The original induction variable will start at some non-max value,
590 // it counts up by one, and the loop iterates only while it remans
591 // less than some value in the same type. As such, it will never wrap.
592 if (isSigned &&
593 !cast<ConstantInt>(InitialVal)->getValue().isMaxSignedValue())
594 NoSignedWrap = true;
595 else if (!isSigned &&
596 !cast<ConstantInt>(InitialVal)->getValue().isMaxValue())
597 NoUnsignedWrap = true;
Dan Gohmana730da32009-02-18 00:52:00 +0000598 return PN;
Dan Gohmancacd2012009-02-12 22:19:27 +0000599}
600
601bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 LI = &getAnalysis<LoopInfo>();
603 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 Changed = false;
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000605
606 // If there are any floating-point or pointer recurrences, attempt to
607 // transform them to use integer recurrences.
608 RewriteNonIntegerIVs(L);
609
Dan Gohmancacd2012009-02-12 22:19:27 +0000610 BasicBlock *Header = L->getHeader();
611 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000612 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmancacd2012009-02-12 22:19:27 +0000613
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614 // Verify the input to the pass in already in LCSSA form.
615 assert(L->isLCSSAForm());
616
617 // Check to see if this loop has a computable loop-invariant execution count.
618 // If so, this means that we can compute the final value of any expressions
619 // that are recurrent in the loop, and substitute the exit values from the
620 // loop into any instructions outside of the loop that use the final values of
621 // the current expressions.
622 //
623 SCEVHandle IterationCount = SE->getIterationCount(L);
624 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000625 RewriteLoopExitValues(L, IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626
627 // Next, analyze all of the induction variables in the loop, canonicalizing
628 // auxillary induction variables.
629 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
630
631 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
632 PHINode *PN = cast<PHINode>(I);
633 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
634 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohman173d9142009-02-14 02:25:19 +0000635 // FIXME: It is an extremely bad idea to indvar substitute anything more
636 // complex than affine induction variables. Doing so will put expensive
637 // polynomial evaluations inside of the loop, and the str reduction pass
638 // currently can only reduce affine polynomials. For now just disable
639 // indvar subst on anything more complex than an affine addrec.
640 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
641 if (AR->getLoop() == L && AR->isAffine())
642 IndVars.push_back(std::make_pair(PN, SCEV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643 }
644 }
645
Dan Gohmancacd2012009-02-12 22:19:27 +0000646 // Compute the type of the largest recurrence expression, and collect
647 // the set of the types of the other recurrence expressions.
648 const Type *LargestType = 0;
649 SmallSetVector<const Type *, 4> SizesToInsert;
650 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
651 LargestType = IterationCount->getType();
652 SizesToInsert.insert(IterationCount->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000654 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
655 const PHINode *PN = IndVars[i].first;
656 SizesToInsert.insert(PN->getType());
657 const Type *EffTy = getEffectiveIndvarType(PN);
658 SizesToInsert.insert(EffTy);
659 if (!LargestType ||
660 EffTy->getPrimitiveSizeInBits() >
661 LargestType->getPrimitiveSizeInBits())
662 LargestType = EffTy;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663 }
664
665 // Create a rewriter object which we'll use to transform the code with.
666 SCEVExpander Rewriter(*SE, *LI);
667
668 // Now that we know the largest of of the induction variables in this loop,
669 // insert a canonical induction variable of the largest size.
Dan Gohmancacd2012009-02-12 22:19:27 +0000670 Value *IndVar = 0;
671 if (!SizesToInsert.empty()) {
672 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
673 ++NumInserted;
674 Changed = true;
675 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676 }
677
Dan Gohmancacd2012009-02-12 22:19:27 +0000678 // If we have a trip count expression, rewrite the loop's exit condition
679 // using it. We can currently only handle loops with a single exit.
Dan Gohmancecc80f2009-02-14 02:31:09 +0000680 bool NoSignedWrap = false;
681 bool NoUnsignedWrap = false;
Dan Gohmana730da32009-02-18 00:52:00 +0000682 const PHINode *OrigControllingPHI = 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000683 if (!isa<SCEVCouldNotCompute>(IterationCount) && ExitingBlock)
684 // Can't rewrite non-branch yet.
685 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
686 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmancecc80f2009-02-14 02:31:09 +0000687 // Determine if the OrigIV will ever undergo overflow.
Dan Gohmana730da32009-02-18 00:52:00 +0000688 OrigControllingPHI =
689 TestOrigIVForWrap(L, BI, OrigCond,
690 NoSignedWrap, NoUnsignedWrap);
Dan Gohmancacd2012009-02-12 22:19:27 +0000691
692 // We'll be replacing the original condition, so it'll be dead.
693 DeadInsts.insert(OrigCond);
694 }
695
696 LinearFunctionTestReplace(L, IterationCount, IndVar,
697 ExitingBlock, BI, Rewriter);
698 }
699
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 // Now that we have a canonical induction variable, we can rewrite any
701 // recurrences in terms of the induction variable. Start with the auxillary
702 // induction variables, and recursively rewrite any of their uses.
Dan Gohman514277c2008-05-23 21:05:58 +0000703 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704
705 // If there were induction variables of other sizes, cast the primary
706 // induction variable to the right size for them, avoiding the need for the
707 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmancacd2012009-02-12 22:19:27 +0000708 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
709 const Type *Ty = SizesToInsert[i];
710 if (Ty != LargestType) {
711 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
712 Rewriter.addInsertedValue(New, SE->getSCEV(New));
713 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
714 << *New << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 }
716 }
717
718 // Rewrite all induction variables in terms of the canonical induction
719 // variable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 while (!IndVars.empty()) {
721 PHINode *PN = IndVars.back().first;
Dan Gohmanc71cac12009-02-17 00:10:53 +0000722 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
723 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
724 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 << " into = " << *NewVal << "\n";
726 NewVal->takeName(PN);
727
Dan Gohmancacd2012009-02-12 22:19:27 +0000728 /// If the new canonical induction variable is wider than the original,
729 /// and the original has uses that are casts to wider types, see if the
730 /// truncate and extend can be omitted.
Dan Gohmana730da32009-02-18 00:52:00 +0000731 if (PN == OrigControllingPHI && PN->getType() != LargestType)
Dan Gohmancacd2012009-02-12 22:19:27 +0000732 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmancecc80f2009-02-14 02:31:09 +0000733 UI != UE; ++UI) {
734 if (isa<SExtInst>(UI) && NoSignedWrap) {
735 SCEVHandle ExtendedStart =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000736 SE->getSignExtendExpr(AR->getStart(), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000737 SCEVHandle ExtendedStep =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000738 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000739 SCEVHandle ExtendedAddRec =
740 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
741 if (LargestType != UI->getType())
742 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
743 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
Dan Gohmancacd2012009-02-12 22:19:27 +0000744 UI->replaceAllUsesWith(TruncIndVar);
745 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
746 DeadInsts.insert(DeadUse);
747 }
Dan Gohmancecc80f2009-02-14 02:31:09 +0000748 if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
749 SCEVHandle ExtendedStart =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000750 SE->getZeroExtendExpr(AR->getStart(), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000751 SCEVHandle ExtendedStep =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000752 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000753 SCEVHandle ExtendedAddRec =
754 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
755 if (LargestType != UI->getType())
756 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
757 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
758 UI->replaceAllUsesWith(TruncIndVar);
759 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
760 DeadInsts.insert(DeadUse);
761 }
762 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000763
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000764 // Replace the old PHI Node with the inserted computation.
765 PN->replaceAllUsesWith(NewVal);
766 DeadInsts.insert(PN);
767 IndVars.pop_back();
768 ++NumRemoved;
769 Changed = true;
770 }
771
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 DeleteTriviallyDeadInstructions(DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 assert(L->isLCSSAForm());
774 return Changed;
775}
Devang Patelbda43802008-09-09 21:41:07 +0000776
Devang Patelb8ccf572008-11-18 00:40:02 +0000777/// Return true if it is OK to use SIToFPInst for an inducation variable
778/// with given inital and exit values.
779static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
780 uint64_t intIV, uint64_t intEV) {
781
Dan Gohman963fc812009-02-17 19:13:57 +0000782 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patelb8ccf572008-11-18 00:40:02 +0000783 return true;
784
785 // If the iteration range can be handled by SIToFPInst then use it.
786 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendlingb9a5a682008-11-18 10:57:27 +0000787 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patelb8ccf572008-11-18 00:40:02 +0000788 return true;
Dan Gohman963fc812009-02-17 19:13:57 +0000789
Devang Patelb8ccf572008-11-18 00:40:02 +0000790 return false;
791}
792
793/// convertToInt - Convert APF to an integer, if possible.
Devang Patele2ba01d2008-11-17 23:27:13 +0000794static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
795
796 bool isExact = false;
Evan Cheng30e65f62008-11-26 01:11:57 +0000797 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
798 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000799 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patele2ba01d2008-11-17 23:27:13 +0000800 APFloat::rmTowardZero, &isExact)
801 != APFloat::opOK)
802 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000803 if (!isExact)
Devang Patele2ba01d2008-11-17 23:27:13 +0000804 return false;
805 return true;
806
807}
808
Devang Patel7ca23c92008-11-03 18:32:19 +0000809/// HandleFloatingPointIV - If the loop has floating induction variable
810/// then insert corresponding integer induction variable if possible.
Devang Patelc8dac622008-11-17 21:32:02 +0000811/// For example,
812/// for(double i = 0; i < 10000; ++i)
813/// bar(i)
814/// is converted into
815/// for(int i = 0; i < 10000; ++i)
816/// bar((double)i);
817///
Dan Gohman963fc812009-02-17 19:13:57 +0000818void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patelc8dac622008-11-17 21:32:02 +0000819 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel7ca23c92008-11-03 18:32:19 +0000820
Devang Patelc8dac622008-11-17 21:32:02 +0000821 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
822 unsigned BackEdge = IncomingEdge^1;
Dan Gohman963fc812009-02-17 19:13:57 +0000823
Devang Patelc8dac622008-11-17 21:32:02 +0000824 // Check incoming value.
Devang Patele2ba01d2008-11-17 23:27:13 +0000825 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
826 if (!InitValue) return;
827 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
828 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
829 return;
830
831 // Check IV increment. Reject this PH if increement operation is not
832 // an add or increment value can not be represented by an integer.
Dan Gohman963fc812009-02-17 19:13:57 +0000833 BinaryOperator *Incr =
Devang Patelc8dac622008-11-17 21:32:02 +0000834 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
835 if (!Incr) return;
836 if (Incr->getOpcode() != Instruction::Add) return;
837 ConstantFP *IncrValue = NULL;
838 unsigned IncrVIndex = 1;
839 if (Incr->getOperand(1) == PH)
840 IncrVIndex = 0;
841 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
842 if (!IncrValue) return;
Devang Patele2ba01d2008-11-17 23:27:13 +0000843 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
844 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
845 return;
Dan Gohman963fc812009-02-17 19:13:57 +0000846
Devang Patele2ba01d2008-11-17 23:27:13 +0000847 // Check Incr uses. One user is PH and the other users is exit condition used
848 // by the conditional terminator.
Devang Patelc8dac622008-11-17 21:32:02 +0000849 Value::use_iterator IncrUse = Incr->use_begin();
850 Instruction *U1 = cast<Instruction>(IncrUse++);
851 if (IncrUse == Incr->use_end()) return;
852 Instruction *U2 = cast<Instruction>(IncrUse++);
853 if (IncrUse != Incr->use_end()) return;
Dan Gohman963fc812009-02-17 19:13:57 +0000854
Devang Patelc8dac622008-11-17 21:32:02 +0000855 // Find exit condition.
856 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
857 if (!EC)
858 EC = dyn_cast<FCmpInst>(U2);
859 if (!EC) return;
860
861 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
862 if (!BI->isConditional()) return;
863 if (BI->getCondition() != EC) return;
Devang Patel7ca23c92008-11-03 18:32:19 +0000864 }
Devang Patel7ca23c92008-11-03 18:32:19 +0000865
Devang Patele2ba01d2008-11-17 23:27:13 +0000866 // Find exit value. If exit value can not be represented as an interger then
867 // do not handle this floating point PH.
Devang Patelc8dac622008-11-17 21:32:02 +0000868 ConstantFP *EV = NULL;
869 unsigned EVIndex = 1;
870 if (EC->getOperand(1) == Incr)
871 EVIndex = 0;
872 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
873 if (!EV) return;
Devang Patelc8dac622008-11-17 21:32:02 +0000874 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patele2ba01d2008-11-17 23:27:13 +0000875 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patelc8dac622008-11-17 21:32:02 +0000876 return;
Dan Gohman963fc812009-02-17 19:13:57 +0000877
Devang Patelc8dac622008-11-17 21:32:02 +0000878 // Find new predicate for integer comparison.
879 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
880 switch (EC->getPredicate()) {
881 case CmpInst::FCMP_OEQ:
882 case CmpInst::FCMP_UEQ:
883 NewPred = CmpInst::ICMP_EQ;
884 break;
885 case CmpInst::FCMP_OGT:
886 case CmpInst::FCMP_UGT:
887 NewPred = CmpInst::ICMP_UGT;
888 break;
889 case CmpInst::FCMP_OGE:
890 case CmpInst::FCMP_UGE:
891 NewPred = CmpInst::ICMP_UGE;
892 break;
893 case CmpInst::FCMP_OLT:
894 case CmpInst::FCMP_ULT:
895 NewPred = CmpInst::ICMP_ULT;
896 break;
897 case CmpInst::FCMP_OLE:
898 case CmpInst::FCMP_ULE:
899 NewPred = CmpInst::ICMP_ULE;
900 break;
901 default:
902 break;
Devang Patel7ca23c92008-11-03 18:32:19 +0000903 }
Devang Patelc8dac622008-11-17 21:32:02 +0000904 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohman963fc812009-02-17 19:13:57 +0000905
Devang Patelc8dac622008-11-17 21:32:02 +0000906 // Insert new integer induction variable.
907 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
908 PH->getName()+".int", PH);
Devang Patele2ba01d2008-11-17 23:27:13 +0000909 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000910 PH->getIncomingBlock(IncomingEdge));
911
Dan Gohman963fc812009-02-17 19:13:57 +0000912 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
913 ConstantInt::get(Type::Int32Ty,
Devang Patele2ba01d2008-11-17 23:27:13 +0000914 newIncrValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000915 Incr->getName()+".int", Incr);
916 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
917
918 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
919 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
920 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
Dan Gohman963fc812009-02-17 19:13:57 +0000921 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patelc8dac622008-11-17 21:32:02 +0000922 EC->getParent()->getTerminator());
Dan Gohman963fc812009-02-17 19:13:57 +0000923
Devang Patelc8dac622008-11-17 21:32:02 +0000924 // Delete old, floating point, exit comparision instruction.
925 EC->replaceAllUsesWith(NewEC);
926 DeadInsts.insert(EC);
Dan Gohman963fc812009-02-17 19:13:57 +0000927
Devang Patelc8dac622008-11-17 21:32:02 +0000928 // Delete old, floating point, increment instruction.
929 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
930 DeadInsts.insert(Incr);
Dan Gohman963fc812009-02-17 19:13:57 +0000931
Devang Patelb8ccf572008-11-18 00:40:02 +0000932 // Replace floating induction variable. Give SIToFPInst preference over
933 // UIToFPInst because it is faster on platforms that are widely used.
934 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Dan Gohman963fc812009-02-17 19:13:57 +0000935 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patele2ba01d2008-11-17 23:27:13 +0000936 PH->getParent()->getFirstNonPHI());
937 PH->replaceAllUsesWith(Conv);
938 } else {
Dan Gohman963fc812009-02-17 19:13:57 +0000939 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patele2ba01d2008-11-17 23:27:13 +0000940 PH->getParent()->getFirstNonPHI());
941 PH->replaceAllUsesWith(Conv);
942 }
Devang Patelc8dac622008-11-17 21:32:02 +0000943 DeadInsts.insert(PH);
Devang Patel7ca23c92008-11-03 18:32:19 +0000944}
945