blob: b07a69cc8b4452e3b12215d3976838b3871ff565 [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>();
Dan Gohman0d35b112009-02-23 16:29:41 +000084 AU.addPreserved<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085 AU.addPreservedID(LoopSimplifyID);
86 AU.addPreservedID(LCSSAID);
87 AU.setPreservesCFG();
88 }
89
90 private:
91
Dan Gohmanf3a060a2009-02-17 20:49:49 +000092 void RewriteNonIntegerIVs(Loop *L);
93
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattnerb25465e2008-11-16 07:17:51 +000095 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohman76d5a0d2009-02-24 18:55:53 +000096 void LinearFunctionTestReplace(Loop *L, SCEVHandle BackedgeTakenCount,
Dan Gohman1247dc32009-02-17 15:57:39 +000097 Value *IndVar,
Dan Gohmancacd2012009-02-12 22:19:27 +000098 BasicBlock *ExitingBlock,
99 BranchInst *BI,
Dan Gohmanebac2542009-02-23 23:20:35 +0000100 SCEVExpander &Rewriter);
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000101 void RewriteLoopExitValues(Loop *L, SCEV *BackedgeTakenCount);
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,
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000235 SCEVHandle BackedgeTakenCount,
Dan Gohmancacd2012009-02-12 22:19:27 +0000236 Value *IndVar,
237 BasicBlock *ExitingBlock,
238 BranchInst *BI,
Dan Gohmanebac2542009-02-23 23:20:35 +0000239 SCEVExpander &Rewriter) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 // If the exiting block is not the same as the backedge block, we must compare
241 // against the preincremented value, otherwise we prefer to compare against
242 // the post-incremented value.
Dan Gohmancacd2012009-02-12 22:19:27 +0000243 Value *CmpIndVar;
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000244 SCEVHandle RHS = BackedgeTakenCount;
Dan Gohmancacd2012009-02-12 22:19:27 +0000245 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000246 // Add one to the "backedge-taken" count to get the trip count.
247 // If this addition may overflow, we have to be more pessimistic and
248 // cast the induction variable before doing the add.
249 SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000250 SCEVHandle N =
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000251 SE->getAddExpr(BackedgeTakenCount,
252 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmancacd2012009-02-12 22:19:27 +0000253 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
254 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
255 // No overflow. Cast the sum.
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000256 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000257 } else {
258 // Potential overflow. Cast before doing the add.
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000259 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
260 IndVar->getType());
261 RHS = SE->getAddExpr(RHS,
262 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmancacd2012009-02-12 22:19:27 +0000263 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000265 // The BackedgeTaken expression contains the number of times that the
266 // backedge branches to the loop header. This is one less than the
267 // number of times the loop executes, so use the incremented indvar.
Dan Gohmancacd2012009-02-12 22:19:27 +0000268 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 } else {
270 // We have to use the preincremented value...
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000271 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
272 IndVar->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000273 CmpIndVar = IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275
276 // Expand the code for the iteration count into the preheader of the loop.
277 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000278 Value *ExitCnt = Rewriter.expandCodeFor(RHS,
Dan Gohmancacd2012009-02-12 22:19:27 +0000279 Preheader->getTerminator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280
281 // Insert a new icmp_ne or icmp_eq instruction before the branch.
282 ICmpInst::Predicate Opcode;
283 if (L->contains(BI->getSuccessor(0)))
284 Opcode = ICmpInst::ICMP_NE;
285 else
286 Opcode = ICmpInst::ICMP_EQ;
287
Dan Gohmancacd2012009-02-12 22:19:27 +0000288 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
289 << " LHS:" << *CmpIndVar // includes a newline
290 << " op:\t"
Dan Gohman8555ff72009-02-14 02:26:50 +0000291 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000292 << " RHS:\t" << *RHS << "\n";
Dan Gohmancacd2012009-02-12 22:19:27 +0000293
294 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 BI->setCondition(Cond);
296 ++NumLFTR;
297 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298}
299
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300/// RewriteLoopExitValues - Check to see if this loop has a computable
301/// loop-invariant execution count. If so, this means that we can compute the
302/// final value of any expressions that are recurrent in the loop, and
303/// substitute the exit values from the loop into any instructions outside of
304/// the loop that use the final values of the current expressions.
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000305void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *BackedgeTakenCount) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 BasicBlock *Preheader = L->getLoopPreheader();
307
308 // Scan all of the instructions in the loop, looking at those that have
309 // extra-loop users and which are recurrences.
310 SCEVExpander Rewriter(*SE, *LI);
311
312 // We insert the code into the preheader of the loop if the loop contains
313 // multiple exit blocks, or in the exit block if there is exactly one.
314 BasicBlock *BlockToInsertInto;
Devang Patel02451fa2007-08-21 00:31:24 +0000315 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 L->getUniqueExitBlocks(ExitBlocks);
317 if (ExitBlocks.size() == 1)
318 BlockToInsertInto = ExitBlocks[0];
319 else
320 BlockToInsertInto = Preheader;
Dan Gohman514277c2008-05-23 21:05:58 +0000321 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000323 bool HasConstantItCount = isa<SCEVConstant>(BackedgeTakenCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324
Chris Lattnerb25465e2008-11-16 07:17:51 +0000325 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326 std::map<Instruction*, Value*> ExitValues;
327
328 // Find all values that are computed inside the loop, but used outside of it.
329 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
330 // the exit blocks of the loop to find them.
331 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
332 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohman963fc812009-02-17 19:13:57 +0000333
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 // If there are no PHI nodes in this exit block, then no values defined
335 // inside the loop are used on this path, skip it.
336 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
337 if (!PN) continue;
Dan Gohman963fc812009-02-17 19:13:57 +0000338
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohman963fc812009-02-17 19:13:57 +0000340
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 // Iterate over all of the PHI nodes.
342 BasicBlock::iterator BBI = ExitBB->begin();
343 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohman963fc812009-02-17 19:13:57 +0000344
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345 // Iterate over all of the values in all the PHI nodes.
346 for (unsigned i = 0; i != NumPreds; ++i) {
347 // If the value being merged in is not integer or is not defined
348 // in the loop, skip it.
349 Value *InVal = PN->getIncomingValue(i);
350 if (!isa<Instruction>(InVal) ||
351 // SCEV only supports integer expressions for now.
352 !isa<IntegerType>(InVal->getType()))
353 continue;
354
355 // If this pred is for a subloop, not L itself, skip it.
Dan Gohman963fc812009-02-17 19:13:57 +0000356 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 continue; // The Block is in a subloop, skip it.
358
359 // Check that InVal is defined in the loop.
360 Instruction *Inst = cast<Instruction>(InVal);
361 if (!L->contains(Inst->getParent()))
362 continue;
Dan Gohman963fc812009-02-17 19:13:57 +0000363
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000364 // We require that this value either have a computable evolution or that
365 // the loop have a constant iteration count. In the case where the loop
366 // has a constant iteration count, we can sometimes force evaluation of
367 // the exit value through brute force.
368 SCEVHandle SH = SE->getSCEV(Inst);
369 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
370 continue; // Cannot get exit evolution for the loop value.
Dan Gohman963fc812009-02-17 19:13:57 +0000371
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372 // Okay, this instruction has a user outside of the current loop
373 // and varies predictably *inside* the loop. Evaluate the value it
374 // contains when the loop exits, if possible.
375 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
376 if (isa<SCEVCouldNotCompute>(ExitValue) ||
377 !ExitValue->isLoopInvariant(L))
378 continue;
379
380 Changed = true;
381 ++NumReplaced;
Dan Gohman963fc812009-02-17 19:13:57 +0000382
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383 // See if we already computed the exit value for the instruction, if so,
384 // just reuse it.
385 Value *&ExitVal = ExitValues[Inst];
386 if (!ExitVal)
387 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Dan Gohman963fc812009-02-17 19:13:57 +0000388
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
390 << " LoopVal = " << *Inst << "\n";
391
392 PN->setIncomingValue(i, ExitVal);
Dan Gohman963fc812009-02-17 19:13:57 +0000393
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394 // If this instruction is dead now, schedule it to be removed.
395 if (Inst->use_empty())
396 InstructionsToDelete.insert(Inst);
Dan Gohman963fc812009-02-17 19:13:57 +0000397
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398 // See if this is a single-entry LCSSA PHI node. If so, we can (and
399 // have to) remove
400 // the PHI entirely. This is safe, because the NewVal won't be variant
401 // in the loop, so we don't need an LCSSA phi node anymore.
402 if (NumPreds == 1) {
403 SE->deleteValueFromRecords(PN);
404 PN->replaceAllUsesWith(ExitVal);
405 PN->eraseFromParent();
406 break;
407 }
408 }
409 }
410 }
Dan Gohman963fc812009-02-17 19:13:57 +0000411
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 DeleteTriviallyDeadInstructions(InstructionsToDelete);
413}
414
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000415void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000416 // First step. Check to see if there are any trivial GEP pointer recurrences.
417 // If there are, change them into integer recurrences, permitting analysis by
418 // the SCEV routines.
419 //
420 BasicBlock *Header = L->getHeader();
421 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000422
Chris Lattnerb25465e2008-11-16 07:17:51 +0000423 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
425 PHINode *PN = cast<PHINode>(I);
426 if (isa<PointerType>(PN->getType()))
427 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Devang Patelc8dac622008-11-17 21:32:02 +0000428 else
429 HandleFloatingPointIV(L, PN, DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430 }
431
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000432 // If the loop previously had a pointer or floating-point IV, ScalarEvolution
433 // may not have been able to compute a trip count. Now that we've done some
434 // re-writing, the trip count may be computable.
435 if (Changed)
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000436 SE->forgetLoopBackedgeTakenCount(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000437
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 if (!DeadInsts.empty())
439 DeleteTriviallyDeadInstructions(DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440}
441
Dan Gohmancacd2012009-02-12 22:19:27 +0000442/// getEffectiveIndvarType - Determine the widest type that the
443/// induction-variable PHINode Phi is cast to.
444///
445static const Type *getEffectiveIndvarType(const PHINode *Phi) {
446 const Type *Ty = Phi->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000447
Dan Gohmancacd2012009-02-12 22:19:27 +0000448 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
449 UI != UE; ++UI) {
450 const Type *CandidateType = NULL;
451 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
452 CandidateType = ZI->getDestTy();
453 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
454 CandidateType = SI->getDestTy();
455 if (CandidateType &&
456 CandidateType->getPrimitiveSizeInBits() >
457 Ty->getPrimitiveSizeInBits())
458 Ty = CandidateType;
459 }
460
461 return Ty;
462}
463
Dan Gohmancecc80f2009-02-14 02:31:09 +0000464/// TestOrigIVForWrap - Analyze the original induction variable
Dan Gohmana730da32009-02-18 00:52:00 +0000465/// that controls the loop's iteration to determine whether it
Dan Gohmana5d38012009-02-18 17:22:41 +0000466/// would ever undergo signed or unsigned overflow. Also, check
467/// whether an induction variable in the same type that starts
468/// at 0 would undergo signed overflow.
Dan Gohmana730da32009-02-18 00:52:00 +0000469///
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000470/// In addition to setting the NoSignedWrap and NoUnsignedWrap
471/// variables to true when appropriate (they are not set to false here),
472/// return the PHI for this induction variable. Also record the initial
473/// and final values and the increment; these are not meaningful unless
474/// either NoSignedWrap or NoUnsignedWrap is true, and are always meaningful
475/// in that case, although the final value may be 0 indicating a nonconstant.
Dan Gohmancacd2012009-02-12 22:19:27 +0000476///
477/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000478/// Perhaps this can be merged with
479/// ScalarEvolution::getBackedgeTakenCount
Dan Gohmancecc80f2009-02-14 02:31:09 +0000480/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmancacd2012009-02-12 22:19:27 +0000481///
Dan Gohmana730da32009-02-18 00:52:00 +0000482static const PHINode *TestOrigIVForWrap(const Loop *L,
483 const BranchInst *BI,
484 const Instruction *OrigCond,
485 bool &NoSignedWrap,
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000486 bool &NoUnsignedWrap,
487 const ConstantInt* &InitialVal,
488 const ConstantInt* &IncrVal,
489 const ConstantInt* &LimitVal) {
Dan Gohmancacd2012009-02-12 22:19:27 +0000490 // Verify that the loop is sane and find the exit condition.
491 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmana730da32009-02-18 00:52:00 +0000492 if (!Cmp) return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000493
Dan Gohmancecc80f2009-02-14 02:31:09 +0000494 const Value *CmpLHS = Cmp->getOperand(0);
495 const Value *CmpRHS = Cmp->getOperand(1);
496 const BasicBlock *TrueBB = BI->getSuccessor(0);
497 const BasicBlock *FalseBB = BI->getSuccessor(1);
498 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmancacd2012009-02-12 22:19:27 +0000499
Dan Gohmancecc80f2009-02-14 02:31:09 +0000500 // Canonicalize a constant to the RHS.
501 if (isa<ConstantInt>(CmpLHS)) {
502 Pred = ICmpInst::getSwappedPredicate(Pred);
503 std::swap(CmpLHS, CmpRHS);
504 }
505 // Canonicalize SLE to SLT.
506 if (Pred == ICmpInst::ICMP_SLE)
507 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
508 if (!CI->getValue().isMaxSignedValue()) {
509 CmpRHS = ConstantInt::get(CI->getValue() + 1);
510 Pred = ICmpInst::ICMP_SLT;
511 }
512 // Canonicalize SGT to SGE.
513 if (Pred == ICmpInst::ICMP_SGT)
514 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
515 if (!CI->getValue().isMaxSignedValue()) {
516 CmpRHS = ConstantInt::get(CI->getValue() + 1);
517 Pred = ICmpInst::ICMP_SGE;
518 }
519 // Canonicalize SGE to SLT.
520 if (Pred == ICmpInst::ICMP_SGE) {
521 std::swap(TrueBB, FalseBB);
522 Pred = ICmpInst::ICMP_SLT;
523 }
524 // Canonicalize ULE to ULT.
525 if (Pred == ICmpInst::ICMP_ULE)
526 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
527 if (!CI->getValue().isMaxValue()) {
528 CmpRHS = ConstantInt::get(CI->getValue() + 1);
529 Pred = ICmpInst::ICMP_ULT;
530 }
531 // Canonicalize UGT to UGE.
532 if (Pred == ICmpInst::ICMP_UGT)
533 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
534 if (!CI->getValue().isMaxValue()) {
535 CmpRHS = ConstantInt::get(CI->getValue() + 1);
536 Pred = ICmpInst::ICMP_UGE;
537 }
538 // Canonicalize UGE to ULT.
539 if (Pred == ICmpInst::ICMP_UGE) {
540 std::swap(TrueBB, FalseBB);
541 Pred = ICmpInst::ICMP_ULT;
542 }
543 // For now, analyze only LT loops for signed overflow.
544 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
Dan Gohmana730da32009-02-18 00:52:00 +0000545 return 0;
Dan Gohmancecc80f2009-02-14 02:31:09 +0000546
547 bool isSigned = Pred == ICmpInst::ICMP_SLT;
548
549 // Get the increment instruction. Look past casts if we will
Dan Gohmancacd2012009-02-12 22:19:27 +0000550 // be able to prove that the original induction variable doesn't
Dan Gohmancecc80f2009-02-14 02:31:09 +0000551 // undergo signed or unsigned overflow, respectively.
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000552 const Value *IncrInst = CmpLHS;
Dan Gohmancecc80f2009-02-14 02:31:09 +0000553 if (isSigned) {
554 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
555 if (!isa<ConstantInt>(CmpRHS) ||
556 !cast<ConstantInt>(CmpRHS)->getValue()
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000557 .isSignedIntN(IncrInst->getType()->getPrimitiveSizeInBits()))
Dan Gohmana730da32009-02-18 00:52:00 +0000558 return 0;
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000559 IncrInst = SI->getOperand(0);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000560 }
561 } else {
562 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
563 if (!isa<ConstantInt>(CmpRHS) ||
564 !cast<ConstantInt>(CmpRHS)->getValue()
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000565 .isIntN(IncrInst->getType()->getPrimitiveSizeInBits()))
Dan Gohmana730da32009-02-18 00:52:00 +0000566 return 0;
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000567 IncrInst = ZI->getOperand(0);
Dan Gohmancecc80f2009-02-14 02:31:09 +0000568 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000569 }
570
571 // For now, only analyze induction variables that have simple increments.
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000572 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrInst);
573 if (!IncrOp || IncrOp->getOpcode() != Instruction::Add)
574 return 0;
575 IncrVal = dyn_cast<ConstantInt>(IncrOp->getOperand(1));
576 if (!IncrVal)
Dan Gohmana730da32009-02-18 00:52:00 +0000577 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000578
579 // Make sure the PHI looks like a normal IV.
580 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
581 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmana730da32009-02-18 00:52:00 +0000582 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000583 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
584 unsigned BackEdge = !IncomingEdge;
585 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
586 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmana730da32009-02-18 00:52:00 +0000587 return 0;
Dan Gohmancecc80f2009-02-14 02:31:09 +0000588 if (!L->contains(TrueBB))
Dan Gohmana730da32009-02-18 00:52:00 +0000589 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000590
591 // For now, only analyze loops with a constant start value, so that
Dan Gohmancecc80f2009-02-14 02:31:09 +0000592 // we can easily determine if the start value is not a maximum value
593 // which would wrap on the first iteration.
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000594 InitialVal = dyn_cast<ConstantInt>(PN->getIncomingValue(IncomingEdge));
Dan Gohman6f2a83e2009-02-18 16:54:33 +0000595 if (!InitialVal)
Dan Gohmana730da32009-02-18 00:52:00 +0000596 return 0;
Dan Gohmancacd2012009-02-12 22:19:27 +0000597
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000598 // The upper limit need not be a constant; we'll check later.
599 LimitVal = dyn_cast<ConstantInt>(CmpRHS);
600
601 // We detect the impossibility of wrapping in two cases, both of
602 // which require starting with a non-max value:
603 // - The IV counts up by one, and the loop iterates only while it remains
604 // less than a limiting value (any) in the same type.
605 // - The IV counts up by a positive increment other than 1, and the
606 // constant limiting value + the increment is less than the max value
607 // (computed as max-increment to avoid overflow)
Dan Gohmana5d38012009-02-18 17:22:41 +0000608 if (isSigned && !InitialVal->getValue().isMaxSignedValue()) {
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000609 if (IncrVal->equalsInt(1))
610 NoSignedWrap = true; // LimitVal need not be constant
611 else if (LimitVal) {
612 uint64_t numBits = LimitVal->getValue().getBitWidth();
613 if (IncrVal->getValue().sgt(APInt::getNullValue(numBits)) &&
614 (APInt::getSignedMaxValue(numBits) - IncrVal->getValue())
615 .sgt(LimitVal->getValue()))
616 NoSignedWrap = true;
617 }
618 } else if (!isSigned && !InitialVal->getValue().isMaxValue()) {
619 if (IncrVal->equalsInt(1))
620 NoUnsignedWrap = true; // LimitVal need not be constant
621 else if (LimitVal) {
622 uint64_t numBits = LimitVal->getValue().getBitWidth();
623 if (IncrVal->getValue().ugt(APInt::getNullValue(numBits)) &&
624 (APInt::getMaxValue(numBits) - IncrVal->getValue())
625 .ugt(LimitVal->getValue()))
626 NoUnsignedWrap = true;
627 }
628 }
Dan Gohmana730da32009-02-18 00:52:00 +0000629 return PN;
Dan Gohmancacd2012009-02-12 22:19:27 +0000630}
631
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000632static Value *getSignExtendedTruncVar(const SCEVAddRecExpr *AR,
633 ScalarEvolution *SE,
634 const Type *LargestType, Loop *L,
635 const Type *myType,
636 SCEVExpander &Rewriter,
637 BasicBlock::iterator InsertPt) {
638 SCEVHandle ExtendedStart =
639 SE->getSignExtendExpr(AR->getStart(), LargestType);
640 SCEVHandle ExtendedStep =
641 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
642 SCEVHandle ExtendedAddRec =
643 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
644 if (LargestType != myType)
645 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, myType);
646 return Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
647}
648
649static Value *getZeroExtendedTruncVar(const SCEVAddRecExpr *AR,
650 ScalarEvolution *SE,
651 const Type *LargestType, Loop *L,
652 const Type *myType,
653 SCEVExpander &Rewriter,
654 BasicBlock::iterator InsertPt) {
655 SCEVHandle ExtendedStart =
656 SE->getZeroExtendExpr(AR->getStart(), LargestType);
657 SCEVHandle ExtendedStep =
658 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
659 SCEVHandle ExtendedAddRec =
660 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
661 if (LargestType != myType)
662 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, myType);
663 return Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
664}
665
Dan Gohmancacd2012009-02-12 22:19:27 +0000666bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667 LI = &getAnalysis<LoopInfo>();
668 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 Changed = false;
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000670
671 // If there are any floating-point or pointer recurrences, attempt to
672 // transform them to use integer recurrences.
673 RewriteNonIntegerIVs(L);
674
Dan Gohmancacd2012009-02-12 22:19:27 +0000675 BasicBlock *Header = L->getHeader();
676 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000677 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmancacd2012009-02-12 22:19:27 +0000678
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000679 // Verify the input to the pass in already in LCSSA form.
680 assert(L->isLCSSAForm());
681
682 // Check to see if this loop has a computable loop-invariant execution count.
683 // If so, this means that we can compute the final value of any expressions
684 // that are recurrent in the loop, and substitute the exit values from the
685 // loop into any instructions outside of the loop that use the final values of
686 // the current expressions.
687 //
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000688 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
689 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
690 RewriteLoopExitValues(L, BackedgeTakenCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691
692 // Next, analyze all of the induction variables in the loop, canonicalizing
693 // auxillary induction variables.
694 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
695
696 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
697 PHINode *PN = cast<PHINode>(I);
698 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
699 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohman173d9142009-02-14 02:25:19 +0000700 // FIXME: It is an extremely bad idea to indvar substitute anything more
701 // complex than affine induction variables. Doing so will put expensive
702 // polynomial evaluations inside of the loop, and the str reduction pass
703 // currently can only reduce affine polynomials. For now just disable
704 // indvar subst on anything more complex than an affine addrec.
705 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
706 if (AR->getLoop() == L && AR->isAffine())
707 IndVars.push_back(std::make_pair(PN, SCEV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000708 }
709 }
710
Dan Gohmancacd2012009-02-12 22:19:27 +0000711 // Compute the type of the largest recurrence expression, and collect
712 // the set of the types of the other recurrence expressions.
713 const Type *LargestType = 0;
714 SmallSetVector<const Type *, 4> SizesToInsert;
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000715 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
716 LargestType = BackedgeTakenCount->getType();
717 SizesToInsert.insert(BackedgeTakenCount->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000719 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
720 const PHINode *PN = IndVars[i].first;
721 SizesToInsert.insert(PN->getType());
722 const Type *EffTy = getEffectiveIndvarType(PN);
723 SizesToInsert.insert(EffTy);
724 if (!LargestType ||
725 EffTy->getPrimitiveSizeInBits() >
726 LargestType->getPrimitiveSizeInBits())
727 LargestType = EffTy;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000728 }
729
730 // Create a rewriter object which we'll use to transform the code with.
731 SCEVExpander Rewriter(*SE, *LI);
732
733 // Now that we know the largest of of the induction variables in this loop,
734 // insert a canonical induction variable of the largest size.
Dan Gohmancacd2012009-02-12 22:19:27 +0000735 Value *IndVar = 0;
736 if (!SizesToInsert.empty()) {
737 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
738 ++NumInserted;
739 Changed = true;
740 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 }
742
Dan Gohmancacd2012009-02-12 22:19:27 +0000743 // If we have a trip count expression, rewrite the loop's exit condition
744 // using it. We can currently only handle loops with a single exit.
Dan Gohmancecc80f2009-02-14 02:31:09 +0000745 bool NoSignedWrap = false;
746 bool NoUnsignedWrap = false;
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000747 const ConstantInt* InitialVal, * IncrVal, * LimitVal;
Dan Gohmana730da32009-02-18 00:52:00 +0000748 const PHINode *OrigControllingPHI = 0;
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000749 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock)
Dan Gohmancacd2012009-02-12 22:19:27 +0000750 // Can't rewrite non-branch yet.
751 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
752 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmancecc80f2009-02-14 02:31:09 +0000753 // Determine if the OrigIV will ever undergo overflow.
Dan Gohmana730da32009-02-18 00:52:00 +0000754 OrigControllingPHI =
755 TestOrigIVForWrap(L, BI, OrigCond,
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000756 NoSignedWrap, NoUnsignedWrap,
757 InitialVal, IncrVal, LimitVal);
Dan Gohmancacd2012009-02-12 22:19:27 +0000758
759 // We'll be replacing the original condition, so it'll be dead.
760 DeadInsts.insert(OrigCond);
761 }
762
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000763 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
Dan Gohmanebac2542009-02-23 23:20:35 +0000764 ExitingBlock, BI, Rewriter);
Dan Gohmancacd2012009-02-12 22:19:27 +0000765 }
766
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 // Now that we have a canonical induction variable, we can rewrite any
768 // recurrences in terms of the induction variable. Start with the auxillary
769 // induction variables, and recursively rewrite any of their uses.
Dan Gohman514277c2008-05-23 21:05:58 +0000770 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771
772 // If there were induction variables of other sizes, cast the primary
773 // induction variable to the right size for them, avoiding the need for the
774 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmancacd2012009-02-12 22:19:27 +0000775 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
776 const Type *Ty = SizesToInsert[i];
777 if (Ty != LargestType) {
778 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
779 Rewriter.addInsertedValue(New, SE->getSCEV(New));
780 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
781 << *New << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782 }
783 }
784
785 // Rewrite all induction variables in terms of the canonical induction
786 // variable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 while (!IndVars.empty()) {
788 PHINode *PN = IndVars.back().first;
Dan Gohmanc71cac12009-02-17 00:10:53 +0000789 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
790 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
791 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000792 << " into = " << *NewVal << "\n";
793 NewVal->takeName(PN);
794
Dan Gohmancacd2012009-02-12 22:19:27 +0000795 /// If the new canonical induction variable is wider than the original,
796 /// and the original has uses that are casts to wider types, see if the
797 /// truncate and extend can be omitted.
Dan Gohmana730da32009-02-18 00:52:00 +0000798 if (PN == OrigControllingPHI && PN->getType() != LargestType)
Dan Gohmancacd2012009-02-12 22:19:27 +0000799 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmancecc80f2009-02-14 02:31:09 +0000800 UI != UE; ++UI) {
Dale Johannesencb91b762009-04-15 20:41:02 +0000801 Instruction *UInst = dyn_cast<Instruction>(*UI);
802 if (UInst && isa<SExtInst>(UInst) && NoSignedWrap) {
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000803 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType, L,
Dale Johannesencb91b762009-04-15 20:41:02 +0000804 UInst->getType(), Rewriter, InsertPt);
805 UInst->replaceAllUsesWith(TruncIndVar);
806 DeadInsts.insert(UInst);
Dan Gohmancacd2012009-02-12 22:19:27 +0000807 }
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000808 // See if we can figure out sext(i+constant) doesn't wrap, so we can
809 // use a larger add. This is common in subscripting.
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000810 if (UInst && UInst->getOpcode()==Instruction::Add &&
811 UInst->hasOneUse() &&
812 isa<ConstantInt>(UInst->getOperand(1)) &&
Dale Johannesencb91b762009-04-15 20:41:02 +0000813 NoSignedWrap && LimitVal) {
814 uint64_t oldBitSize = LimitVal->getValue().getBitWidth();
815 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
816 ConstantInt* AddRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
817 if (((APInt::getSignedMaxValue(oldBitSize) - IncrVal->getValue()) -
818 AddRHS->getValue()).sgt(LimitVal->getValue())) {
819 // We've determined this is (i+constant) and it won't overflow.
820 if (isa<SExtInst>(UInst->use_begin())) {
821 SExtInst* oldSext = dyn_cast<SExtInst>(UInst->use_begin());
822 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
823 L, oldSext->getType(), Rewriter,
824 InsertPt);
825 APInt APcopy = APInt(AddRHS->getValue());
826 ConstantInt* newAddRHS =ConstantInt::get(APcopy.sext(newBitSize));
827 Value *NewAdd =
828 BinaryOperator::CreateAdd(TruncIndVar, newAddRHS,
829 UInst->getName()+".nosex", UInst);
830 oldSext->replaceAllUsesWith(NewAdd);
831 if (Instruction *DeadUse = dyn_cast<Instruction>(oldSext))
832 DeadInsts.insert(DeadUse);
833 DeadInsts.insert(UInst);
834 }
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000835 }
836 }
Dale Johannesencb91b762009-04-15 20:41:02 +0000837 if (UInst && isa<ZExtInst>(UInst) && NoUnsignedWrap) {
Dale Johannesenb6f383e2009-04-15 01:10:12 +0000838 Value *TruncIndVar = getZeroExtendedTruncVar(AR, SE, LargestType, L,
Dale Johannesencb91b762009-04-15 20:41:02 +0000839 UInst->getType(), Rewriter, InsertPt);
840 UInst->replaceAllUsesWith(TruncIndVar);
841 DeadInsts.insert(UInst);
842 }
843 // If we have zext(i&constant), we can use the larger variable. This
844 // is not common but is a bottleneck in Openssl.
845 // (RHS doesn't have to be constant. There should be a better approach
846 // than bottom-up pattern matching for this...)
847 if (UInst && UInst->getOpcode()==Instruction::And &&
848 UInst->hasOneUse() &&
849 isa<ConstantInt>(UInst->getOperand(1)) &&
850 isa<ZExtInst>(UInst->use_begin())) {
851 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
852 ConstantInt* AndRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
853 ZExtInst* oldZext = dyn_cast<ZExtInst>(UInst->use_begin());
854 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
855 L, oldZext->getType(), Rewriter, InsertPt);
856 APInt APcopy = APInt(AndRHS->getValue());
857 ConstantInt* newAndRHS = ConstantInt::get(APcopy.zext(newBitSize));
858 Value *NewAnd =
859 BinaryOperator::CreateAnd(TruncIndVar, newAndRHS,
860 UInst->getName()+".nozex", UInst);
861 oldZext->replaceAllUsesWith(NewAnd);
862 if (Instruction *DeadUse = dyn_cast<Instruction>(oldZext))
Dan Gohmancecc80f2009-02-14 02:31:09 +0000863 DeadInsts.insert(DeadUse);
Dale Johannesencb91b762009-04-15 20:41:02 +0000864 DeadInsts.insert(UInst);
865 }
866 // If we have zext((i+constant)&constant), we can use the larger
867 // variable even if the add does overflow. This works whenever the
868 // constant being ANDed is the same size as i, which it presumably is.
869 // We don't need to restrict the expression being and'ed to i+const,
870 // but we have to promote everything in it, so it's convenient.
871 if (UInst && UInst->getOpcode()==Instruction::Add &&
872 UInst->hasOneUse() &&
873 isa<ConstantInt>(UInst->getOperand(1))) {
874 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
875 ConstantInt* AddRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
876 Instruction *UInst2 = dyn_cast<Instruction>(UInst->use_begin());
877 if (UInst2 && UInst2->getOpcode() == Instruction::And &&
878 UInst2->hasOneUse() &&
879 isa<ConstantInt>(UInst2->getOperand(1)) &&
880 isa<ZExtInst>(UInst2->use_begin())) {
881 ZExtInst* oldZext = dyn_cast<ZExtInst>(UInst2->use_begin());
882 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
883 L, oldZext->getType(), Rewriter, InsertPt);
884 ConstantInt* AndRHS = dyn_cast<ConstantInt>(UInst2->getOperand(1));
885 APInt APcopy = APInt(AddRHS->getValue());
886 ConstantInt* newAddRHS = ConstantInt::get(APcopy.zext(newBitSize));
887 Value *NewAdd =
888 BinaryOperator::CreateAdd(TruncIndVar, newAddRHS,
889 UInst->getName()+".nozex", UInst2);
890 APInt APcopy2 = APInt(AndRHS->getValue());
891 ConstantInt* newAndRHS = ConstantInt::get(APcopy2.zext(newBitSize));
892 Value *NewAnd =
893 BinaryOperator::CreateAnd(NewAdd, newAndRHS,
894 UInst->getName()+".nozex", UInst2);
895 oldZext->replaceAllUsesWith(NewAnd);
896 if (Instruction *DeadUse = dyn_cast<Instruction>(oldZext))
897 DeadInsts.insert(DeadUse);
898 DeadInsts.insert(UInst);
899 DeadInsts.insert(UInst2);
900 }
Dan Gohmancecc80f2009-02-14 02:31:09 +0000901 }
902 }
Dan Gohmancacd2012009-02-12 22:19:27 +0000903
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000904 // Replace the old PHI Node with the inserted computation.
905 PN->replaceAllUsesWith(NewVal);
906 DeadInsts.insert(PN);
907 IndVars.pop_back();
908 ++NumRemoved;
909 Changed = true;
910 }
911
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 DeleteTriviallyDeadInstructions(DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913 assert(L->isLCSSAForm());
914 return Changed;
915}
Devang Patelbda43802008-09-09 21:41:07 +0000916
Devang Patelb8ccf572008-11-18 00:40:02 +0000917/// Return true if it is OK to use SIToFPInst for an inducation variable
918/// with given inital and exit values.
919static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
920 uint64_t intIV, uint64_t intEV) {
921
Dan Gohman963fc812009-02-17 19:13:57 +0000922 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patelb8ccf572008-11-18 00:40:02 +0000923 return true;
924
925 // If the iteration range can be handled by SIToFPInst then use it.
926 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendlingb9a5a682008-11-18 10:57:27 +0000927 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patelb8ccf572008-11-18 00:40:02 +0000928 return true;
Dan Gohman963fc812009-02-17 19:13:57 +0000929
Devang Patelb8ccf572008-11-18 00:40:02 +0000930 return false;
931}
932
933/// convertToInt - Convert APF to an integer, if possible.
Devang Patele2ba01d2008-11-17 23:27:13 +0000934static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
935
936 bool isExact = false;
Evan Cheng30e65f62008-11-26 01:11:57 +0000937 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
938 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000939 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patele2ba01d2008-11-17 23:27:13 +0000940 APFloat::rmTowardZero, &isExact)
941 != APFloat::opOK)
942 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000943 if (!isExact)
Devang Patele2ba01d2008-11-17 23:27:13 +0000944 return false;
945 return true;
946
947}
948
Devang Patel7ca23c92008-11-03 18:32:19 +0000949/// HandleFloatingPointIV - If the loop has floating induction variable
950/// then insert corresponding integer induction variable if possible.
Devang Patelc8dac622008-11-17 21:32:02 +0000951/// For example,
952/// for(double i = 0; i < 10000; ++i)
953/// bar(i)
954/// is converted into
955/// for(int i = 0; i < 10000; ++i)
956/// bar((double)i);
957///
Dan Gohman963fc812009-02-17 19:13:57 +0000958void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patelc8dac622008-11-17 21:32:02 +0000959 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel7ca23c92008-11-03 18:32:19 +0000960
Devang Patelc8dac622008-11-17 21:32:02 +0000961 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
962 unsigned BackEdge = IncomingEdge^1;
Dan Gohman963fc812009-02-17 19:13:57 +0000963
Devang Patelc8dac622008-11-17 21:32:02 +0000964 // Check incoming value.
Devang Patele2ba01d2008-11-17 23:27:13 +0000965 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
966 if (!InitValue) return;
967 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
968 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
969 return;
970
971 // Check IV increment. Reject this PH if increement operation is not
972 // an add or increment value can not be represented by an integer.
Dan Gohman963fc812009-02-17 19:13:57 +0000973 BinaryOperator *Incr =
Devang Patelc8dac622008-11-17 21:32:02 +0000974 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
975 if (!Incr) return;
976 if (Incr->getOpcode() != Instruction::Add) return;
977 ConstantFP *IncrValue = NULL;
978 unsigned IncrVIndex = 1;
979 if (Incr->getOperand(1) == PH)
980 IncrVIndex = 0;
981 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
982 if (!IncrValue) return;
Devang Patele2ba01d2008-11-17 23:27:13 +0000983 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
984 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
985 return;
Dan Gohman963fc812009-02-17 19:13:57 +0000986
Devang Patele2ba01d2008-11-17 23:27:13 +0000987 // Check Incr uses. One user is PH and the other users is exit condition used
988 // by the conditional terminator.
Devang Patelc8dac622008-11-17 21:32:02 +0000989 Value::use_iterator IncrUse = Incr->use_begin();
990 Instruction *U1 = cast<Instruction>(IncrUse++);
991 if (IncrUse == Incr->use_end()) return;
992 Instruction *U2 = cast<Instruction>(IncrUse++);
993 if (IncrUse != Incr->use_end()) return;
Dan Gohman963fc812009-02-17 19:13:57 +0000994
Devang Patelc8dac622008-11-17 21:32:02 +0000995 // Find exit condition.
996 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
997 if (!EC)
998 EC = dyn_cast<FCmpInst>(U2);
999 if (!EC) return;
1000
1001 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
1002 if (!BI->isConditional()) return;
1003 if (BI->getCondition() != EC) return;
Devang Patel7ca23c92008-11-03 18:32:19 +00001004 }
Devang Patel7ca23c92008-11-03 18:32:19 +00001005
Devang Patele2ba01d2008-11-17 23:27:13 +00001006 // Find exit value. If exit value can not be represented as an interger then
1007 // do not handle this floating point PH.
Devang Patelc8dac622008-11-17 21:32:02 +00001008 ConstantFP *EV = NULL;
1009 unsigned EVIndex = 1;
1010 if (EC->getOperand(1) == Incr)
1011 EVIndex = 0;
1012 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
1013 if (!EV) return;
Devang Patelc8dac622008-11-17 21:32:02 +00001014 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patele2ba01d2008-11-17 23:27:13 +00001015 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patelc8dac622008-11-17 21:32:02 +00001016 return;
Dan Gohman963fc812009-02-17 19:13:57 +00001017
Devang Patelc8dac622008-11-17 21:32:02 +00001018 // Find new predicate for integer comparison.
1019 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
1020 switch (EC->getPredicate()) {
1021 case CmpInst::FCMP_OEQ:
1022 case CmpInst::FCMP_UEQ:
1023 NewPred = CmpInst::ICMP_EQ;
1024 break;
1025 case CmpInst::FCMP_OGT:
1026 case CmpInst::FCMP_UGT:
1027 NewPred = CmpInst::ICMP_UGT;
1028 break;
1029 case CmpInst::FCMP_OGE:
1030 case CmpInst::FCMP_UGE:
1031 NewPred = CmpInst::ICMP_UGE;
1032 break;
1033 case CmpInst::FCMP_OLT:
1034 case CmpInst::FCMP_ULT:
1035 NewPred = CmpInst::ICMP_ULT;
1036 break;
1037 case CmpInst::FCMP_OLE:
1038 case CmpInst::FCMP_ULE:
1039 NewPred = CmpInst::ICMP_ULE;
1040 break;
1041 default:
1042 break;
Devang Patel7ca23c92008-11-03 18:32:19 +00001043 }
Devang Patelc8dac622008-11-17 21:32:02 +00001044 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohman963fc812009-02-17 19:13:57 +00001045
Devang Patelc8dac622008-11-17 21:32:02 +00001046 // Insert new integer induction variable.
1047 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
1048 PH->getName()+".int", PH);
Devang Patele2ba01d2008-11-17 23:27:13 +00001049 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patelc8dac622008-11-17 21:32:02 +00001050 PH->getIncomingBlock(IncomingEdge));
1051
Dan Gohman963fc812009-02-17 19:13:57 +00001052 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
1053 ConstantInt::get(Type::Int32Ty,
Devang Patele2ba01d2008-11-17 23:27:13 +00001054 newIncrValue),
Devang Patelc8dac622008-11-17 21:32:02 +00001055 Incr->getName()+".int", Incr);
1056 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
1057
1058 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
1059 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
1060 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
Dan Gohman963fc812009-02-17 19:13:57 +00001061 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patelc8dac622008-11-17 21:32:02 +00001062 EC->getParent()->getTerminator());
Dan Gohman963fc812009-02-17 19:13:57 +00001063
Devang Patelc8dac622008-11-17 21:32:02 +00001064 // Delete old, floating point, exit comparision instruction.
1065 EC->replaceAllUsesWith(NewEC);
1066 DeadInsts.insert(EC);
Dan Gohman963fc812009-02-17 19:13:57 +00001067
Devang Patelc8dac622008-11-17 21:32:02 +00001068 // Delete old, floating point, increment instruction.
1069 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
1070 DeadInsts.insert(Incr);
Dan Gohman963fc812009-02-17 19:13:57 +00001071
Devang Patelb8ccf572008-11-18 00:40:02 +00001072 // Replace floating induction variable. Give SIToFPInst preference over
1073 // UIToFPInst because it is faster on platforms that are widely used.
1074 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Dan Gohman963fc812009-02-17 19:13:57 +00001075 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patele2ba01d2008-11-17 23:27:13 +00001076 PH->getParent()->getFirstNonPHI());
1077 PH->replaceAllUsesWith(Conv);
1078 } else {
Dan Gohman963fc812009-02-17 19:13:57 +00001079 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patele2ba01d2008-11-17 23:27:13 +00001080 PH->getParent()->getFirstNonPHI());
1081 PH->replaceAllUsesWith(Conv);
1082 }
Devang Patelc8dac622008-11-17 21:32:02 +00001083 DeadInsts.insert(PH);
Devang Patel7ca23c92008-11-03 18:32:19 +00001084}
1085