blob: 3e9615c849a751c25b99597fce6613a7a0229438 [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,
Dan Gohmana5d38012009-02-18 17:22:41 +000099 SCEVExpander &Rewriter,
100 bool SignExtendTripCount);
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000101 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000102
Chris Lattnerb25465e2008-11-16 07:17:51 +0000103 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Patelbda43802008-09-09 21:41:07 +0000104
Dan Gohman963fc812009-02-17 19:13:57 +0000105 void HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patelc8dac622008-11-17 21:32:02 +0000106 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108}
109
Dan Gohman089efff2008-05-13 00:00:25 +0000110char IndVarSimplify::ID = 0;
111static RegisterPass<IndVarSimplify>
112X("indvars", "Canonicalize Induction Variables");
113
Daniel Dunbar163555a2008-10-22 23:32:42 +0000114Pass *llvm::createIndVarSimplifyPass() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115 return new IndVarSimplify();
116}
117
118/// DeleteTriviallyDeadInstructions - If any of the instructions is the
119/// specified set are trivially dead, delete them and see if this makes any of
120/// their operands subsequently dead.
121void IndVarSimplify::
Chris Lattnerb25465e2008-11-16 07:17:51 +0000122DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 while (!Insts.empty()) {
124 Instruction *I = *Insts.begin();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000125 Insts.erase(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126 if (isInstructionTriviallyDead(I)) {
127 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
128 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
129 Insts.insert(U);
130 SE->deleteValueFromRecords(I);
131 DOUT << "INDVARS: Deleting: " << *I;
132 I->eraseFromParent();
133 Changed = true;
134 }
135 }
136}
137
138
139/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
140/// recurrence. If so, change it into an integer recurrence, permitting
141/// analysis by the SCEV routines.
142void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
143 BasicBlock *Preheader,
Chris Lattnerb25465e2008-11-16 07:17:51 +0000144 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
146 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
147 unsigned BackedgeIdx = PreheaderIdx^1;
148 if (GetElementPtrInst *GEPI =
149 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
150 if (GEPI->getOperand(0) == PN) {
151 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
152 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
Dan Gohman963fc812009-02-17 19:13:57 +0000153
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154 // Okay, we found a pointer recurrence. Transform this pointer
155 // recurrence into an integer recurrence. Compute the value that gets
156 // added to the pointer at every iteration.
157 Value *AddedVal = GEPI->getOperand(1);
158
159 // Insert a new integer PHI node into the top of the block.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000160 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
161 PN->getName()+".rec", PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
163
164 // Create the new add instruction.
Gabor Greifa645dd32008-05-16 19:29:10 +0000165 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166 GEPI->getName()+".rec", GEPI);
167 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
168
169 // Update the existing GEP to use the recurrence.
170 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
171
172 // Update the GEP to use the new recurrence we just inserted.
173 GEPI->setOperand(1, NewAdd);
174
175 // If the incoming value is a constant expr GEP, try peeling out the array
176 // 0 index if possible to make things simpler.
177 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
178 if (CE->getOpcode() == Instruction::GetElementPtr) {
179 unsigned NumOps = CE->getNumOperands();
180 assert(NumOps > 1 && "CE folding didn't work!");
181 if (CE->getOperand(NumOps-1)->isNullValue()) {
182 // Check to make sure the last index really is an array index.
183 gep_type_iterator GTI = gep_type_begin(CE);
184 for (unsigned i = 1, e = CE->getNumOperands()-1;
185 i != e; ++i, ++GTI)
186 /*empty*/;
187 if (isa<SequentialType>(*GTI)) {
188 // Pull the last index out of the constant expr GEP.
189 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
190 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
191 &CEIdxs[0],
192 CEIdxs.size());
David Greene393be882007-09-04 15:46:09 +0000193 Value *Idx[2];
194 Idx[0] = Constant::getNullValue(Type::Int32Ty);
195 Idx[1] = NewAdd;
Gabor Greifd6da1d02008-04-06 20:25:17 +0000196 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
Dan Gohman963fc812009-02-17 19:13:57 +0000197 NCE, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 GEPI->getName(), GEPI);
199 SE->deleteValueFromRecords(GEPI);
200 GEPI->replaceAllUsesWith(NGEPI);
201 GEPI->eraseFromParent();
202 GEPI = NGEPI;
203 }
204 }
205 }
206
207
208 // Finally, if there are any other users of the PHI node, we must
209 // insert a new GEP instruction that uses the pre-incremented version
210 // of the induction amount.
211 if (!PN->use_empty()) {
212 BasicBlock::iterator InsertPos = PN; ++InsertPos;
213 while (isa<PHINode>(InsertPos)) ++InsertPos;
214 Value *PreInc =
Gabor Greifd6da1d02008-04-06 20:25:17 +0000215 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
216 NewPhi, "", InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 PreInc->takeName(PN);
218 PN->replaceAllUsesWith(PreInc);
219 }
220
221 // Delete the old PHI for sure, and the GEP if its otherwise unused.
222 DeadInsts.insert(PN);
223
224 ++NumPointer;
225 Changed = true;
226 }
227}
228
229/// LinearFunctionTestReplace - This method rewrites the exit condition of the
230/// loop to be a canonical != comparison against the incremented loop induction
231/// variable. This pass is able to rewrite the exit tests of any loop where the
232/// SCEV analysis can determine a loop-invariant trip count of the loop, which
233/// is actually a much broader range than just linear tests.
Dan Gohmancacd2012009-02-12 22:19:27 +0000234void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
235 SCEVHandle IterationCount,
236 Value *IndVar,
237 BasicBlock *ExitingBlock,
238 BranchInst *BI,
Dan Gohmana5d38012009-02-18 17:22:41 +0000239 SCEVExpander &Rewriter,
240 bool SignExtendTripCount) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241 // If the exiting block is not the same as the backedge block, we must compare
242 // against the preincremented value, otherwise we prefer to compare against
243 // the post-incremented value.
Dan Gohmancacd2012009-02-12 22:19:27 +0000244 Value *CmpIndVar;
245 if (ExitingBlock == L->getLoopLatch()) {
246 // What ScalarEvolution calls the "iteration count" is actually the
247 // number of times the branch is taken. Add one to get the number
248 // of times the branch is executed. If this addition may overflow,
249 // we have to be more pessimistic and cast the induction variable
250 // before doing the add.
251 SCEVHandle Zero = SE->getIntegerSCEV(0, IterationCount->getType());
252 SCEVHandle N =
253 SE->getAddExpr(IterationCount,
254 SE->getIntegerSCEV(1, IterationCount->getType()));
255 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
256 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
257 // No overflow. Cast the sum.
Dan Gohmana5d38012009-02-18 17:22:41 +0000258 if (SignExtendTripCount)
259 IterationCount = SE->getTruncateOrSignExtend(N, IndVar->getType());
260 else
261 IterationCount = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000262 } else {
263 // Potential overflow. Cast before doing the add.
Dan Gohmana5d38012009-02-18 17:22:41 +0000264 if (SignExtendTripCount)
265 IterationCount = SE->getTruncateOrSignExtend(IterationCount,
266 IndVar->getType());
267 else
268 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
269 IndVar->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000270 IterationCount =
271 SE->getAddExpr(IterationCount,
272 SE->getIntegerSCEV(1, IndVar->getType()));
273 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 // The IterationCount expression contains the number of times that the
276 // backedge actually branches to the loop header. This is one less than the
277 // number of times the loop executes, so add one to it.
Dan Gohmancacd2012009-02-12 22:19:27 +0000278 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279 } else {
280 // We have to use the preincremented value...
Dan Gohmana5d38012009-02-18 17:22:41 +0000281 if (SignExtendTripCount)
282 IterationCount = SE->getTruncateOrSignExtend(IterationCount,
283 IndVar->getType());
284 else
285 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
286 IndVar->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000287 CmpIndVar = IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289
290 // Expand the code for the iteration count into the preheader of the loop.
291 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmancacd2012009-02-12 22:19:27 +0000292 Value *ExitCnt = Rewriter.expandCodeFor(IterationCount,
293 Preheader->getTerminator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294
295 // Insert a new icmp_ne or icmp_eq instruction before the branch.
296 ICmpInst::Predicate Opcode;
297 if (L->contains(BI->getSuccessor(0)))
298 Opcode = ICmpInst::ICMP_NE;
299 else
300 Opcode = ICmpInst::ICMP_EQ;
301
Dan Gohmancacd2012009-02-12 22:19:27 +0000302 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
303 << " LHS:" << *CmpIndVar // includes a newline
304 << " op:\t"
Dan Gohman8555ff72009-02-14 02:26:50 +0000305 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohmancacd2012009-02-12 22:19:27 +0000306 << " RHS:\t" << *IterationCount << "\n";
307
308 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 BI->setCondition(Cond);
310 ++NumLFTR;
311 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312}
313
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314/// RewriteLoopExitValues - Check to see if this loop has a computable
315/// loop-invariant execution count. If so, this means that we can compute the
316/// final value of any expressions that are recurrent in the loop, and
317/// substitute the exit values from the loop into any instructions outside of
318/// the loop that use the final values of the current expressions.
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000319void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320 BasicBlock *Preheader = L->getLoopPreheader();
321
322 // Scan all of the instructions in the loop, looking at those that have
323 // extra-loop users and which are recurrences.
324 SCEVExpander Rewriter(*SE, *LI);
325
326 // We insert the code into the preheader of the loop if the loop contains
327 // multiple exit blocks, or in the exit block if there is exactly one.
328 BasicBlock *BlockToInsertInto;
Devang Patel02451fa2007-08-21 00:31:24 +0000329 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330 L->getUniqueExitBlocks(ExitBlocks);
331 if (ExitBlocks.size() == 1)
332 BlockToInsertInto = ExitBlocks[0];
333 else
334 BlockToInsertInto = Preheader;
Dan Gohman514277c2008-05-23 21:05:58 +0000335 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000337 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338
Chris Lattnerb25465e2008-11-16 07:17:51 +0000339 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 std::map<Instruction*, Value*> ExitValues;
341
342 // Find all values that are computed inside the loop, but used outside of it.
343 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
344 // the exit blocks of the loop to find them.
345 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
346 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohman963fc812009-02-17 19:13:57 +0000347
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000348 // If there are no PHI nodes in this exit block, then no values defined
349 // inside the loop are used on this path, skip it.
350 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
351 if (!PN) continue;
Dan Gohman963fc812009-02-17 19:13:57 +0000352
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000353 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohman963fc812009-02-17 19:13:57 +0000354
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000355 // Iterate over all of the PHI nodes.
356 BasicBlock::iterator BBI = ExitBB->begin();
357 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohman963fc812009-02-17 19:13:57 +0000358
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 // Iterate over all of the values in all the PHI nodes.
360 for (unsigned i = 0; i != NumPreds; ++i) {
361 // If the value being merged in is not integer or is not defined
362 // in the loop, skip it.
363 Value *InVal = PN->getIncomingValue(i);
364 if (!isa<Instruction>(InVal) ||
365 // SCEV only supports integer expressions for now.
366 !isa<IntegerType>(InVal->getType()))
367 continue;
368
369 // If this pred is for a subloop, not L itself, skip it.
Dan Gohman963fc812009-02-17 19:13:57 +0000370 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371 continue; // The Block is in a subloop, skip it.
372
373 // Check that InVal is defined in the loop.
374 Instruction *Inst = cast<Instruction>(InVal);
375 if (!L->contains(Inst->getParent()))
376 continue;
Dan Gohman963fc812009-02-17 19:13:57 +0000377
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 // We require that this value either have a computable evolution or that
379 // the loop have a constant iteration count. In the case where the loop
380 // has a constant iteration count, we can sometimes force evaluation of
381 // the exit value through brute force.
382 SCEVHandle SH = SE->getSCEV(Inst);
383 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
384 continue; // Cannot get exit evolution for the loop value.
Dan Gohman963fc812009-02-17 19:13:57 +0000385
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 // Okay, this instruction has a user outside of the current loop
387 // and varies predictably *inside* the loop. Evaluate the value it
388 // contains when the loop exits, if possible.
389 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
390 if (isa<SCEVCouldNotCompute>(ExitValue) ||
391 !ExitValue->isLoopInvariant(L))
392 continue;
393
394 Changed = true;
395 ++NumReplaced;
Dan Gohman963fc812009-02-17 19:13:57 +0000396
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397 // See if we already computed the exit value for the instruction, if so,
398 // just reuse it.
399 Value *&ExitVal = ExitValues[Inst];
400 if (!ExitVal)
401 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Dan Gohman963fc812009-02-17 19:13:57 +0000402
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
404 << " LoopVal = " << *Inst << "\n";
405
406 PN->setIncomingValue(i, ExitVal);
Dan Gohman963fc812009-02-17 19:13:57 +0000407
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 // If this instruction is dead now, schedule it to be removed.
409 if (Inst->use_empty())
410 InstructionsToDelete.insert(Inst);
Dan Gohman963fc812009-02-17 19:13:57 +0000411
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 // See if this is a single-entry LCSSA PHI node. If so, we can (and
413 // have to) remove
414 // the PHI entirely. This is safe, because the NewVal won't be variant
415 // in the loop, so we don't need an LCSSA phi node anymore.
416 if (NumPreds == 1) {
417 SE->deleteValueFromRecords(PN);
418 PN->replaceAllUsesWith(ExitVal);
419 PN->eraseFromParent();
420 break;
421 }
422 }
423 }
424 }
Dan Gohman963fc812009-02-17 19:13:57 +0000425
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 DeleteTriviallyDeadInstructions(InstructionsToDelete);
427}
428
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000429void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430 // First step. Check to see if there are any trivial GEP pointer recurrences.
431 // If there are, change them into integer recurrences, permitting analysis by
432 // the SCEV routines.
433 //
434 BasicBlock *Header = L->getHeader();
435 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436
Chris Lattnerb25465e2008-11-16 07:17:51 +0000437 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
439 PHINode *PN = cast<PHINode>(I);
440 if (isa<PointerType>(PN->getType()))
441 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Devang Patelc8dac622008-11-17 21:32:02 +0000442 else
443 HandleFloatingPointIV(L, PN, DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444 }
445
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000446 // If the loop previously had a pointer or floating-point IV, ScalarEvolution
447 // may not have been able to compute a trip count. Now that we've done some
448 // re-writing, the trip count may be computable.
449 if (Changed)
450 SE->forgetLoopIterationCount(L);
451
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 if (!DeadInsts.empty())
453 DeleteTriviallyDeadInstructions(DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454}
455
Dan Gohmancacd2012009-02-12 22:19:27 +0000456/// getEffectiveIndvarType - Determine the widest type that the
457/// induction-variable PHINode Phi is cast to.
458///
459static const Type *getEffectiveIndvarType(const PHINode *Phi) {
460 const Type *Ty = Phi->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000461
Dan Gohmancacd2012009-02-12 22:19:27 +0000462 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
463 UI != UE; ++UI) {
464 const Type *CandidateType = NULL;
465 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
466 CandidateType = ZI->getDestTy();
467 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
468 CandidateType = SI->getDestTy();
469 if (CandidateType &&
470 CandidateType->getPrimitiveSizeInBits() >
471 Ty->getPrimitiveSizeInBits())
472 Ty = CandidateType;
473 }
474
475 return Ty;
476}
477
Dan Gohmancecc80f2009-02-14 02:31:09 +0000478/// TestOrigIVForWrap - Analyze the original induction variable
Dan Gohmana730da32009-02-18 00:52:00 +0000479/// that controls the loop's iteration to determine whether it
Dan Gohmana5d38012009-02-18 17:22:41 +0000480/// would ever undergo signed or unsigned overflow. Also, check
481/// whether an induction variable in the same type that starts
482/// at 0 would undergo signed overflow.
Dan Gohmana730da32009-02-18 00:52:00 +0000483///
Dan Gohmana5d38012009-02-18 17:22:41 +0000484/// In addition to setting the NoSignedWrap, NoUnsignedWrap, and
485/// SignExtendTripCount variables, return the PHI for this induction
486/// variable.
Dan Gohmancacd2012009-02-12 22:19:27 +0000487///
488/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohmancecc80f2009-02-14 02:31:09 +0000489/// Perhaps this can be merged with ScalarEvolution::getIterationCount
490/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmancacd2012009-02-12 22:19:27 +0000491///
Dan Gohmana730da32009-02-18 00:52:00 +0000492static const PHINode *TestOrigIVForWrap(const Loop *L,
493 const BranchInst *BI,
494 const Instruction *OrigCond,
495 bool &NoSignedWrap,
Dan Gohmana5d38012009-02-18 17:22:41 +0000496 bool &NoUnsignedWrap,
497 bool &SignExtendTripCount) {
Dan Gohmancacd2012009-02-12 22:19:27 +0000498 // Verify that the loop is sane and find the exit condition.
499 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmana730da32009-02-18 00:52:00 +0000500 if (!Cmp) return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000501
Dan Gohmancecc80f2009-02-14 02:31:09 +0000502 const Value *CmpLHS = Cmp->getOperand(0);
503 const Value *CmpRHS = Cmp->getOperand(1);
504 const BasicBlock *TrueBB = BI->getSuccessor(0);
505 const BasicBlock *FalseBB = BI->getSuccessor(1);
506 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmancacd2012009-02-12 22:19:27 +0000507
Dan Gohmancecc80f2009-02-14 02:31:09 +0000508 // Canonicalize a constant to the RHS.
509 if (isa<ConstantInt>(CmpLHS)) {
510 Pred = ICmpInst::getSwappedPredicate(Pred);
511 std::swap(CmpLHS, CmpRHS);
512 }
513 // Canonicalize SLE to SLT.
514 if (Pred == ICmpInst::ICMP_SLE)
515 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
516 if (!CI->getValue().isMaxSignedValue()) {
517 CmpRHS = ConstantInt::get(CI->getValue() + 1);
518 Pred = ICmpInst::ICMP_SLT;
519 }
520 // Canonicalize SGT to SGE.
521 if (Pred == ICmpInst::ICMP_SGT)
522 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
523 if (!CI->getValue().isMaxSignedValue()) {
524 CmpRHS = ConstantInt::get(CI->getValue() + 1);
525 Pred = ICmpInst::ICMP_SGE;
526 }
527 // Canonicalize SGE to SLT.
528 if (Pred == ICmpInst::ICMP_SGE) {
529 std::swap(TrueBB, FalseBB);
530 Pred = ICmpInst::ICMP_SLT;
531 }
532 // Canonicalize ULE to ULT.
533 if (Pred == ICmpInst::ICMP_ULE)
534 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
535 if (!CI->getValue().isMaxValue()) {
536 CmpRHS = ConstantInt::get(CI->getValue() + 1);
537 Pred = ICmpInst::ICMP_ULT;
538 }
539 // Canonicalize UGT to UGE.
540 if (Pred == ICmpInst::ICMP_UGT)
541 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
542 if (!CI->getValue().isMaxValue()) {
543 CmpRHS = ConstantInt::get(CI->getValue() + 1);
544 Pred = ICmpInst::ICMP_UGE;
545 }
546 // Canonicalize UGE to ULT.
547 if (Pred == ICmpInst::ICMP_UGE) {
548 std::swap(TrueBB, FalseBB);
549 Pred = ICmpInst::ICMP_ULT;
550 }
551 // For now, analyze only LT loops for signed overflow.
552 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
Dan Gohmana730da32009-02-18 00:52:00 +0000553 return 0;
Dan Gohmancecc80f2009-02-14 02:31:09 +0000554
555 bool isSigned = Pred == ICmpInst::ICMP_SLT;
556
557 // Get the increment instruction. Look past casts if we will
Dan Gohmancacd2012009-02-12 22:19:27 +0000558 // be able to prove that the original induction variable doesn't
Dan Gohmancecc80f2009-02-14 02:31:09 +0000559 // undergo signed or unsigned overflow, respectively.
560 const Value *IncrVal = CmpLHS;
561 if (isSigned) {
562 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
563 if (!isa<ConstantInt>(CmpRHS) ||
564 !cast<ConstantInt>(CmpRHS)->getValue()
565 .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
Dan Gohmana730da32009-02-18 00:52:00 +0000566 return 0;
Dan Gohmancecc80f2009-02-14 02:31:09 +0000567 IncrVal = SI->getOperand(0);
568 }
569 } else {
570 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
571 if (!isa<ConstantInt>(CmpRHS) ||
572 !cast<ConstantInt>(CmpRHS)->getValue()
573 .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
Dan Gohmana730da32009-02-18 00:52:00 +0000574 return 0;
Dan Gohmancecc80f2009-02-14 02:31:09 +0000575 IncrVal = ZI->getOperand(0);
576 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000577 }
578
579 // For now, only analyze induction variables that have simple increments.
580 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
581 if (!IncrOp ||
582 IncrOp->getOpcode() != Instruction::Add ||
583 !isa<ConstantInt>(IncrOp->getOperand(1)) ||
584 !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
Dan Gohmana730da32009-02-18 00:52:00 +0000585 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000586
587 // Make sure the PHI looks like a normal IV.
588 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
589 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmana730da32009-02-18 00:52:00 +0000590 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000591 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
592 unsigned BackEdge = !IncomingEdge;
593 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
594 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmana730da32009-02-18 00:52:00 +0000595 return 0;
Dan Gohmancecc80f2009-02-14 02:31:09 +0000596 if (!L->contains(TrueBB))
Dan Gohmana730da32009-02-18 00:52:00 +0000597 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000598
599 // For now, only analyze loops with a constant start value, so that
Dan Gohmancecc80f2009-02-14 02:31:09 +0000600 // we can easily determine if the start value is not a maximum value
601 // which would wrap on the first iteration.
Dan Gohman6f2a83e2009-02-18 16:54:33 +0000602 const ConstantInt *InitialVal =
603 dyn_cast<ConstantInt>(PN->getIncomingValue(IncomingEdge));
604 if (!InitialVal)
Dan Gohmana730da32009-02-18 00:52:00 +0000605 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000606
Dan Gohmancecc80f2009-02-14 02:31:09 +0000607 // The original induction variable will start at some non-max value,
608 // it counts up by one, and the loop iterates only while it remans
609 // less than some value in the same type. As such, it will never wrap.
Dan Gohmana5d38012009-02-18 17:22:41 +0000610 if (isSigned && !InitialVal->getValue().isMaxSignedValue()) {
Dan Gohmancecc80f2009-02-14 02:31:09 +0000611 NoSignedWrap = true;
Dan Gohmana5d38012009-02-18 17:22:41 +0000612 // If the original induction variable starts at zero or greater,
613 // the trip count can be considered signed.
614 if (InitialVal->getValue().isNonNegative())
615 SignExtendTripCount = true;
616 } else if (!isSigned && !InitialVal->getValue().isMaxValue())
Dan Gohmancecc80f2009-02-14 02:31:09 +0000617 NoUnsignedWrap = true;
Dan Gohmana730da32009-02-18 00:52:00 +0000618 return PN;
Dan Gohmancacd2012009-02-12 22:19:27 +0000619}
620
621bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622 LI = &getAnalysis<LoopInfo>();
623 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 Changed = false;
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000625
626 // If there are any floating-point or pointer recurrences, attempt to
627 // transform them to use integer recurrences.
628 RewriteNonIntegerIVs(L);
629
Dan Gohmancacd2012009-02-12 22:19:27 +0000630 BasicBlock *Header = L->getHeader();
631 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000632 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmancacd2012009-02-12 22:19:27 +0000633
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 // Verify the input to the pass in already in LCSSA form.
635 assert(L->isLCSSAForm());
636
637 // Check to see if this loop has a computable loop-invariant execution count.
638 // If so, this means that we can compute the final value of any expressions
639 // that are recurrent in the loop, and substitute the exit values from the
640 // loop into any instructions outside of the loop that use the final values of
641 // the current expressions.
642 //
643 SCEVHandle IterationCount = SE->getIterationCount(L);
644 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000645 RewriteLoopExitValues(L, IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646
647 // Next, analyze all of the induction variables in the loop, canonicalizing
648 // auxillary induction variables.
649 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
650
651 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
652 PHINode *PN = cast<PHINode>(I);
653 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
654 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohman173d9142009-02-14 02:25:19 +0000655 // FIXME: It is an extremely bad idea to indvar substitute anything more
656 // complex than affine induction variables. Doing so will put expensive
657 // polynomial evaluations inside of the loop, and the str reduction pass
658 // currently can only reduce affine polynomials. For now just disable
659 // indvar subst on anything more complex than an affine addrec.
660 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
661 if (AR->getLoop() == L && AR->isAffine())
662 IndVars.push_back(std::make_pair(PN, SCEV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663 }
664 }
665
Dan Gohmancacd2012009-02-12 22:19:27 +0000666 // Compute the type of the largest recurrence expression, and collect
667 // the set of the types of the other recurrence expressions.
668 const Type *LargestType = 0;
669 SmallSetVector<const Type *, 4> SizesToInsert;
670 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
671 LargestType = IterationCount->getType();
672 SizesToInsert.insert(IterationCount->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000674 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
675 const PHINode *PN = IndVars[i].first;
676 SizesToInsert.insert(PN->getType());
677 const Type *EffTy = getEffectiveIndvarType(PN);
678 SizesToInsert.insert(EffTy);
679 if (!LargestType ||
680 EffTy->getPrimitiveSizeInBits() >
681 LargestType->getPrimitiveSizeInBits())
682 LargestType = EffTy;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683 }
684
685 // Create a rewriter object which we'll use to transform the code with.
686 SCEVExpander Rewriter(*SE, *LI);
687
688 // Now that we know the largest of of the induction variables in this loop,
689 // insert a canonical induction variable of the largest size.
Dan Gohmancacd2012009-02-12 22:19:27 +0000690 Value *IndVar = 0;
691 if (!SizesToInsert.empty()) {
692 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
693 ++NumInserted;
694 Changed = true;
695 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696 }
697
Dan Gohmancacd2012009-02-12 22:19:27 +0000698 // If we have a trip count expression, rewrite the loop's exit condition
699 // using it. We can currently only handle loops with a single exit.
Dan Gohmancecc80f2009-02-14 02:31:09 +0000700 bool NoSignedWrap = false;
701 bool NoUnsignedWrap = false;
Dan Gohmana5d38012009-02-18 17:22:41 +0000702 bool SignExtendTripCount = false;
Dan Gohmana730da32009-02-18 00:52:00 +0000703 const PHINode *OrigControllingPHI = 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000704 if (!isa<SCEVCouldNotCompute>(IterationCount) && ExitingBlock)
705 // Can't rewrite non-branch yet.
706 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
707 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmancecc80f2009-02-14 02:31:09 +0000708 // Determine if the OrigIV will ever undergo overflow.
Dan Gohmana730da32009-02-18 00:52:00 +0000709 OrigControllingPHI =
710 TestOrigIVForWrap(L, BI, OrigCond,
Dan Gohmana5d38012009-02-18 17:22:41 +0000711 NoSignedWrap, NoUnsignedWrap,
712 SignExtendTripCount);
Dan Gohmancacd2012009-02-12 22:19:27 +0000713
714 // We'll be replacing the original condition, so it'll be dead.
715 DeadInsts.insert(OrigCond);
716 }
717
718 LinearFunctionTestReplace(L, IterationCount, IndVar,
Dan Gohmana5d38012009-02-18 17:22:41 +0000719 ExitingBlock, BI, Rewriter,
720 SignExtendTripCount);
Dan Gohmancacd2012009-02-12 22:19:27 +0000721 }
722
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 // Now that we have a canonical induction variable, we can rewrite any
724 // recurrences in terms of the induction variable. Start with the auxillary
725 // induction variables, and recursively rewrite any of their uses.
Dan Gohman514277c2008-05-23 21:05:58 +0000726 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727
728 // If there were induction variables of other sizes, cast the primary
729 // induction variable to the right size for them, avoiding the need for the
730 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmancacd2012009-02-12 22:19:27 +0000731 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
732 const Type *Ty = SizesToInsert[i];
733 if (Ty != LargestType) {
734 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
735 Rewriter.addInsertedValue(New, SE->getSCEV(New));
736 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
737 << *New << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738 }
739 }
740
741 // Rewrite all induction variables in terms of the canonical induction
742 // variable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743 while (!IndVars.empty()) {
744 PHINode *PN = IndVars.back().first;
Dan Gohmanc71cac12009-02-17 00:10:53 +0000745 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
746 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
747 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000748 << " into = " << *NewVal << "\n";
749 NewVal->takeName(PN);
750
Dan Gohmancacd2012009-02-12 22:19:27 +0000751 /// If the new canonical induction variable is wider than the original,
752 /// and the original has uses that are casts to wider types, see if the
753 /// truncate and extend can be omitted.
Dan Gohmana730da32009-02-18 00:52:00 +0000754 if (PN == OrigControllingPHI && PN->getType() != LargestType)
Dan Gohmancacd2012009-02-12 22:19:27 +0000755 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmancecc80f2009-02-14 02:31:09 +0000756 UI != UE; ++UI) {
757 if (isa<SExtInst>(UI) && NoSignedWrap) {
758 SCEVHandle ExtendedStart =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000759 SE->getSignExtendExpr(AR->getStart(), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000760 SCEVHandle ExtendedStep =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000761 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000762 SCEVHandle ExtendedAddRec =
763 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
764 if (LargestType != UI->getType())
765 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
766 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
Dan Gohmancacd2012009-02-12 22:19:27 +0000767 UI->replaceAllUsesWith(TruncIndVar);
768 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
769 DeadInsts.insert(DeadUse);
770 }
Dan Gohmancecc80f2009-02-14 02:31:09 +0000771 if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
772 SCEVHandle ExtendedStart =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000773 SE->getZeroExtendExpr(AR->getStart(), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000774 SCEVHandle ExtendedStep =
Dan Gohmanc71cac12009-02-17 00:10:53 +0000775 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000776 SCEVHandle ExtendedAddRec =
777 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
778 if (LargestType != UI->getType())
779 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
780 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
781 UI->replaceAllUsesWith(TruncIndVar);
782 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
783 DeadInsts.insert(DeadUse);
784 }
785 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000786
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 // Replace the old PHI Node with the inserted computation.
788 PN->replaceAllUsesWith(NewVal);
789 DeadInsts.insert(PN);
790 IndVars.pop_back();
791 ++NumRemoved;
792 Changed = true;
793 }
794
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 DeleteTriviallyDeadInstructions(DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000796 assert(L->isLCSSAForm());
797 return Changed;
798}
Devang Patelbda43802008-09-09 21:41:07 +0000799
Devang Patelb8ccf572008-11-18 00:40:02 +0000800/// Return true if it is OK to use SIToFPInst for an inducation variable
801/// with given inital and exit values.
802static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
803 uint64_t intIV, uint64_t intEV) {
804
Dan Gohman963fc812009-02-17 19:13:57 +0000805 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patelb8ccf572008-11-18 00:40:02 +0000806 return true;
807
808 // If the iteration range can be handled by SIToFPInst then use it.
809 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendlingb9a5a682008-11-18 10:57:27 +0000810 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patelb8ccf572008-11-18 00:40:02 +0000811 return true;
Dan Gohman963fc812009-02-17 19:13:57 +0000812
Devang Patelb8ccf572008-11-18 00:40:02 +0000813 return false;
814}
815
816/// convertToInt - Convert APF to an integer, if possible.
Devang Patele2ba01d2008-11-17 23:27:13 +0000817static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
818
819 bool isExact = false;
Evan Cheng30e65f62008-11-26 01:11:57 +0000820 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
821 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000822 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patele2ba01d2008-11-17 23:27:13 +0000823 APFloat::rmTowardZero, &isExact)
824 != APFloat::opOK)
825 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000826 if (!isExact)
Devang Patele2ba01d2008-11-17 23:27:13 +0000827 return false;
828 return true;
829
830}
831
Devang Patel7ca23c92008-11-03 18:32:19 +0000832/// HandleFloatingPointIV - If the loop has floating induction variable
833/// then insert corresponding integer induction variable if possible.
Devang Patelc8dac622008-11-17 21:32:02 +0000834/// For example,
835/// for(double i = 0; i < 10000; ++i)
836/// bar(i)
837/// is converted into
838/// for(int i = 0; i < 10000; ++i)
839/// bar((double)i);
840///
Dan Gohman963fc812009-02-17 19:13:57 +0000841void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patelc8dac622008-11-17 21:32:02 +0000842 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel7ca23c92008-11-03 18:32:19 +0000843
Devang Patelc8dac622008-11-17 21:32:02 +0000844 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
845 unsigned BackEdge = IncomingEdge^1;
Dan Gohman963fc812009-02-17 19:13:57 +0000846
Devang Patelc8dac622008-11-17 21:32:02 +0000847 // Check incoming value.
Devang Patele2ba01d2008-11-17 23:27:13 +0000848 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
849 if (!InitValue) return;
850 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
851 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
852 return;
853
854 // Check IV increment. Reject this PH if increement operation is not
855 // an add or increment value can not be represented by an integer.
Dan Gohman963fc812009-02-17 19:13:57 +0000856 BinaryOperator *Incr =
Devang Patelc8dac622008-11-17 21:32:02 +0000857 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
858 if (!Incr) return;
859 if (Incr->getOpcode() != Instruction::Add) return;
860 ConstantFP *IncrValue = NULL;
861 unsigned IncrVIndex = 1;
862 if (Incr->getOperand(1) == PH)
863 IncrVIndex = 0;
864 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
865 if (!IncrValue) return;
Devang Patele2ba01d2008-11-17 23:27:13 +0000866 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
867 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
868 return;
Dan Gohman963fc812009-02-17 19:13:57 +0000869
Devang Patele2ba01d2008-11-17 23:27:13 +0000870 // Check Incr uses. One user is PH and the other users is exit condition used
871 // by the conditional terminator.
Devang Patelc8dac622008-11-17 21:32:02 +0000872 Value::use_iterator IncrUse = Incr->use_begin();
873 Instruction *U1 = cast<Instruction>(IncrUse++);
874 if (IncrUse == Incr->use_end()) return;
875 Instruction *U2 = cast<Instruction>(IncrUse++);
876 if (IncrUse != Incr->use_end()) return;
Dan Gohman963fc812009-02-17 19:13:57 +0000877
Devang Patelc8dac622008-11-17 21:32:02 +0000878 // Find exit condition.
879 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
880 if (!EC)
881 EC = dyn_cast<FCmpInst>(U2);
882 if (!EC) return;
883
884 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
885 if (!BI->isConditional()) return;
886 if (BI->getCondition() != EC) return;
Devang Patel7ca23c92008-11-03 18:32:19 +0000887 }
Devang Patel7ca23c92008-11-03 18:32:19 +0000888
Devang Patele2ba01d2008-11-17 23:27:13 +0000889 // Find exit value. If exit value can not be represented as an interger then
890 // do not handle this floating point PH.
Devang Patelc8dac622008-11-17 21:32:02 +0000891 ConstantFP *EV = NULL;
892 unsigned EVIndex = 1;
893 if (EC->getOperand(1) == Incr)
894 EVIndex = 0;
895 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
896 if (!EV) return;
Devang Patelc8dac622008-11-17 21:32:02 +0000897 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patele2ba01d2008-11-17 23:27:13 +0000898 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patelc8dac622008-11-17 21:32:02 +0000899 return;
Dan Gohman963fc812009-02-17 19:13:57 +0000900
Devang Patelc8dac622008-11-17 21:32:02 +0000901 // Find new predicate for integer comparison.
902 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
903 switch (EC->getPredicate()) {
904 case CmpInst::FCMP_OEQ:
905 case CmpInst::FCMP_UEQ:
906 NewPred = CmpInst::ICMP_EQ;
907 break;
908 case CmpInst::FCMP_OGT:
909 case CmpInst::FCMP_UGT:
910 NewPred = CmpInst::ICMP_UGT;
911 break;
912 case CmpInst::FCMP_OGE:
913 case CmpInst::FCMP_UGE:
914 NewPred = CmpInst::ICMP_UGE;
915 break;
916 case CmpInst::FCMP_OLT:
917 case CmpInst::FCMP_ULT:
918 NewPred = CmpInst::ICMP_ULT;
919 break;
920 case CmpInst::FCMP_OLE:
921 case CmpInst::FCMP_ULE:
922 NewPred = CmpInst::ICMP_ULE;
923 break;
924 default:
925 break;
Devang Patel7ca23c92008-11-03 18:32:19 +0000926 }
Devang Patelc8dac622008-11-17 21:32:02 +0000927 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohman963fc812009-02-17 19:13:57 +0000928
Devang Patelc8dac622008-11-17 21:32:02 +0000929 // Insert new integer induction variable.
930 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
931 PH->getName()+".int", PH);
Devang Patele2ba01d2008-11-17 23:27:13 +0000932 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000933 PH->getIncomingBlock(IncomingEdge));
934
Dan Gohman963fc812009-02-17 19:13:57 +0000935 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
936 ConstantInt::get(Type::Int32Ty,
Devang Patele2ba01d2008-11-17 23:27:13 +0000937 newIncrValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000938 Incr->getName()+".int", Incr);
939 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
940
941 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
942 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
943 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
Dan Gohman963fc812009-02-17 19:13:57 +0000944 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patelc8dac622008-11-17 21:32:02 +0000945 EC->getParent()->getTerminator());
Dan Gohman963fc812009-02-17 19:13:57 +0000946
Devang Patelc8dac622008-11-17 21:32:02 +0000947 // Delete old, floating point, exit comparision instruction.
948 EC->replaceAllUsesWith(NewEC);
949 DeadInsts.insert(EC);
Dan Gohman963fc812009-02-17 19:13:57 +0000950
Devang Patelc8dac622008-11-17 21:32:02 +0000951 // Delete old, floating point, increment instruction.
952 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
953 DeadInsts.insert(Incr);
Dan Gohman963fc812009-02-17 19:13:57 +0000954
Devang Patelb8ccf572008-11-18 00:40:02 +0000955 // Replace floating induction variable. Give SIToFPInst preference over
956 // UIToFPInst because it is faster on platforms that are widely used.
957 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Dan Gohman963fc812009-02-17 19:13:57 +0000958 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patele2ba01d2008-11-17 23:27:13 +0000959 PH->getParent()->getFirstNonPHI());
960 PH->replaceAllUsesWith(Conv);
961 } else {
Dan Gohman963fc812009-02-17 19:13:57 +0000962 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patele2ba01d2008-11-17 23:27:13 +0000963 PH->getParent()->getFirstNonPHI());
964 PH->replaceAllUsesWith(Conv);
965 }
Devang Patelc8dac622008-11-17 21:32:02 +0000966 DeadInsts.insert(PH);
Devang Patel7ca23c92008-11-03 18:32:19 +0000967}
968