blob: 2af10a6f7b2912cfde0a04a1df5723f9a8cd7a0c [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"
Chris Lattnerb25465e2008-11-16 07:17:51 +000056#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057#include "llvm/ADT/Statistic.h"
58using namespace llvm;
59
60STATISTIC(NumRemoved , "Number of aux indvars removed");
61STATISTIC(NumPointer , "Number of pointer indvars promoted");
62STATISTIC(NumInserted, "Number of canonical indvars added");
63STATISTIC(NumReplaced, "Number of exit values replaced");
64STATISTIC(NumLFTR , "Number of loop exit tests replaced");
65
66namespace {
67 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
68 LoopInfo *LI;
69 ScalarEvolution *SE;
70 bool Changed;
71 public:
72
73 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000074 IndVarSimplify() : LoopPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075
76 bool runOnLoop(Loop *L, LPPassManager &LPM);
77 bool doInitialization(Loop *L, LPPassManager &LPM);
78 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patele6a8d482007-09-10 18:08:23 +000079 AU.addRequired<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080 AU.addRequiredID(LCSSAID);
81 AU.addRequiredID(LoopSimplifyID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 AU.addRequired<LoopInfo>();
83 AU.addPreservedID(LoopSimplifyID);
84 AU.addPreservedID(LCSSAID);
85 AU.setPreservesCFG();
86 }
87
88 private:
89
90 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattnerb25465e2008-11-16 07:17:51 +000091 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000092 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
93 SCEVExpander &RW);
Dan Gohmand8dc3bb2008-08-05 22:34:21 +000094 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095
Chris Lattnerb25465e2008-11-16 07:17:51 +000096 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Patelbda43802008-09-09 21:41:07 +000097
98 void OptimizeCanonicalIVType(Loop *L);
Devang Patel7ca23c92008-11-03 18:32:19 +000099 void HandleFloatingPointIV(Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101}
102
Dan Gohman089efff2008-05-13 00:00:25 +0000103char IndVarSimplify::ID = 0;
104static RegisterPass<IndVarSimplify>
105X("indvars", "Canonicalize Induction Variables");
106
Daniel Dunbar163555a2008-10-22 23:32:42 +0000107Pass *llvm::createIndVarSimplifyPass() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 return new IndVarSimplify();
109}
110
111/// DeleteTriviallyDeadInstructions - If any of the instructions is the
112/// specified set are trivially dead, delete them and see if this makes any of
113/// their operands subsequently dead.
114void IndVarSimplify::
Chris Lattnerb25465e2008-11-16 07:17:51 +0000115DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116 while (!Insts.empty()) {
117 Instruction *I = *Insts.begin();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000118 Insts.erase(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119 if (isInstructionTriviallyDead(I)) {
120 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
121 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
122 Insts.insert(U);
123 SE->deleteValueFromRecords(I);
124 DOUT << "INDVARS: Deleting: " << *I;
125 I->eraseFromParent();
126 Changed = true;
127 }
128 }
129}
130
131
132/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
133/// recurrence. If so, change it into an integer recurrence, permitting
134/// analysis by the SCEV routines.
135void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
136 BasicBlock *Preheader,
Chris Lattnerb25465e2008-11-16 07:17:51 +0000137 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
139 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
140 unsigned BackedgeIdx = PreheaderIdx^1;
141 if (GetElementPtrInst *GEPI =
142 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
143 if (GEPI->getOperand(0) == PN) {
144 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
145 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
146
147 // Okay, we found a pointer recurrence. Transform this pointer
148 // recurrence into an integer recurrence. Compute the value that gets
149 // added to the pointer at every iteration.
150 Value *AddedVal = GEPI->getOperand(1);
151
152 // Insert a new integer PHI node into the top of the block.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000153 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
154 PN->getName()+".rec", PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
156
157 // Create the new add instruction.
Gabor Greifa645dd32008-05-16 19:29:10 +0000158 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 GEPI->getName()+".rec", GEPI);
160 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
161
162 // Update the existing GEP to use the recurrence.
163 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
164
165 // Update the GEP to use the new recurrence we just inserted.
166 GEPI->setOperand(1, NewAdd);
167
168 // If the incoming value is a constant expr GEP, try peeling out the array
169 // 0 index if possible to make things simpler.
170 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
171 if (CE->getOpcode() == Instruction::GetElementPtr) {
172 unsigned NumOps = CE->getNumOperands();
173 assert(NumOps > 1 && "CE folding didn't work!");
174 if (CE->getOperand(NumOps-1)->isNullValue()) {
175 // Check to make sure the last index really is an array index.
176 gep_type_iterator GTI = gep_type_begin(CE);
177 for (unsigned i = 1, e = CE->getNumOperands()-1;
178 i != e; ++i, ++GTI)
179 /*empty*/;
180 if (isa<SequentialType>(*GTI)) {
181 // Pull the last index out of the constant expr GEP.
182 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
183 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
184 &CEIdxs[0],
185 CEIdxs.size());
David Greene393be882007-09-04 15:46:09 +0000186 Value *Idx[2];
187 Idx[0] = Constant::getNullValue(Type::Int32Ty);
188 Idx[1] = NewAdd;
Gabor Greifd6da1d02008-04-06 20:25:17 +0000189 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
David Greene393be882007-09-04 15:46:09 +0000190 NCE, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 GEPI->getName(), GEPI);
192 SE->deleteValueFromRecords(GEPI);
193 GEPI->replaceAllUsesWith(NGEPI);
194 GEPI->eraseFromParent();
195 GEPI = NGEPI;
196 }
197 }
198 }
199
200
201 // Finally, if there are any other users of the PHI node, we must
202 // insert a new GEP instruction that uses the pre-incremented version
203 // of the induction amount.
204 if (!PN->use_empty()) {
205 BasicBlock::iterator InsertPos = PN; ++InsertPos;
206 while (isa<PHINode>(InsertPos)) ++InsertPos;
207 Value *PreInc =
Gabor Greifd6da1d02008-04-06 20:25:17 +0000208 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
209 NewPhi, "", InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 PreInc->takeName(PN);
211 PN->replaceAllUsesWith(PreInc);
212 }
213
214 // Delete the old PHI for sure, and the GEP if its otherwise unused.
215 DeadInsts.insert(PN);
216
217 ++NumPointer;
218 Changed = true;
219 }
220}
221
222/// LinearFunctionTestReplace - This method rewrites the exit condition of the
223/// loop to be a canonical != comparison against the incremented loop induction
224/// variable. This pass is able to rewrite the exit tests of any loop where the
225/// SCEV analysis can determine a loop-invariant trip count of the loop, which
226/// is actually a much broader range than just linear tests.
227///
228/// This method returns a "potentially dead" instruction whose computation chain
229/// should be deleted when convenient.
230Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
231 SCEV *IterationCount,
232 SCEVExpander &RW) {
233 // Find the exit block for the loop. We can currently only handle loops with
234 // a single exit.
Devang Patel02451fa2007-08-21 00:31:24 +0000235 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 L->getExitBlocks(ExitBlocks);
237 if (ExitBlocks.size() != 1) return 0;
238 BasicBlock *ExitBlock = ExitBlocks[0];
239
240 // Make sure there is only one predecessor block in the loop.
241 BasicBlock *ExitingBlock = 0;
242 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
243 PI != PE; ++PI)
244 if (L->contains(*PI)) {
245 if (ExitingBlock == 0)
246 ExitingBlock = *PI;
247 else
248 return 0; // Multiple exits from loop to this block.
249 }
250 assert(ExitingBlock && "Loop info is broken");
251
252 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
253 return 0; // Can't rewrite non-branch yet
254 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
255 assert(BI->isConditional() && "Must be conditional to be part of loop!");
256
257 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
258
259 // If the exiting block is not the same as the backedge block, we must compare
260 // against the preincremented value, otherwise we prefer to compare against
261 // the post-incremented value.
262 BasicBlock *Header = L->getHeader();
263 pred_iterator HPI = pred_begin(Header);
264 assert(HPI != pred_end(Header) && "Loop with zero preds???");
265 if (!L->contains(*HPI)) ++HPI;
266 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
267 "No backedge in loop?");
268
269 SCEVHandle TripCount = IterationCount;
270 Value *IndVar;
271 if (*HPI == ExitingBlock) {
272 // The IterationCount expression contains the number of times that the
273 // backedge actually branches to the loop header. This is one less than the
274 // number of times the loop executes, so add one to it.
275 ConstantInt *OneC = ConstantInt::get(IterationCount->getType(), 1);
Dan Gohman89f85052007-10-22 18:31:58 +0000276 TripCount = SE->getAddExpr(IterationCount, SE->getConstant(OneC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277 IndVar = L->getCanonicalInductionVariableIncrement();
278 } else {
279 // We have to use the preincremented value...
280 IndVar = L->getCanonicalInductionVariable();
281 }
282
283 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
284 << " IndVar = " << *IndVar << "\n";
285
286 // Expand the code for the iteration count into the preheader of the loop.
287 BasicBlock *Preheader = L->getLoopPreheader();
288 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator());
289
290 // Insert a new icmp_ne or icmp_eq instruction before the branch.
291 ICmpInst::Predicate Opcode;
292 if (L->contains(BI->getSuccessor(0)))
293 Opcode = ICmpInst::ICMP_NE;
294 else
295 Opcode = ICmpInst::ICMP_EQ;
296
297 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
298 BI->setCondition(Cond);
299 ++NumLFTR;
300 Changed = true;
301 return PotentiallyDeadInst;
302}
303
304
305/// RewriteLoopExitValues - Check to see if this loop has a computable
306/// loop-invariant execution count. If so, this means that we can compute the
307/// final value of any expressions that are recurrent in the loop, and
308/// substitute the exit values from the loop into any instructions outside of
309/// the loop that use the final values of the current expressions.
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000310void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311 BasicBlock *Preheader = L->getLoopPreheader();
312
313 // Scan all of the instructions in the loop, looking at those that have
314 // extra-loop users and which are recurrences.
315 SCEVExpander Rewriter(*SE, *LI);
316
317 // We insert the code into the preheader of the loop if the loop contains
318 // multiple exit blocks, or in the exit block if there is exactly one.
319 BasicBlock *BlockToInsertInto;
Devang Patel02451fa2007-08-21 00:31:24 +0000320 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321 L->getUniqueExitBlocks(ExitBlocks);
322 if (ExitBlocks.size() == 1)
323 BlockToInsertInto = ExitBlocks[0];
324 else
325 BlockToInsertInto = Preheader;
Dan Gohman514277c2008-05-23 21:05:58 +0000326 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000328 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329
Chris Lattnerb25465e2008-11-16 07:17:51 +0000330 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 std::map<Instruction*, Value*> ExitValues;
332
333 // Find all values that are computed inside the loop, but used outside of it.
334 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
335 // the exit blocks of the loop to find them.
336 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
337 BasicBlock *ExitBB = ExitBlocks[i];
338
339 // If there are no PHI nodes in this exit block, then no values defined
340 // inside the loop are used on this path, skip it.
341 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
342 if (!PN) continue;
343
344 unsigned NumPreds = PN->getNumIncomingValues();
345
346 // Iterate over all of the PHI nodes.
347 BasicBlock::iterator BBI = ExitBB->begin();
348 while ((PN = dyn_cast<PHINode>(BBI++))) {
349
350 // Iterate over all of the values in all the PHI nodes.
351 for (unsigned i = 0; i != NumPreds; ++i) {
352 // If the value being merged in is not integer or is not defined
353 // in the loop, skip it.
354 Value *InVal = PN->getIncomingValue(i);
355 if (!isa<Instruction>(InVal) ||
356 // SCEV only supports integer expressions for now.
357 !isa<IntegerType>(InVal->getType()))
358 continue;
359
360 // If this pred is for a subloop, not L itself, skip it.
361 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
362 continue; // The Block is in a subloop, skip it.
363
364 // Check that InVal is defined in the loop.
365 Instruction *Inst = cast<Instruction>(InVal);
366 if (!L->contains(Inst->getParent()))
367 continue;
368
369 // We require that this value either have a computable evolution or that
370 // the loop have a constant iteration count. In the case where the loop
371 // has a constant iteration count, we can sometimes force evaluation of
372 // the exit value through brute force.
373 SCEVHandle SH = SE->getSCEV(Inst);
374 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
375 continue; // Cannot get exit evolution for the loop value.
376
377 // Okay, this instruction has a user outside of the current loop
378 // and varies predictably *inside* the loop. Evaluate the value it
379 // contains when the loop exits, if possible.
380 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
381 if (isa<SCEVCouldNotCompute>(ExitValue) ||
382 !ExitValue->isLoopInvariant(L))
383 continue;
384
385 Changed = true;
386 ++NumReplaced;
387
388 // See if we already computed the exit value for the instruction, if so,
389 // just reuse it.
390 Value *&ExitVal = ExitValues[Inst];
391 if (!ExitVal)
392 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
393
394 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
395 << " LoopVal = " << *Inst << "\n";
396
397 PN->setIncomingValue(i, ExitVal);
398
399 // If this instruction is dead now, schedule it to be removed.
400 if (Inst->use_empty())
401 InstructionsToDelete.insert(Inst);
402
403 // See if this is a single-entry LCSSA PHI node. If so, we can (and
404 // have to) remove
405 // the PHI entirely. This is safe, because the NewVal won't be variant
406 // in the loop, so we don't need an LCSSA phi node anymore.
407 if (NumPreds == 1) {
408 SE->deleteValueFromRecords(PN);
409 PN->replaceAllUsesWith(ExitVal);
410 PN->eraseFromParent();
411 break;
412 }
413 }
414 }
415 }
416
417 DeleteTriviallyDeadInstructions(InstructionsToDelete);
418}
419
420bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
421
422 Changed = false;
423 // First step. Check to see if there are any trivial GEP pointer recurrences.
424 // If there are, change them into integer recurrences, permitting analysis by
425 // the SCEV routines.
426 //
427 BasicBlock *Header = L->getHeader();
428 BasicBlock *Preheader = L->getLoopPreheader();
429 SE = &LPM.getAnalysis<ScalarEvolution>();
430
Chris Lattnerb25465e2008-11-16 07:17:51 +0000431 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
433 PHINode *PN = cast<PHINode>(I);
434 if (isa<PointerType>(PN->getType()))
435 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
436 }
437
438 if (!DeadInsts.empty())
439 DeleteTriviallyDeadInstructions(DeadInsts);
440
441 return Changed;
442}
443
444bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
445
446
447 LI = &getAnalysis<LoopInfo>();
448 SE = &getAnalysis<ScalarEvolution>();
449
450 Changed = false;
451 BasicBlock *Header = L->getHeader();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000452 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453
454 // Verify the input to the pass in already in LCSSA form.
455 assert(L->isLCSSAForm());
456
457 // Check to see if this loop has a computable loop-invariant execution count.
458 // If so, this means that we can compute the final value of any expressions
459 // that are recurrent in the loop, and substitute the exit values from the
460 // loop into any instructions outside of the loop that use the final values of
461 // the current expressions.
462 //
463 SCEVHandle IterationCount = SE->getIterationCount(L);
464 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000465 RewriteLoopExitValues(L, IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000466
467 // Next, analyze all of the induction variables in the loop, canonicalizing
468 // auxillary induction variables.
469 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
470
Devang Patel7ca23c92008-11-03 18:32:19 +0000471 HandleFloatingPointIV(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000472 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
473 PHINode *PN = cast<PHINode>(I);
474 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
475 SCEVHandle SCEV = SE->getSCEV(PN);
476 if (SCEV->hasComputableLoopEvolution(L))
477 // FIXME: It is an extremely bad idea to indvar substitute anything more
478 // complex than affine induction variables. Doing so will put expensive
479 // polynomial evaluations inside of the loop, and the str reduction pass
480 // currently can only reduce affine polynomials. For now just disable
481 // indvar subst on anything more complex than an affine addrec.
482 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
483 if (AR->isAffine())
484 IndVars.push_back(std::make_pair(PN, SCEV));
485 }
486 }
487
488 // If there are no induction variables in the loop, there is nothing more to
489 // do.
490 if (IndVars.empty()) {
491 // Actually, if we know how many times the loop iterates, lets insert a
492 // canonical induction variable to help subsequent passes.
493 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
494 SCEVExpander Rewriter(*SE, *LI);
495 Rewriter.getOrInsertCanonicalInductionVariable(L,
496 IterationCount->getType());
497 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
498 Rewriter)) {
Chris Lattnerb25465e2008-11-16 07:17:51 +0000499 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500 InstructionsToDelete.insert(I);
501 DeleteTriviallyDeadInstructions(InstructionsToDelete);
502 }
503 }
504 return Changed;
505 }
506
507 // Compute the type of the largest recurrence expression.
508 //
509 const Type *LargestType = IndVars[0].first->getType();
510 bool DifferingSizes = false;
511 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
512 const Type *Ty = IndVars[i].first->getType();
513 DifferingSizes |=
514 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
515 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
516 LargestType = Ty;
517 }
518
519 // Create a rewriter object which we'll use to transform the code with.
520 SCEVExpander Rewriter(*SE, *LI);
521
522 // Now that we know the largest of of the induction variables in this loop,
523 // insert a canonical induction variable of the largest size.
524 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
525 ++NumInserted;
526 Changed = true;
527 DOUT << "INDVARS: New CanIV: " << *IndVar;
528
529 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Wojciech Matyjewiczc561c132008-06-13 17:02:03 +0000530 IterationCount = SE->getTruncateOrZeroExtend(IterationCount, LargestType);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
532 DeadInsts.insert(DI);
533 }
534
535 // Now that we have a canonical induction variable, we can rewrite any
536 // recurrences in terms of the induction variable. Start with the auxillary
537 // induction variables, and recursively rewrite any of their uses.
Dan Gohman514277c2008-05-23 21:05:58 +0000538 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539
540 // If there were induction variables of other sizes, cast the primary
541 // induction variable to the right size for them, avoiding the need for the
542 // code evaluation methods to insert induction variables of different sizes.
543 if (DifferingSizes) {
544 SmallVector<unsigned,4> InsertedSizes;
545 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
546 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
547 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
548 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
549 == InsertedSizes.end()) {
550 PHINode *PN = IndVars[i].first;
551 InsertedSizes.push_back(ithSize);
552 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
553 InsertPt);
554 Rewriter.addInsertedValue(New, SE->getSCEV(New));
555 DOUT << "INDVARS: Made trunc IV for " << *PN
556 << " NewVal = " << *New << "\n";
557 }
558 }
559 }
560
561 // Rewrite all induction variables in terms of the canonical induction
562 // variable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000563 while (!IndVars.empty()) {
564 PHINode *PN = IndVars.back().first;
565 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
566 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
567 << " into = " << *NewVal << "\n";
568 NewVal->takeName(PN);
569
570 // Replace the old PHI Node with the inserted computation.
571 PN->replaceAllUsesWith(NewVal);
572 DeadInsts.insert(PN);
573 IndVars.pop_back();
574 ++NumRemoved;
575 Changed = true;
576 }
577
578#if 0
579 // Now replace all derived expressions in the loop body with simpler
580 // expressions.
Dan Gohman4d2e8ae2008-06-22 20:18:58 +0000581 for (LoopInfo::block_iterator I = L->block_begin(), E = L->block_end();
582 I != E; ++I) {
583 BasicBlock *BB = *I;
584 if (LI->getLoopFor(BB) == L) { // Not in a subloop...
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
586 if (I->getType()->isInteger() && // Is an integer instruction
587 !I->use_empty() &&
588 !Rewriter.isInsertedInstruction(I)) {
589 SCEVHandle SH = SE->getSCEV(I);
590 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
591 if (V != I) {
592 if (isa<Instruction>(V))
593 V->takeName(I);
594 I->replaceAllUsesWith(V);
595 DeadInsts.insert(I);
596 ++NumRemoved;
597 Changed = true;
598 }
599 }
600 }
Dan Gohman4d2e8ae2008-06-22 20:18:58 +0000601 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602#endif
603
604 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Patelbda43802008-09-09 21:41:07 +0000605 OptimizeCanonicalIVType(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 assert(L->isLCSSAForm());
607 return Changed;
608}
Devang Patelbda43802008-09-09 21:41:07 +0000609
610/// OptimizeCanonicalIVType - If loop induction variable is always
Devang Patel7c9fc2a2008-09-10 14:49:55 +0000611/// sign or zero extended then extend the type of the induction
Devang Patelbda43802008-09-09 21:41:07 +0000612/// variable.
613void IndVarSimplify::OptimizeCanonicalIVType(Loop *L) {
614 PHINode *PH = L->getCanonicalInductionVariable();
615 if (!PH) return;
616
617 // Check loop iteration count.
618 SCEVHandle IC = SE->getIterationCount(L);
619 if (isa<SCEVCouldNotCompute>(IC)) return;
620 SCEVConstant *IterationCount = dyn_cast<SCEVConstant>(IC);
621 if (!IterationCount) return;
622
623 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
624 unsigned BackEdge = IncomingEdge^1;
625
626 // Check IV uses. If all IV uses are either SEXT or ZEXT (except
627 // IV increment instruction) then this IV is suitable for this
Devang Patel7c9fc2a2008-09-10 14:49:55 +0000628 // transformation.
629 bool isSEXT = false;
Devang Patelbda43802008-09-09 21:41:07 +0000630 BinaryOperator *Incr = NULL;
Devang Patel7c9fc2a2008-09-10 14:49:55 +0000631 const Type *NewType = NULL;
Devang Patelbda43802008-09-09 21:41:07 +0000632 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
633 UI != UE; ++UI) {
634 const Type *CandidateType = NULL;
635 if (ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
636 CandidateType = ZI->getDestTy();
637 else if (SExtInst *SI = dyn_cast<SExtInst>(UI)) {
638 CandidateType = SI->getDestTy();
Devang Patel7c9fc2a2008-09-10 14:49:55 +0000639 isSEXT = true;
Devang Patelbda43802008-09-09 21:41:07 +0000640 }
641 else if ((Incr = dyn_cast<BinaryOperator>(UI))) {
642 // Validate IV increment instruction.
643 if (PH->getIncomingValue(BackEdge) == Incr)
644 continue;
645 }
646 if (!CandidateType) {
647 NewType = NULL;
648 break;
649 }
650 if (!NewType)
651 NewType = CandidateType;
652 else if (NewType != CandidateType) {
653 NewType = NULL;
654 break;
655 }
656 }
657
658 // IV uses are not suitable then avoid this transformation.
659 if (!NewType || !Incr)
660 return;
661
662 // IV increment instruction has two uses, one is loop exit condition
663 // and second is the IV (phi node) itself.
664 ICmpInst *Exit = NULL;
665 for(Value::use_iterator II = Incr->use_begin(), IE = Incr->use_end();
666 II != IE; ++II) {
667 if (PH == *II) continue;
668 Exit = dyn_cast<ICmpInst>(*II);
669 break;
670 }
671 if (!Exit) return;
672 ConstantInt *EV = dyn_cast<ConstantInt>(Exit->getOperand(0));
673 if (!EV)
674 EV = dyn_cast<ConstantInt>(Exit->getOperand(1));
675 if (!EV) return;
676
677 // Check iteration count max value to avoid loops that wrap around IV.
678 APInt ICount = IterationCount->getValue()->getValue();
679 if (ICount.isNegative()) return;
680 uint32_t BW = PH->getType()->getPrimitiveSizeInBits();
681 APInt Max = (isSEXT ? APInt::getSignedMaxValue(BW) : APInt::getMaxValue(BW));
682 if (ICount.getZExtValue() > Max.getZExtValue()) return;
683
684 // Extend IV type.
685
686 SCEVExpander Rewriter(*SE, *LI);
687 Value *NewIV = Rewriter.getOrInsertCanonicalInductionVariable(L,NewType);
688 PHINode *NewPH = cast<PHINode>(NewIV);
689 Instruction *NewIncr = cast<Instruction>(NewPH->getIncomingValue(BackEdge));
690
691 // Replace all SEXT or ZEXT uses.
692 SmallVector<Instruction *, 4> PHUses;
693 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
694 UI != UE; ++UI) {
695 Instruction *I = cast<Instruction>(UI);
696 PHUses.push_back(I);
697 }
698 while (!PHUses.empty()){
699 Instruction *Use = PHUses.back(); PHUses.pop_back();
700 if (Incr == Use) continue;
701
702 SE->deleteValueFromRecords(Use);
703 Use->replaceAllUsesWith(NewIV);
704 Use->eraseFromParent();
705 }
706
707 // Replace exit condition.
708 ConstantInt *NEV = ConstantInt::get(NewType, EV->getZExtValue());
709 Instruction *NE = new ICmpInst(Exit->getPredicate(),
710 NewIncr, NEV, "new.exit",
711 Exit->getParent()->getTerminator());
712 SE->deleteValueFromRecords(Exit);
713 Exit->replaceAllUsesWith(NE);
714 Exit->eraseFromParent();
715
716 // Remove old IV and increment instructions.
717 SE->deleteValueFromRecords(PH);
718 PH->removeIncomingValue((unsigned)0);
719 PH->removeIncomingValue((unsigned)0);
720 SE->deleteValueFromRecords(Incr);
721 Incr->eraseFromParent();
722}
723
Devang Patel7ca23c92008-11-03 18:32:19 +0000724/// HandleFloatingPointIV - If the loop has floating induction variable
725/// then insert corresponding integer induction variable if possible.
726void IndVarSimplify::HandleFloatingPointIV(Loop *L) {
727 BasicBlock *Header = L->getHeader();
728 SmallVector <PHINode *, 4> FPHIs;
729 Instruction *NonPHIInsn = NULL;
730
731 // Collect all floating point IVs first.
732 BasicBlock::iterator I = Header->begin();
733 while(true) {
734 if (!isa<PHINode>(I)) {
735 NonPHIInsn = I;
736 break;
737 }
738 PHINode *PH = cast<PHINode>(I);
739 if (PH->getType()->isFloatingPoint())
740 FPHIs.push_back(PH);
741 ++I;
742 }
743
744 for (SmallVector<PHINode *, 4>::iterator I = FPHIs.begin(), E = FPHIs.end();
745 I != E; ++I) {
746 PHINode *PH = *I;
747 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
748 unsigned BackEdge = IncomingEdge^1;
749
750 // Check incoming value.
751 ConstantFP *CZ = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
752 if (!CZ) continue;
753 APFloat PHInit = CZ->getValueAPF();
754 if (!PHInit.isPosZero()) continue;
755
756 // Check IV increment.
757 BinaryOperator *Incr =
758 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
759 if (!Incr) continue;
760 if (Incr->getOpcode() != Instruction::Add) continue;
761 ConstantFP *IncrValue = NULL;
762 unsigned IncrVIndex = 1;
763 if (Incr->getOperand(1) == PH)
764 IncrVIndex = 0;
765 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
766 if (!IncrValue) continue;
767 APFloat IVAPF = IncrValue->getValueAPF();
768 APFloat One = APFloat(IVAPF.getSemantics(), 1);
769 if (!IVAPF.bitwiseIsEqual(One)) continue;
770
771 // Check Incr uses.
772 Value::use_iterator IncrUse = Incr->use_begin();
773 Instruction *U1 = cast<Instruction>(IncrUse++);
774 if (IncrUse == Incr->use_end()) continue;
775 Instruction *U2 = cast<Instruction>(IncrUse++);
776 if (IncrUse != Incr->use_end()) continue;
777
778 // Find exict condition.
779 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
780 if (!EC)
781 EC = dyn_cast<FCmpInst>(U2);
782 if (!EC) continue;
783 bool skip = false;
784 Instruction *Terminator = EC->getParent()->getTerminator();
785 for(Value::use_iterator ECUI = EC->use_begin(), ECUE = EC->use_end();
786 ECUI != ECUE; ++ECUI) {
787 Instruction *U = cast<Instruction>(ECUI);
788 if (U != Terminator) {
789 skip = true;
790 break;
791 }
792 }
793 if (skip) continue;
794
795 // Find exit value.
796 ConstantFP *EV = NULL;
797 unsigned EVIndex = 1;
798 if (EC->getOperand(1) == Incr)
799 EVIndex = 0;
800 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
801 if (!EV) continue;
802 APFloat EVAPF = EV->getValueAPF();
803 if (EVAPF.isNegative()) continue;
804
805 // Find corresponding integer exit value.
806 uint64_t integerVal = Type::Int32Ty->getPrimitiveSizeInBits();
807 bool isExact = false;
808 if (EVAPF.convertToInteger(&integerVal, 32, false, APFloat::rmTowardZero, &isExact)
809 != APFloat::opOK)
810 continue;
811 if (!isExact) continue;
812
813 // Find new predicate for integer comparison.
814 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
815 switch (EC->getPredicate()) {
816 case CmpInst::FCMP_OEQ:
817 case CmpInst::FCMP_UEQ:
818 NewPred = CmpInst::ICMP_EQ;
819 break;
820 case CmpInst::FCMP_OGT:
821 case CmpInst::FCMP_UGT:
822 NewPred = CmpInst::ICMP_UGT;
823 break;
824 case CmpInst::FCMP_OGE:
825 case CmpInst::FCMP_UGE:
826 NewPred = CmpInst::ICMP_UGE;
827 break;
828 case CmpInst::FCMP_OLT:
829 case CmpInst::FCMP_ULT:
830 NewPred = CmpInst::ICMP_ULT;
831 break;
832 case CmpInst::FCMP_OLE:
833 case CmpInst::FCMP_ULE:
834 NewPred = CmpInst::ICMP_ULE;
835 break;
836 default:
837 break;
838 }
839 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) continue;
840
841 // Insert new integer induction variable.
842 SCEVExpander Rewriter(*SE, *LI);
843 PHINode *NewIV =
844 cast<PHINode>(Rewriter.getOrInsertCanonicalInductionVariable(L,Type::Int32Ty));
845 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, integerVal);
846 Value *LHS = (EVIndex == 1 ? NewIV->getIncomingValue(BackEdge) : NewEV);
847 Value *RHS = (EVIndex == 1 ? NewEV : NewIV->getIncomingValue(BackEdge));
848 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
849 EC->getParent()->getTerminator());
850
851 // Delete old, floating point, exit comparision instruction.
852 SE->deleteValueFromRecords(EC);
853 EC->replaceAllUsesWith(NewEC);
854 EC->eraseFromParent();
855
856 // Delete old, floating point, increment instruction.
857 SE->deleteValueFromRecords(Incr);
858 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
859 Incr->eraseFromParent();
860
861 // Replace floating induction variable.
862 UIToFPInst *Conv = new UIToFPInst(NewIV, PH->getType(), "indvar.conv",
863 NonPHIInsn);
864 PH->replaceAllUsesWith(Conv);
865
866 SE->deleteValueFromRecords(PH);
867 PH->removeIncomingValue((unsigned)0);
868 PH->removeIncomingValue((unsigned)0);
869 }
870}
871