Implement PR1179/PR1232 and test/Transforms/IndVarsSimplify/loop_evaluate_[234].ll
[oota-llvm.git] / lib / Transforms / Scalar / IndVarSimplify.cpp
1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
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/Support/CFG.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/GetElementPtrTypeIterator.h"
52 #include "llvm/Transforms/Utils/Local.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/Statistic.h"
56 using namespace llvm;
57
58 STATISTIC(NumRemoved , "Number of aux indvars removed");
59 STATISTIC(NumPointer , "Number of pointer indvars promoted");
60 STATISTIC(NumInserted, "Number of canonical indvars added");
61 STATISTIC(NumReplaced, "Number of exit values replaced");
62 STATISTIC(NumLFTR    , "Number of loop exit tests replaced");
63
64 namespace {
65   class VISIBILITY_HIDDEN IndVarSimplify : public FunctionPass {
66     LoopInfo        *LI;
67     ScalarEvolution *SE;
68     bool Changed;
69   public:
70     virtual bool runOnFunction(Function &) {
71       LI = &getAnalysis<LoopInfo>();
72       SE = &getAnalysis<ScalarEvolution>();
73       Changed = false;
74
75       // Induction Variables live in the header nodes of loops
76       for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
77         runOnLoop(*I);
78       return Changed;
79     }
80
81     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82       AU.addRequiredID(LCSSAID);
83       AU.addRequiredID(LoopSimplifyID);
84       AU.addRequired<ScalarEvolution>();
85       AU.addRequired<LoopInfo>();
86       AU.addPreservedID(LoopSimplifyID);
87       AU.addPreservedID(LCSSAID);
88       AU.setPreservesCFG();
89     }
90   private:
91     void runOnLoop(Loop *L);
92     void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
93                                     std::set<Instruction*> &DeadInsts);
94     Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
95                                            SCEVExpander &RW);
96     void RewriteLoopExitValues(Loop *L);
97
98     void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
99   };
100   RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
101 }
102
103 FunctionPass *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.
110 void IndVarSimplify::
111 DeleteTriviallyDeadInstructions(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->deleteInstructionFromRecords(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.
131 void 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.
149       PHINode *NewPhi = new PHINode(AddedVal->getType(),
150                                     PN->getName()+".rec", PN);
151       NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
152
153       // Create the new add instruction.
154       Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
155                                                 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());
182               GetElementPtrInst *NGEPI = new GetElementPtrInst(
183                   NCE, Constant::getNullValue(Type::Int32Ty), NewAdd, 
184                   GEPI->getName(), GEPI);
185               GEPI->replaceAllUsesWith(NGEPI);
186               GEPI->eraseFromParent();
187               GEPI = NGEPI;
188             }
189           }
190         }
191
192
193       // Finally, if there are any other users of the PHI node, we must
194       // insert a new GEP instruction that uses the pre-incremented version
195       // of the induction amount.
196       if (!PN->use_empty()) {
197         BasicBlock::iterator InsertPos = PN; ++InsertPos;
198         while (isa<PHINode>(InsertPos)) ++InsertPos;
199         Value *PreInc =
200           new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
201                                 NewPhi, "", InsertPos);
202         PreInc->takeName(PN);
203         PN->replaceAllUsesWith(PreInc);
204       }
205
206       // Delete the old PHI for sure, and the GEP if its otherwise unused.
207       DeadInsts.insert(PN);
208
209       ++NumPointer;
210       Changed = true;
211     }
212 }
213
214 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
215 /// loop to be a canonical != comparison against the incremented loop induction
216 /// variable.  This pass is able to rewrite the exit tests of any loop where the
217 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
218 /// is actually a much broader range than just linear tests.
219 ///
220 /// This method returns a "potentially dead" instruction whose computation chain
221 /// should be deleted when convenient.
222 Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
223                                                        SCEV *IterationCount,
224                                                        SCEVExpander &RW) {
225   // Find the exit block for the loop.  We can currently only handle loops with
226   // a single exit.
227   std::vector<BasicBlock*> ExitBlocks;
228   L->getExitBlocks(ExitBlocks);
229   if (ExitBlocks.size() != 1) return 0;
230   BasicBlock *ExitBlock = ExitBlocks[0];
231
232   // Make sure there is only one predecessor block in the loop.
233   BasicBlock *ExitingBlock = 0;
234   for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
235        PI != PE; ++PI)
236     if (L->contains(*PI)) {
237       if (ExitingBlock == 0)
238         ExitingBlock = *PI;
239       else
240         return 0;  // Multiple exits from loop to this block.
241     }
242   assert(ExitingBlock && "Loop info is broken");
243
244   if (!isa<BranchInst>(ExitingBlock->getTerminator()))
245     return 0;  // Can't rewrite non-branch yet
246   BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
247   assert(BI->isConditional() && "Must be conditional to be part of loop!");
248
249   Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
250   
251   // If the exiting block is not the same as the backedge block, we must compare
252   // against the preincremented value, otherwise we prefer to compare against
253   // the post-incremented value.
254   BasicBlock *Header = L->getHeader();
255   pred_iterator HPI = pred_begin(Header);
256   assert(HPI != pred_end(Header) && "Loop with zero preds???");
257   if (!L->contains(*HPI)) ++HPI;
258   assert(HPI != pred_end(Header) && L->contains(*HPI) &&
259          "No backedge in loop?");
260
261   SCEVHandle TripCount = IterationCount;
262   Value *IndVar;
263   if (*HPI == ExitingBlock) {
264     // The IterationCount expression contains the number of times that the
265     // backedge actually branches to the loop header.  This is one less than the
266     // number of times the loop executes, so add one to it.
267     Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
268     TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
269     IndVar = L->getCanonicalInductionVariableIncrement();
270   } else {
271     // We have to use the preincremented value...
272     IndVar = L->getCanonicalInductionVariable();
273   }
274   
275   DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
276        << "  IndVar = " << *IndVar << "\n";
277
278   // Expand the code for the iteration count into the preheader of the loop.
279   BasicBlock *Preheader = L->getLoopPreheader();
280   Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
281                                     IndVar->getType());
282
283   // Insert a new icmp_ne or icmp_eq instruction before the branch.
284   ICmpInst::Predicate Opcode;
285   if (L->contains(BI->getSuccessor(0)))
286     Opcode = ICmpInst::ICMP_NE;
287   else
288     Opcode = ICmpInst::ICMP_EQ;
289
290   Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
291   BI->setCondition(Cond);
292   ++NumLFTR;
293   Changed = true;
294   return PotentiallyDeadInst;
295 }
296
297
298 /// RewriteLoopExitValues - Check to see if this loop has a computable
299 /// loop-invariant execution count.  If so, this means that we can compute the
300 /// final value of any expressions that are recurrent in the loop, and
301 /// substitute the exit values from the loop into any instructions outside of
302 /// the loop that use the final values of the current expressions.
303 void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
304   BasicBlock *Preheader = L->getLoopPreheader();
305
306   // Scan all of the instructions in the loop, looking at those that have
307   // extra-loop users and which are recurrences.
308   SCEVExpander Rewriter(*SE, *LI);
309
310   // We insert the code into the preheader of the loop if the loop contains
311   // multiple exit blocks, or in the exit block if there is exactly one.
312   BasicBlock *BlockToInsertInto;
313   std::vector<BasicBlock*> ExitBlocks;
314   L->getExitBlocks(ExitBlocks);
315   if (ExitBlocks.size() == 1)
316     BlockToInsertInto = ExitBlocks[0];
317   else
318     BlockToInsertInto = Preheader;
319   BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
320   while (isa<PHINode>(InsertPt)) ++InsertPt;
321
322   bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
323
324   std::set<Instruction*> InstructionsToDelete;
325
326   // Loop over all of the integer-valued instructions in this loop, but that are
327   // not in a subloop.
328   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
329     if (LI->getLoopFor(L->getBlocks()[i]) != L) 
330       continue; // The Block is in a subloop, skip it.
331     BasicBlock *BB = L->getBlocks()[i];
332     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
333       Instruction *I = II++;
334       
335       if (!I->getType()->isInteger())
336         continue;          // SCEV only supports integer expressions for now.
337       
338       // We require that this value either have a computable evolution or that
339       // the loop have a constant iteration count.  In the case where the loop
340       // has a constant iteration count, we can sometimes force evaluation of
341       // the exit value through brute force.
342       SCEVHandle SH = SE->getSCEV(I);
343       if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
344         continue;          // Cannot get exit evolution for the loop value.
345       
346       // Find out if this predictably varying value is actually used
347       // outside of the loop.  "Extra" is as opposed to "intra".
348       std::vector<Instruction*> ExtraLoopUsers;
349       for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
350            UI != E; ++UI) {
351         Instruction *User = cast<Instruction>(*UI);
352         if (!L->contains(User->getParent()))
353           ExtraLoopUsers.push_back(User);
354       }
355       
356       // If nothing outside the loop uses this value, don't rewrite it.
357       if (ExtraLoopUsers.empty())
358         continue;
359       
360       // Okay, this instruction has a user outside of the current loop
361       // and varies predictably *inside* the loop.  Evaluate the value it
362       // contains when the loop exits if possible.
363       SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
364       if (isa<SCEVCouldNotCompute>(ExitValue) ||
365           !ExitValue->isLoopInvariant(L))
366         continue;
367       
368       Changed = true;
369       ++NumReplaced;
370       
371       Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
372                                              I->getType());
373
374       DOUT << "INDVARS: RLEV: AfterLoopVal = " << *NewVal
375            << "  LoopVal = " << *I << "\n";
376       
377       // Rewrite any users of the computed value outside of the loop
378       // with the newly computed value.
379       for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i) {
380         Instruction *User = ExtraLoopUsers[i];
381         
382         User->replaceUsesOfWith(I, NewVal);
383
384         // See if this is an LCSSA PHI node.  If so, we can (and have to) remove
385         // the PHI entirely.  This is safe, because the NewVal won't be variant
386         // in the loop, so we don't need an LCSSA phi node anymore.
387         PHINode *LCSSAPN = dyn_cast<PHINode>(User);
388         if (LCSSAPN && LCSSAPN->getNumOperands() == 2 &&
389             L->contains(LCSSAPN->getIncomingBlock(0))) {
390           LCSSAPN->replaceAllUsesWith(NewVal);
391           LCSSAPN->eraseFromParent();
392         }
393       }
394
395       // If this instruction is dead now, schedule it to be removed.
396       if (I->use_empty())
397         InstructionsToDelete.insert(I);
398     }
399   }
400   
401   DeleteTriviallyDeadInstructions(InstructionsToDelete);
402 }
403
404
405 void IndVarSimplify::runOnLoop(Loop *L) {
406   // First step.  Check to see if there are any trivial GEP pointer recurrences.
407   // If there are, change them into integer recurrences, permitting analysis by
408   // the SCEV routines.
409   //
410   BasicBlock *Header    = L->getHeader();
411   BasicBlock *Preheader = L->getLoopPreheader();
412
413   std::set<Instruction*> DeadInsts;
414   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
415     PHINode *PN = cast<PHINode>(I);
416     if (isa<PointerType>(PN->getType()))
417       EliminatePointerRecurrence(PN, Preheader, DeadInsts);
418   }
419
420   if (!DeadInsts.empty())
421     DeleteTriviallyDeadInstructions(DeadInsts);
422
423
424   // Next, transform all loops nesting inside of this loop.
425   for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
426     runOnLoop(*I);
427
428   // Verify the input to the pass in already in LCSSA form.
429   assert(L->isLCSSAForm());
430
431   // Check to see if this loop has a computable loop-invariant execution count.
432   // If so, this means that we can compute the final value of any expressions
433   // that are recurrent in the loop, and substitute the exit values from the
434   // loop into any instructions outside of the loop that use the final values of
435   // the current expressions.
436   //
437   SCEVHandle IterationCount = SE->getIterationCount(L);
438   if (!isa<SCEVCouldNotCompute>(IterationCount))
439     RewriteLoopExitValues(L);
440
441   // Next, analyze all of the induction variables in the loop, canonicalizing
442   // auxillary induction variables.
443   std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
444
445   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
446     PHINode *PN = cast<PHINode>(I);
447     if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
448       SCEVHandle SCEV = SE->getSCEV(PN);
449       if (SCEV->hasComputableLoopEvolution(L))
450         // FIXME: It is an extremely bad idea to indvar substitute anything more
451         // complex than affine induction variables.  Doing so will put expensive
452         // polynomial evaluations inside of the loop, and the str reduction pass
453         // currently can only reduce affine polynomials.  For now just disable
454         // indvar subst on anything more complex than an affine addrec.
455         if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
456           if (AR->isAffine())
457             IndVars.push_back(std::make_pair(PN, SCEV));
458     }
459   }
460
461   // If there are no induction variables in the loop, there is nothing more to
462   // do.
463   if (IndVars.empty()) {
464     // Actually, if we know how many times the loop iterates, lets insert a
465     // canonical induction variable to help subsequent passes.
466     if (!isa<SCEVCouldNotCompute>(IterationCount)) {
467       SCEVExpander Rewriter(*SE, *LI);
468       Rewriter.getOrInsertCanonicalInductionVariable(L,
469                                                      IterationCount->getType());
470       if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
471                                                      Rewriter)) {
472         std::set<Instruction*> InstructionsToDelete;
473         InstructionsToDelete.insert(I);
474         DeleteTriviallyDeadInstructions(InstructionsToDelete);
475       }
476     }
477     return;
478   }
479
480   // Compute the type of the largest recurrence expression.
481   //
482   const Type *LargestType = IndVars[0].first->getType();
483   bool DifferingSizes = false;
484   for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
485     const Type *Ty = IndVars[i].first->getType();
486     DifferingSizes |= 
487       Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
488     if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
489       LargestType = Ty;
490   }
491
492   // Create a rewriter object which we'll use to transform the code with.
493   SCEVExpander Rewriter(*SE, *LI);
494
495   // Now that we know the largest of of the induction variables in this loop,
496   // insert a canonical induction variable of the largest size.
497   Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
498   ++NumInserted;
499   Changed = true;
500   DOUT << "INDVARS: New CanIV: " << *IndVar;
501
502   if (!isa<SCEVCouldNotCompute>(IterationCount))
503     if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
504       DeadInsts.insert(DI);
505
506   // Now that we have a canonical induction variable, we can rewrite any
507   // recurrences in terms of the induction variable.  Start with the auxillary
508   // induction variables, and recursively rewrite any of their uses.
509   BasicBlock::iterator InsertPt = Header->begin();
510   while (isa<PHINode>(InsertPt)) ++InsertPt;
511
512   // If there were induction variables of other sizes, cast the primary
513   // induction variable to the right size for them, avoiding the need for the
514   // code evaluation methods to insert induction variables of different sizes.
515   if (DifferingSizes) {
516     SmallVector<unsigned,4> InsertedSizes;
517     InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
518     for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
519       unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
520       if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
521           == InsertedSizes.end()) {
522         PHINode *PN = IndVars[i].first;
523         InsertedSizes.push_back(ithSize);
524         Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
525                                          InsertPt);
526         Rewriter.addInsertedValue(New, SE->getSCEV(New));
527         DOUT << "INDVARS: Made trunc IV for " << *PN
528              << "   NewVal = " << *New << "\n";
529       }
530     }
531   }
532
533   // Rewrite all induction variables in terms of the canonical induction
534   // variable.
535   std::map<unsigned, Value*> InsertedSizes;
536   while (!IndVars.empty()) {
537     PHINode *PN = IndVars.back().first;
538     Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
539                                            PN->getType());
540     DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
541          << "   into = " << *NewVal << "\n";
542     NewVal->takeName(PN);
543
544     // Replace the old PHI Node with the inserted computation.
545     PN->replaceAllUsesWith(NewVal);
546     DeadInsts.insert(PN);
547     IndVars.pop_back();
548     ++NumRemoved;
549     Changed = true;
550   }
551
552 #if 0
553   // Now replace all derived expressions in the loop body with simpler
554   // expressions.
555   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
556     if (LI->getLoopFor(L->getBlocks()[i]) == L) {  // Not in a subloop...
557       BasicBlock *BB = L->getBlocks()[i];
558       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
559         if (I->getType()->isInteger() &&      // Is an integer instruction
560             !I->use_empty() &&
561             !Rewriter.isInsertedInstruction(I)) {
562           SCEVHandle SH = SE->getSCEV(I);
563           Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
564           if (V != I) {
565             if (isa<Instruction>(V))
566               V->takeName(I);
567             I->replaceAllUsesWith(V);
568             DeadInsts.insert(I);
569             ++NumRemoved;
570             Changed = true;
571           }
572         }
573     }
574 #endif
575
576   DeleteTriviallyDeadInstructions(DeadInsts);
577   
578   assert(L->isLCSSAForm());
579 }