IndVarSimplify.cpp revision 6934a04a8c15e9971cd1ea4d5c8df2d7afdd5be5
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"
56using namespace llvm;
57
58STATISTIC(NumRemoved , "Number of aux indvars removed");
59STATISTIC(NumPointer , "Number of pointer indvars promoted");
60STATISTIC(NumInserted, "Number of canonical indvars added");
61STATISTIC(NumReplaced, "Number of exit values replaced");
62STATISTIC(NumLFTR    , "Number of loop exit tests replaced");
63
64namespace {
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(LoopSimplifyID);
83      AU.addRequired<ScalarEvolution>();
84      AU.addRequired<LoopInfo>();
85      AU.addPreservedID(LoopSimplifyID);
86      AU.addPreservedID(LCSSAID);
87      AU.setPreservesCFG();
88    }
89  private:
90    void runOnLoop(Loop *L);
91    void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
92                                    std::set<Instruction*> &DeadInsts);
93    Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
94                                           SCEVExpander &RW);
95    void RewriteLoopExitValues(Loop *L);
96
97    void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
98  };
99  RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
100}
101
102FunctionPass *llvm::createIndVarSimplifyPass() {
103  return new IndVarSimplify();
104}
105
106/// DeleteTriviallyDeadInstructions - If any of the instructions is the
107/// specified set are trivially dead, delete them and see if this makes any of
108/// their operands subsequently dead.
109void IndVarSimplify::
110DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
111  while (!Insts.empty()) {
112    Instruction *I = *Insts.begin();
113    Insts.erase(Insts.begin());
114    if (isInstructionTriviallyDead(I)) {
115      for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
116        if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
117          Insts.insert(U);
118      SE->deleteInstructionFromRecords(I);
119      DOUT << "INDVARS: Deleting: " << *I;
120      I->eraseFromParent();
121      Changed = true;
122    }
123  }
124}
125
126
127/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
128/// recurrence.  If so, change it into an integer recurrence, permitting
129/// analysis by the SCEV routines.
130void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
131                                                BasicBlock *Preheader,
132                                            std::set<Instruction*> &DeadInsts) {
133  assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
134  unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
135  unsigned BackedgeIdx = PreheaderIdx^1;
136  if (GetElementPtrInst *GEPI =
137          dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
138    if (GEPI->getOperand(0) == PN) {
139      assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
140      DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
141
142      // Okay, we found a pointer recurrence.  Transform this pointer
143      // recurrence into an integer recurrence.  Compute the value that gets
144      // added to the pointer at every iteration.
145      Value *AddedVal = GEPI->getOperand(1);
146
147      // Insert a new integer PHI node into the top of the block.
148      PHINode *NewPhi = new PHINode(AddedVal->getType(),
149                                    PN->getName()+".rec", PN);
150      NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
151
152      // Create the new add instruction.
153      Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
154                                                GEPI->getName()+".rec", GEPI);
155      NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
156
157      // Update the existing GEP to use the recurrence.
158      GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
159
160      // Update the GEP to use the new recurrence we just inserted.
161      GEPI->setOperand(1, NewAdd);
162
163      // If the incoming value is a constant expr GEP, try peeling out the array
164      // 0 index if possible to make things simpler.
165      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
166        if (CE->getOpcode() == Instruction::GetElementPtr) {
167          unsigned NumOps = CE->getNumOperands();
168          assert(NumOps > 1 && "CE folding didn't work!");
169          if (CE->getOperand(NumOps-1)->isNullValue()) {
170            // Check to make sure the last index really is an array index.
171            gep_type_iterator GTI = gep_type_begin(CE);
172            for (unsigned i = 1, e = CE->getNumOperands()-1;
173                 i != e; ++i, ++GTI)
174              /*empty*/;
175            if (isa<SequentialType>(*GTI)) {
176              // Pull the last index out of the constant expr GEP.
177              SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
178              Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
179                                                             &CEIdxs[0],
180                                                             CEIdxs.size());
181              GetElementPtrInst *NGEPI =
182                new GetElementPtrInst(NCE, Constant::getNullValue(Type::Int32Ty),
183                                      NewAdd, GEPI->getName(), GEPI);
184              GEPI->replaceAllUsesWith(NGEPI);
185              GEPI->eraseFromParent();
186              GEPI = NGEPI;
187            }
188          }
189        }
190
191
192      // Finally, if there are any other users of the PHI node, we must
193      // insert a new GEP instruction that uses the pre-incremented version
194      // of the induction amount.
195      if (!PN->use_empty()) {
196        BasicBlock::iterator InsertPos = PN; ++InsertPos;
197        while (isa<PHINode>(InsertPos)) ++InsertPos;
198        Value *PreInc =
199          new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
200                                NewPhi, "", InsertPos);
201        PreInc->takeName(PN);
202        PN->replaceAllUsesWith(PreInc);
203      }
204
205      // Delete the old PHI for sure, and the GEP if its otherwise unused.
206      DeadInsts.insert(PN);
207
208      ++NumPointer;
209      Changed = true;
210    }
211}
212
213/// LinearFunctionTestReplace - This method rewrites the exit condition of the
214/// loop to be a canonical != comparison against the incremented loop induction
215/// variable.  This pass is able to rewrite the exit tests of any loop where the
216/// SCEV analysis can determine a loop-invariant trip count of the loop, which
217/// is actually a much broader range than just linear tests.
218///
219/// This method returns a "potentially dead" instruction whose computation chain
220/// should be deleted when convenient.
221Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
222                                                       SCEV *IterationCount,
223                                                       SCEVExpander &RW) {
224  // Find the exit block for the loop.  We can currently only handle loops with
225  // a single exit.
226  std::vector<BasicBlock*> ExitBlocks;
227  L->getExitBlocks(ExitBlocks);
228  if (ExitBlocks.size() != 1) return 0;
229  BasicBlock *ExitBlock = ExitBlocks[0];
230
231  // Make sure there is only one predecessor block in the loop.
232  BasicBlock *ExitingBlock = 0;
233  for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
234       PI != PE; ++PI)
235    if (L->contains(*PI)) {
236      if (ExitingBlock == 0)
237        ExitingBlock = *PI;
238      else
239        return 0;  // Multiple exits from loop to this block.
240    }
241  assert(ExitingBlock && "Loop info is broken");
242
243  if (!isa<BranchInst>(ExitingBlock->getTerminator()))
244    return 0;  // Can't rewrite non-branch yet
245  BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
246  assert(BI->isConditional() && "Must be conditional to be part of loop!");
247
248  Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
249
250  // If the exiting block is not the same as the backedge block, we must compare
251  // against the preincremented value, otherwise we prefer to compare against
252  // the post-incremented value.
253  BasicBlock *Header = L->getHeader();
254  pred_iterator HPI = pred_begin(Header);
255  assert(HPI != pred_end(Header) && "Loop with zero preds???");
256  if (!L->contains(*HPI)) ++HPI;
257  assert(HPI != pred_end(Header) && L->contains(*HPI) &&
258         "No backedge in loop?");
259
260  SCEVHandle TripCount = IterationCount;
261  Value *IndVar;
262  if (*HPI == ExitingBlock) {
263    // The IterationCount expression contains the number of times that the
264    // backedge actually branches to the loop header.  This is one less than the
265    // number of times the loop executes, so add one to it.
266    Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
267    TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
268    IndVar = L->getCanonicalInductionVariableIncrement();
269  } else {
270    // We have to use the preincremented value...
271    IndVar = L->getCanonicalInductionVariable();
272  }
273
274  DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
275       << "  IndVar = " << *IndVar << "\n";
276
277  // Expand the code for the iteration count into the preheader of the loop.
278  BasicBlock *Preheader = L->getLoopPreheader();
279  Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
280                                    IndVar->getType());
281
282  // Insert a new icmp_ne or icmp_eq instruction before the branch.
283  ICmpInst::Predicate Opcode;
284  if (L->contains(BI->getSuccessor(0)))
285    Opcode = ICmpInst::ICMP_NE;
286  else
287    Opcode = ICmpInst::ICMP_EQ;
288
289  Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
290  BI->setCondition(Cond);
291  ++NumLFTR;
292  Changed = true;
293  return PotentiallyDeadInst;
294}
295
296
297/// RewriteLoopExitValues - Check to see if this loop has a computable
298/// loop-invariant execution count.  If so, this means that we can compute the
299/// final value of any expressions that are recurrent in the loop, and
300/// substitute the exit values from the loop into any instructions outside of
301/// the loop that use the final values of the current expressions.
302void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
303  BasicBlock *Preheader = L->getLoopPreheader();
304
305  // Scan all of the instructions in the loop, looking at those that have
306  // extra-loop users and which are recurrences.
307  SCEVExpander Rewriter(*SE, *LI);
308
309  // We insert the code into the preheader of the loop if the loop contains
310  // multiple exit blocks, or in the exit block if there is exactly one.
311  BasicBlock *BlockToInsertInto;
312  std::vector<BasicBlock*> ExitBlocks;
313  L->getExitBlocks(ExitBlocks);
314  if (ExitBlocks.size() == 1)
315    BlockToInsertInto = ExitBlocks[0];
316  else
317    BlockToInsertInto = Preheader;
318  BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
319  while (isa<PHINode>(InsertPt)) ++InsertPt;
320
321  bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
322
323  std::set<Instruction*> InstructionsToDelete;
324
325  for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
326    if (LI->getLoopFor(L->getBlocks()[i]) == L) {  // Not in a subloop...
327      BasicBlock *BB = L->getBlocks()[i];
328      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
329        if (I->getType()->isInteger()) {      // Is an integer instruction
330          SCEVHandle SH = SE->getSCEV(I);
331          if (SH->hasComputableLoopEvolution(L) ||    // Varies predictably
332              HasConstantItCount) {
333            // Find out if this predictably varying value is actually used
334            // outside of the loop.  "extra" as opposed to "intra".
335            std::vector<Instruction*> ExtraLoopUsers;
336            for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
337                 UI != E; ++UI) {
338              Instruction *User = cast<Instruction>(*UI);
339              if (!L->contains(User->getParent())) {
340                // If this is a PHI node in the exit block and we're inserting,
341                // into the exit block, it must have a single entry.  In this
342                // case, we can't insert the code after the PHI and have the PHI
343                // still use it.  Instead, don't insert the the PHI.
344                if (PHINode *PN = dyn_cast<PHINode>(User)) {
345                  // FIXME: This is a case where LCSSA pessimizes code, this
346                  // should be fixed better.
347                  if (PN->getNumOperands() == 2 &&
348                      PN->getParent() == BlockToInsertInto)
349                    continue;
350                }
351                ExtraLoopUsers.push_back(User);
352              }
353            }
354
355            if (!ExtraLoopUsers.empty()) {
356              // Okay, this instruction has a user outside of the current loop
357              // and varies predictably in this loop.  Evaluate the value it
358              // contains when the loop exits, and insert code for it.
359              SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
360              if (!isa<SCEVCouldNotCompute>(ExitValue)) {
361                Changed = true;
362                ++NumReplaced;
363                // Remember the next instruction.  The rewriter can move code
364                // around in some cases.
365                BasicBlock::iterator NextI = I; ++NextI;
366
367                Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
368                                                       I->getType());
369
370                DOUT << "INDVARS: RLEV: AfterLoopVal = " << *NewVal
371                     << "  LoopVal = " << *I << "\n";
372
373                // Rewrite any users of the computed value outside of the loop
374                // with the newly computed value.
375                for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i) {
376                  PHINode* PN = dyn_cast<PHINode>(ExtraLoopUsers[i]);
377                  if (PN && PN->getNumOperands() == 2 &&
378                      !L->contains(PN->getParent())) {
379                    // We're dealing with an LCSSA Phi.  Handle it specially.
380                    Instruction* LCSSAInsertPt = BlockToInsertInto->begin();
381
382                    Instruction* NewInstr = dyn_cast<Instruction>(NewVal);
383                    if (NewInstr && !isa<PHINode>(NewInstr) &&
384                        !L->contains(NewInstr->getParent()))
385                      for (unsigned j = 0; j < NewInstr->getNumOperands(); ++j){
386                        Instruction* PredI =
387                                 dyn_cast<Instruction>(NewInstr->getOperand(j));
388                        if (PredI && L->contains(PredI->getParent())) {
389                          PHINode* NewLCSSA = new PHINode(PredI->getType(),
390                                                    PredI->getName() + ".lcssa",
391                                                    LCSSAInsertPt);
392                          NewLCSSA->addIncoming(PredI,
393                                     BlockToInsertInto->getSinglePredecessor());
394
395                          NewInstr->replaceUsesOfWith(PredI, NewLCSSA);
396                        }
397                      }
398
399                    PN->replaceAllUsesWith(NewVal);
400                    PN->eraseFromParent();
401                  } else {
402                    ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
403                  }
404                }
405
406                // If this instruction is dead now, schedule it to be removed.
407                if (I->use_empty())
408                  InstructionsToDelete.insert(I);
409                I = NextI;
410                continue;  // Skip the ++I
411              }
412            }
413          }
414        }
415
416        // Next instruction.  Continue instruction skips this.
417        ++I;
418      }
419    }
420
421  DeleteTriviallyDeadInstructions(InstructionsToDelete);
422}
423
424
425void IndVarSimplify::runOnLoop(Loop *L) {
426  // First step.  Check to see if there are any trivial GEP pointer recurrences.
427  // If there are, change them into integer recurrences, permitting analysis by
428  // the SCEV routines.
429  //
430  BasicBlock *Header    = L->getHeader();
431  BasicBlock *Preheader = L->getLoopPreheader();
432
433  std::set<Instruction*> DeadInsts;
434  for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
435    PHINode *PN = cast<PHINode>(I);
436    if (isa<PointerType>(PN->getType()))
437      EliminatePointerRecurrence(PN, Preheader, DeadInsts);
438  }
439
440  if (!DeadInsts.empty())
441    DeleteTriviallyDeadInstructions(DeadInsts);
442
443
444  // Next, transform all loops nesting inside of this loop.
445  for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
446    runOnLoop(*I);
447
448  // Check to see if this loop has a computable loop-invariant execution count.
449  // If so, this means that we can compute the final value of any expressions
450  // that are recurrent in the loop, and substitute the exit values from the
451  // loop into any instructions outside of the loop that use the final values of
452  // the current expressions.
453  //
454  SCEVHandle IterationCount = SE->getIterationCount(L);
455  if (!isa<SCEVCouldNotCompute>(IterationCount))
456    RewriteLoopExitValues(L);
457
458  // Next, analyze all of the induction variables in the loop, canonicalizing
459  // auxillary induction variables.
460  std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
461
462  for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
463    PHINode *PN = cast<PHINode>(I);
464    if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
465      SCEVHandle SCEV = SE->getSCEV(PN);
466      if (SCEV->hasComputableLoopEvolution(L))
467        // FIXME: It is an extremely bad idea to indvar substitute anything more
468        // complex than affine induction variables.  Doing so will put expensive
469        // polynomial evaluations inside of the loop, and the str reduction pass
470        // currently can only reduce affine polynomials.  For now just disable
471        // indvar subst on anything more complex than an affine addrec.
472        if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
473          if (AR->isAffine())
474            IndVars.push_back(std::make_pair(PN, SCEV));
475    }
476  }
477
478  // If there are no induction variables in the loop, there is nothing more to
479  // do.
480  if (IndVars.empty()) {
481    // Actually, if we know how many times the loop iterates, lets insert a
482    // canonical induction variable to help subsequent passes.
483    if (!isa<SCEVCouldNotCompute>(IterationCount)) {
484      SCEVExpander Rewriter(*SE, *LI);
485      Rewriter.getOrInsertCanonicalInductionVariable(L,
486                                                     IterationCount->getType());
487      if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
488                                                     Rewriter)) {
489        std::set<Instruction*> InstructionsToDelete;
490        InstructionsToDelete.insert(I);
491        DeleteTriviallyDeadInstructions(InstructionsToDelete);
492      }
493    }
494    return;
495  }
496
497  // Compute the type of the largest recurrence expression.
498  //
499  const Type *LargestType = IndVars[0].first->getType();
500  bool DifferingSizes = false;
501  for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
502    const Type *Ty = IndVars[i].first->getType();
503    DifferingSizes |=
504      Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
505    if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
506      LargestType = Ty;
507  }
508
509  // Create a rewriter object which we'll use to transform the code with.
510  SCEVExpander Rewriter(*SE, *LI);
511
512  // Now that we know the largest of of the induction variables in this loop,
513  // insert a canonical induction variable of the largest size.
514  Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
515  ++NumInserted;
516  Changed = true;
517  DOUT << "INDVARS: New CanIV: " << *IndVar;
518
519  if (!isa<SCEVCouldNotCompute>(IterationCount))
520    if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
521      DeadInsts.insert(DI);
522
523  // Now that we have a canonical induction variable, we can rewrite any
524  // recurrences in terms of the induction variable.  Start with the auxillary
525  // induction variables, and recursively rewrite any of their uses.
526  BasicBlock::iterator InsertPt = Header->begin();
527  while (isa<PHINode>(InsertPt)) ++InsertPt;
528
529  // If there were induction variables of other sizes, cast the primary
530  // induction variable to the right size for them, avoiding the need for the
531  // code evaluation methods to insert induction variables of different sizes.
532  if (DifferingSizes) {
533    SmallVector<unsigned,4> InsertedSizes;
534    InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
535    for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
536      unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
537      if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
538          == InsertedSizes.end()) {
539        PHINode *PN = IndVars[i].first;
540        InsertedSizes.push_back(ithSize);
541        Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
542                                         InsertPt);
543        Rewriter.addInsertedValue(New, SE->getSCEV(New));
544        DOUT << "INDVARS: Made trunc IV for " << *PN
545             << "   NewVal = " << *New << "\n";
546      }
547    }
548  }
549
550  // Rewrite all induction variables in terms of the canonical induction
551  // variable.
552  std::map<unsigned, Value*> InsertedSizes;
553  while (!IndVars.empty()) {
554    PHINode *PN = IndVars.back().first;
555    Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
556                                           PN->getType());
557    DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
558         << "   into = " << *NewVal << "\n";
559    NewVal->takeName(PN);
560
561    // Replace the old PHI Node with the inserted computation.
562    PN->replaceAllUsesWith(NewVal);
563    DeadInsts.insert(PN);
564    IndVars.pop_back();
565    ++NumRemoved;
566    Changed = true;
567  }
568
569#if 0
570  // Now replace all derived expressions in the loop body with simpler
571  // expressions.
572  for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
573    if (LI->getLoopFor(L->getBlocks()[i]) == L) {  // Not in a subloop...
574      BasicBlock *BB = L->getBlocks()[i];
575      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
576        if (I->getType()->isInteger() &&      // Is an integer instruction
577            !I->use_empty() &&
578            !Rewriter.isInsertedInstruction(I)) {
579          SCEVHandle SH = SE->getSCEV(I);
580          Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
581          if (V != I) {
582            if (isa<Instruction>(V))
583              V->takeName(I);
584            I->replaceAllUsesWith(V);
585            DeadInsts.insert(I);
586            ++NumRemoved;
587            Changed = true;
588          }
589        }
590    }
591#endif
592
593  DeleteTriviallyDeadInstructions(DeadInsts);
594
595  if (mustPreserveAnalysisID(LCSSAID)) assert(L->isLCSSAForm());
596}
597