blob: 5d709e50fbbf1ad764aa0893a1a87d35d4631477 [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"
56#include "llvm/ADT/Statistic.h"
57using namespace llvm;
58
59STATISTIC(NumRemoved , "Number of aux indvars removed");
60STATISTIC(NumPointer , "Number of pointer indvars promoted");
61STATISTIC(NumInserted, "Number of canonical indvars added");
62STATISTIC(NumReplaced, "Number of exit values replaced");
63STATISTIC(NumLFTR , "Number of loop exit tests replaced");
64
65namespace {
66 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
67 LoopInfo *LI;
68 ScalarEvolution *SE;
69 bool Changed;
70 public:
71
72 static char ID; // Pass identification, replacement for typeid
73 IndVarSimplify() : LoopPass((intptr_t)&ID) {}
74
75 bool runOnLoop(Loop *L, LPPassManager &LPM);
76 bool doInitialization(Loop *L, LPPassManager &LPM);
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patele6a8d482007-09-10 18:08:23 +000078 AU.addRequired<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079 AU.addRequiredID(LCSSAID);
80 AU.addRequiredID(LoopSimplifyID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081 AU.addRequired<LoopInfo>();
82 AU.addPreservedID(LoopSimplifyID);
83 AU.addPreservedID(LCSSAID);
84 AU.setPreservesCFG();
85 }
86
87 private:
88
89 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
90 std::set<Instruction*> &DeadInsts);
91 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
92 SCEVExpander &RW);
Dan Gohmand8dc3bb2008-08-05 22:34:21 +000093 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094
95 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
96 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097}
98
Dan Gohman089efff2008-05-13 00:00:25 +000099char IndVarSimplify::ID = 0;
100static RegisterPass<IndVarSimplify>
101X("indvars", "Canonicalize Induction Variables");
102
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103LoopPass *llvm::createIndVarSimplifyPass() {
104 return new IndVarSimplify();
105}
106
107/// DeleteTriviallyDeadInstructions - If any of the instructions is the
108/// specified set are trivially dead, delete them and see if this makes any of
109/// their operands subsequently dead.
110void IndVarSimplify::
111DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
112 while (!Insts.empty()) {
113 Instruction *I = *Insts.begin();
114 Insts.erase(Insts.begin());
115 if (isInstructionTriviallyDead(I)) {
116 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
117 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
118 Insts.insert(U);
119 SE->deleteValueFromRecords(I);
120 DOUT << "INDVARS: Deleting: " << *I;
121 I->eraseFromParent();
122 Changed = true;
123 }
124 }
125}
126
127
128/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
129/// recurrence. If so, change it into an integer recurrence, permitting
130/// analysis by the SCEV routines.
131void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
132 BasicBlock *Preheader,
133 std::set<Instruction*> &DeadInsts) {
134 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
135 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
136 unsigned BackedgeIdx = PreheaderIdx^1;
137 if (GetElementPtrInst *GEPI =
138 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
139 if (GEPI->getOperand(0) == PN) {
140 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
141 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
142
143 // Okay, we found a pointer recurrence. Transform this pointer
144 // recurrence into an integer recurrence. Compute the value that gets
145 // added to the pointer at every iteration.
146 Value *AddedVal = GEPI->getOperand(1);
147
148 // Insert a new integer PHI node into the top of the block.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000149 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
150 PN->getName()+".rec", PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
152
153 // Create the new add instruction.
Gabor Greifa645dd32008-05-16 19:29:10 +0000154 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 GEPI->getName()+".rec", GEPI);
156 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
157
158 // Update the existing GEP to use the recurrence.
159 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
160
161 // Update the GEP to use the new recurrence we just inserted.
162 GEPI->setOperand(1, NewAdd);
163
164 // If the incoming value is a constant expr GEP, try peeling out the array
165 // 0 index if possible to make things simpler.
166 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
167 if (CE->getOpcode() == Instruction::GetElementPtr) {
168 unsigned NumOps = CE->getNumOperands();
169 assert(NumOps > 1 && "CE folding didn't work!");
170 if (CE->getOperand(NumOps-1)->isNullValue()) {
171 // Check to make sure the last index really is an array index.
172 gep_type_iterator GTI = gep_type_begin(CE);
173 for (unsigned i = 1, e = CE->getNumOperands()-1;
174 i != e; ++i, ++GTI)
175 /*empty*/;
176 if (isa<SequentialType>(*GTI)) {
177 // Pull the last index out of the constant expr GEP.
178 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
179 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
180 &CEIdxs[0],
181 CEIdxs.size());
David Greene393be882007-09-04 15:46:09 +0000182 Value *Idx[2];
183 Idx[0] = Constant::getNullValue(Type::Int32Ty);
184 Idx[1] = NewAdd;
Gabor Greifd6da1d02008-04-06 20:25:17 +0000185 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
David Greene393be882007-09-04 15:46:09 +0000186 NCE, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 GEPI->getName(), GEPI);
188 SE->deleteValueFromRecords(GEPI);
189 GEPI->replaceAllUsesWith(NGEPI);
190 GEPI->eraseFromParent();
191 GEPI = NGEPI;
192 }
193 }
194 }
195
196
197 // Finally, if there are any other users of the PHI node, we must
198 // insert a new GEP instruction that uses the pre-incremented version
199 // of the induction amount.
200 if (!PN->use_empty()) {
201 BasicBlock::iterator InsertPos = PN; ++InsertPos;
202 while (isa<PHINode>(InsertPos)) ++InsertPos;
203 Value *PreInc =
Gabor Greifd6da1d02008-04-06 20:25:17 +0000204 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
205 NewPhi, "", InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 PreInc->takeName(PN);
207 PN->replaceAllUsesWith(PreInc);
208 }
209
210 // Delete the old PHI for sure, and the GEP if its otherwise unused.
211 DeadInsts.insert(PN);
212
213 ++NumPointer;
214 Changed = true;
215 }
216}
217
218/// LinearFunctionTestReplace - This method rewrites the exit condition of the
219/// loop to be a canonical != comparison against the incremented loop induction
220/// variable. This pass is able to rewrite the exit tests of any loop where the
221/// SCEV analysis can determine a loop-invariant trip count of the loop, which
222/// is actually a much broader range than just linear tests.
223///
224/// This method returns a "potentially dead" instruction whose computation chain
225/// should be deleted when convenient.
226Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
227 SCEV *IterationCount,
228 SCEVExpander &RW) {
229 // Find the exit block for the loop. We can currently only handle loops with
230 // a single exit.
Devang Patel02451fa2007-08-21 00:31:24 +0000231 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 L->getExitBlocks(ExitBlocks);
233 if (ExitBlocks.size() != 1) return 0;
234 BasicBlock *ExitBlock = ExitBlocks[0];
235
236 // Make sure there is only one predecessor block in the loop.
237 BasicBlock *ExitingBlock = 0;
238 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
239 PI != PE; ++PI)
240 if (L->contains(*PI)) {
241 if (ExitingBlock == 0)
242 ExitingBlock = *PI;
243 else
244 return 0; // Multiple exits from loop to this block.
245 }
246 assert(ExitingBlock && "Loop info is broken");
247
248 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
249 return 0; // Can't rewrite non-branch yet
250 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
251 assert(BI->isConditional() && "Must be conditional to be part of loop!");
252
253 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
254
255 // If the exiting block is not the same as the backedge block, we must compare
256 // against the preincremented value, otherwise we prefer to compare against
257 // the post-incremented value.
258 BasicBlock *Header = L->getHeader();
259 pred_iterator HPI = pred_begin(Header);
260 assert(HPI != pred_end(Header) && "Loop with zero preds???");
261 if (!L->contains(*HPI)) ++HPI;
262 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
263 "No backedge in loop?");
264
265 SCEVHandle TripCount = IterationCount;
266 Value *IndVar;
267 if (*HPI == ExitingBlock) {
268 // The IterationCount expression contains the number of times that the
269 // backedge actually branches to the loop header. This is one less than the
270 // number of times the loop executes, so add one to it.
271 ConstantInt *OneC = ConstantInt::get(IterationCount->getType(), 1);
Dan Gohman89f85052007-10-22 18:31:58 +0000272 TripCount = SE->getAddExpr(IterationCount, SE->getConstant(OneC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 IndVar = L->getCanonicalInductionVariableIncrement();
274 } else {
275 // We have to use the preincremented value...
276 IndVar = L->getCanonicalInductionVariable();
277 }
278
279 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
280 << " IndVar = " << *IndVar << "\n";
281
282 // Expand the code for the iteration count into the preheader of the loop.
283 BasicBlock *Preheader = L->getLoopPreheader();
284 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator());
285
286 // Insert a new icmp_ne or icmp_eq instruction before the branch.
287 ICmpInst::Predicate Opcode;
288 if (L->contains(BI->getSuccessor(0)))
289 Opcode = ICmpInst::ICMP_NE;
290 else
291 Opcode = ICmpInst::ICMP_EQ;
292
293 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
294 BI->setCondition(Cond);
295 ++NumLFTR;
296 Changed = true;
297 return PotentiallyDeadInst;
298}
299
300
301/// RewriteLoopExitValues - Check to see if this loop has a computable
302/// loop-invariant execution count. If so, this means that we can compute the
303/// final value of any expressions that are recurrent in the loop, and
304/// substitute the exit values from the loop into any instructions outside of
305/// the loop that use the final values of the current expressions.
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000306void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 BasicBlock *Preheader = L->getLoopPreheader();
308
309 // Scan all of the instructions in the loop, looking at those that have
310 // extra-loop users and which are recurrences.
311 SCEVExpander Rewriter(*SE, *LI);
312
313 // We insert the code into the preheader of the loop if the loop contains
314 // multiple exit blocks, or in the exit block if there is exactly one.
315 BasicBlock *BlockToInsertInto;
Devang Patel02451fa2007-08-21 00:31:24 +0000316 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 L->getUniqueExitBlocks(ExitBlocks);
318 if (ExitBlocks.size() == 1)
319 BlockToInsertInto = ExitBlocks[0];
320 else
321 BlockToInsertInto = Preheader;
Dan Gohman514277c2008-05-23 21:05:58 +0000322 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000324 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325
326 std::set<Instruction*> InstructionsToDelete;
327 std::map<Instruction*, Value*> ExitValues;
328
329 // Find all values that are computed inside the loop, but used outside of it.
330 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
331 // the exit blocks of the loop to find them.
332 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
333 BasicBlock *ExitBB = ExitBlocks[i];
334
335 // If there are no PHI nodes in this exit block, then no values defined
336 // inside the loop are used on this path, skip it.
337 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
338 if (!PN) continue;
339
340 unsigned NumPreds = PN->getNumIncomingValues();
341
342 // Iterate over all of the PHI nodes.
343 BasicBlock::iterator BBI = ExitBB->begin();
344 while ((PN = dyn_cast<PHINode>(BBI++))) {
345
346 // Iterate over all of the values in all the PHI nodes.
347 for (unsigned i = 0; i != NumPreds; ++i) {
348 // If the value being merged in is not integer or is not defined
349 // in the loop, skip it.
350 Value *InVal = PN->getIncomingValue(i);
351 if (!isa<Instruction>(InVal) ||
352 // SCEV only supports integer expressions for now.
353 !isa<IntegerType>(InVal->getType()))
354 continue;
355
356 // If this pred is for a subloop, not L itself, skip it.
357 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
358 continue; // The Block is in a subloop, skip it.
359
360 // Check that InVal is defined in the loop.
361 Instruction *Inst = cast<Instruction>(InVal);
362 if (!L->contains(Inst->getParent()))
363 continue;
364
365 // We require that this value either have a computable evolution or that
366 // the loop have a constant iteration count. In the case where the loop
367 // has a constant iteration count, we can sometimes force evaluation of
368 // the exit value through brute force.
369 SCEVHandle SH = SE->getSCEV(Inst);
370 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
371 continue; // Cannot get exit evolution for the loop value.
372
373 // Okay, this instruction has a user outside of the current loop
374 // and varies predictably *inside* the loop. Evaluate the value it
375 // contains when the loop exits, if possible.
376 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
377 if (isa<SCEVCouldNotCompute>(ExitValue) ||
378 !ExitValue->isLoopInvariant(L))
379 continue;
380
381 Changed = true;
382 ++NumReplaced;
383
384 // See if we already computed the exit value for the instruction, if so,
385 // just reuse it.
386 Value *&ExitVal = ExitValues[Inst];
387 if (!ExitVal)
388 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
389
390 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
391 << " LoopVal = " << *Inst << "\n";
392
393 PN->setIncomingValue(i, ExitVal);
394
395 // If this instruction is dead now, schedule it to be removed.
396 if (Inst->use_empty())
397 InstructionsToDelete.insert(Inst);
398
399 // See if this is a single-entry LCSSA PHI node. If so, we can (and
400 // have to) remove
401 // the PHI entirely. This is safe, because the NewVal won't be variant
402 // in the loop, so we don't need an LCSSA phi node anymore.
403 if (NumPreds == 1) {
404 SE->deleteValueFromRecords(PN);
405 PN->replaceAllUsesWith(ExitVal);
406 PN->eraseFromParent();
407 break;
408 }
409 }
410 }
411 }
412
413 DeleteTriviallyDeadInstructions(InstructionsToDelete);
414}
415
416bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
417
418 Changed = false;
419 // First step. Check to see if there are any trivial GEP pointer recurrences.
420 // If there are, change them into integer recurrences, permitting analysis by
421 // the SCEV routines.
422 //
423 BasicBlock *Header = L->getHeader();
424 BasicBlock *Preheader = L->getLoopPreheader();
425 SE = &LPM.getAnalysis<ScalarEvolution>();
426
427 std::set<Instruction*> DeadInsts;
428 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
429 PHINode *PN = cast<PHINode>(I);
430 if (isa<PointerType>(PN->getType()))
431 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
432 }
433
434 if (!DeadInsts.empty())
435 DeleteTriviallyDeadInstructions(DeadInsts);
436
437 return Changed;
438}
439
440bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
441
442
443 LI = &getAnalysis<LoopInfo>();
444 SE = &getAnalysis<ScalarEvolution>();
445
446 Changed = false;
447 BasicBlock *Header = L->getHeader();
448 std::set<Instruction*> DeadInsts;
449
450 // Verify the input to the pass in already in LCSSA form.
451 assert(L->isLCSSAForm());
452
453 // Check to see if this loop has a computable loop-invariant execution count.
454 // If so, this means that we can compute the final value of any expressions
455 // that are recurrent in the loop, and substitute the exit values from the
456 // loop into any instructions outside of the loop that use the final values of
457 // the current expressions.
458 //
459 SCEVHandle IterationCount = SE->getIterationCount(L);
460 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000461 RewriteLoopExitValues(L, IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000462
463 // Next, analyze all of the induction variables in the loop, canonicalizing
464 // auxillary induction variables.
465 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
466
467 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
468 PHINode *PN = cast<PHINode>(I);
469 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
470 SCEVHandle SCEV = SE->getSCEV(PN);
471 if (SCEV->hasComputableLoopEvolution(L))
472 // FIXME: It is an extremely bad idea to indvar substitute anything more
473 // complex than affine induction variables. Doing so will put expensive
474 // polynomial evaluations inside of the loop, and the str reduction pass
475 // currently can only reduce affine polynomials. For now just disable
476 // indvar subst on anything more complex than an affine addrec.
477 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
478 if (AR->isAffine())
479 IndVars.push_back(std::make_pair(PN, SCEV));
480 }
481 }
482
483 // If there are no induction variables in the loop, there is nothing more to
484 // do.
485 if (IndVars.empty()) {
486 // Actually, if we know how many times the loop iterates, lets insert a
487 // canonical induction variable to help subsequent passes.
488 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
489 SCEVExpander Rewriter(*SE, *LI);
490 Rewriter.getOrInsertCanonicalInductionVariable(L,
491 IterationCount->getType());
492 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
493 Rewriter)) {
494 std::set<Instruction*> InstructionsToDelete;
495 InstructionsToDelete.insert(I);
496 DeleteTriviallyDeadInstructions(InstructionsToDelete);
497 }
498 }
499 return Changed;
500 }
501
502 // Compute the type of the largest recurrence expression.
503 //
504 const Type *LargestType = IndVars[0].first->getType();
505 bool DifferingSizes = false;
506 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
507 const Type *Ty = IndVars[i].first->getType();
508 DifferingSizes |=
509 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
510 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
511 LargestType = Ty;
512 }
513
514 // Create a rewriter object which we'll use to transform the code with.
515 SCEVExpander Rewriter(*SE, *LI);
516
517 // Now that we know the largest of of the induction variables in this loop,
518 // insert a canonical induction variable of the largest size.
519 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
520 ++NumInserted;
521 Changed = true;
522 DOUT << "INDVARS: New CanIV: " << *IndVar;
523
524 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Wojciech Matyjewiczc561c132008-06-13 17:02:03 +0000525 IterationCount = SE->getTruncateOrZeroExtend(IterationCount, LargestType);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000526 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
527 DeadInsts.insert(DI);
528 }
529
530 // Now that we have a canonical induction variable, we can rewrite any
531 // recurrences in terms of the induction variable. Start with the auxillary
532 // induction variables, and recursively rewrite any of their uses.
Dan Gohman514277c2008-05-23 21:05:58 +0000533 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534
535 // If there were induction variables of other sizes, cast the primary
536 // induction variable to the right size for them, avoiding the need for the
537 // code evaluation methods to insert induction variables of different sizes.
538 if (DifferingSizes) {
539 SmallVector<unsigned,4> InsertedSizes;
540 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
541 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
542 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
543 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
544 == InsertedSizes.end()) {
545 PHINode *PN = IndVars[i].first;
546 InsertedSizes.push_back(ithSize);
547 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
548 InsertPt);
549 Rewriter.addInsertedValue(New, SE->getSCEV(New));
550 DOUT << "INDVARS: Made trunc IV for " << *PN
551 << " NewVal = " << *New << "\n";
552 }
553 }
554 }
555
556 // Rewrite all induction variables in terms of the canonical induction
557 // variable.
558 std::map<unsigned, Value*> InsertedSizes;
559 while (!IndVars.empty()) {
560 PHINode *PN = IndVars.back().first;
561 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
562 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
563 << " into = " << *NewVal << "\n";
564 NewVal->takeName(PN);
565
566 // Replace the old PHI Node with the inserted computation.
567 PN->replaceAllUsesWith(NewVal);
568 DeadInsts.insert(PN);
569 IndVars.pop_back();
570 ++NumRemoved;
571 Changed = true;
572 }
573
574#if 0
575 // Now replace all derived expressions in the loop body with simpler
576 // expressions.
Dan Gohman4d2e8ae2008-06-22 20:18:58 +0000577 for (LoopInfo::block_iterator I = L->block_begin(), E = L->block_end();
578 I != E; ++I) {
579 BasicBlock *BB = *I;
580 if (LI->getLoopFor(BB) == L) { // Not in a subloop...
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000581 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
582 if (I->getType()->isInteger() && // Is an integer instruction
583 !I->use_empty() &&
584 !Rewriter.isInsertedInstruction(I)) {
585 SCEVHandle SH = SE->getSCEV(I);
586 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
587 if (V != I) {
588 if (isa<Instruction>(V))
589 V->takeName(I);
590 I->replaceAllUsesWith(V);
591 DeadInsts.insert(I);
592 ++NumRemoved;
593 Changed = true;
594 }
595 }
596 }
Dan Gohman4d2e8ae2008-06-22 20:18:58 +0000597 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000598#endif
599
600 DeleteTriviallyDeadInstructions(DeadInsts);
601
602 assert(L->isLCSSAForm());
603 return Changed;
604}