Fix PR336: The instcombine pass asserts when visiting load instruction
[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 make 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 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/BasicBlock.h"
42 #include "llvm/Constants.h"
43 #include "llvm/Instructions.h"
44 #include "llvm/Type.h"
45 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
46 #include "llvm/Analysis/LoopInfo.h"
47 #include "llvm/Support/CFG.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "Support/CommandLine.h"
50 #include "Support/Statistic.h"
51 using namespace llvm;
52
53 namespace {
54   /// SCEVExpander - This class uses information about analyze scalars to
55   /// rewrite expressions in canonical form.
56   ///
57   /// Clients should create an instance of this class when rewriting is needed,
58   /// and destroying it when finished to allow the release of the associated
59   /// memory.
60   struct SCEVExpander : public SCEVVisitor<SCEVExpander, Value*> {
61     ScalarEvolution &SE;
62     LoopInfo &LI;
63     std::map<SCEVHandle, Value*> InsertedExpressions;
64     std::set<Instruction*> InsertedInstructions;
65
66     Instruction *InsertPt;
67
68     friend class SCEVVisitor<SCEVExpander, Value*>;
69   public:
70     SCEVExpander(ScalarEvolution &se, LoopInfo &li) : SE(se), LI(li) {}
71
72     /// isInsertedInstruction - Return true if the specified instruction was
73     /// inserted by the code rewriter.  If so, the client should not modify the
74     /// instruction.
75     bool isInsertedInstruction(Instruction *I) const {
76       return InsertedInstructions.count(I);
77     }
78     
79     /// getOrInsertCanonicalInductionVariable - This method returns the
80     /// canonical induction variable of the specified type for the specified
81     /// loop (inserting one if there is none).  A canonical induction variable
82     /// starts at zero and steps by one on each iteration.
83     Value *getOrInsertCanonicalInductionVariable(const Loop *L, const Type *Ty){
84       assert((Ty->isInteger() || Ty->isFloatingPoint()) &&
85              "Can only insert integer or floating point induction variables!");
86       SCEVHandle H = SCEVAddRecExpr::get(SCEVUnknown::getIntegerSCEV(0, Ty),
87                                          SCEVUnknown::getIntegerSCEV(1, Ty), L);
88       return expand(H);
89     }
90
91     /// addInsertedValue - Remember the specified instruction as being the
92     /// canonical form for the specified SCEV.
93     void addInsertedValue(Instruction *I, SCEV *S) {
94       InsertedExpressions[S] = (Value*)I;
95       InsertedInstructions.insert(I);
96     }
97
98     /// expandCodeFor - Insert code to directly compute the specified SCEV
99     /// expression into the program.  The inserted code is inserted into the
100     /// specified block.
101     ///
102     /// If a particular value sign is required, a type may be specified for the
103     /// result.
104     Value *expandCodeFor(SCEVHandle SH, Instruction *IP, const Type *Ty = 0) {
105       // Expand the code for this SCEV.
106       this->InsertPt = IP;
107       return expandInTy(SH, Ty);
108     }
109
110   protected:
111     Value *expand(SCEV *S) {
112       // Check to see if we already expanded this.
113       std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
114       if (I != InsertedExpressions.end())
115         return I->second;
116
117       Value *V = visit(S);
118       InsertedExpressions[S] = V;
119       return V;
120     }
121
122     Value *expandInTy(SCEV *S, const Type *Ty) {
123       Value *V = expand(S);
124       if (Ty && V->getType() != Ty) {
125         // FIXME: keep track of the cast instruction.
126         if (Constant *C = dyn_cast<Constant>(V))
127           return ConstantExpr::getCast(C, Ty);
128         else if (Instruction *I = dyn_cast<Instruction>(V)) {
129           // Check to see if there is already a cast.  If there is, use it.
130           for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 
131                UI != E; ++UI) {
132             if ((*UI)->getType() == Ty)
133               if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
134                 BasicBlock::iterator It = I; ++It;
135                 while (isa<PHINode>(It)) ++It;
136                 if (It != BasicBlock::iterator(CI)) {
137                   // Splice the cast immediately after the operand in question.
138                   I->getParent()->getInstList().splice(It,
139                                                        CI->getParent()->getInstList(),
140                                                        CI);
141                 }
142                 return CI;
143               }
144           }
145           BasicBlock::iterator IP = I; ++IP;
146           if (InvokeInst *II = dyn_cast<InvokeInst>(I))
147             IP = II->getNormalDest()->begin();
148           while (isa<PHINode>(IP)) ++IP;
149           return new CastInst(V, Ty, V->getName(), IP);
150         } else {
151           // FIXME: check to see if there is already a cast!
152           return new CastInst(V, Ty, V->getName(), InsertPt);
153         }
154       }
155       return V;
156     }
157
158     Value *visitConstant(SCEVConstant *S) {
159       return S->getValue();
160     }
161
162     Value *visitTruncateExpr(SCEVTruncateExpr *S) {
163       Value *V = expand(S->getOperand());
164       return new CastInst(V, S->getType(), "tmp.", InsertPt);
165     }
166
167     Value *visitZeroExtendExpr(SCEVZeroExtendExpr *S) {
168       Value *V = expandInTy(S->getOperand(),V->getType()->getUnsignedVersion());
169       return new CastInst(V, S->getType(), "tmp.", InsertPt);
170     }
171
172     Value *visitAddExpr(SCEVAddExpr *S) {
173       const Type *Ty = S->getType();
174       Value *V = expandInTy(S->getOperand(S->getNumOperands()-1), Ty);
175
176       // Emit a bunch of add instructions
177       for (int i = S->getNumOperands()-2; i >= 0; --i)
178         V = BinaryOperator::create(Instruction::Add, V,
179                                    expandInTy(S->getOperand(i), Ty),
180                                    "tmp.", InsertPt);
181       return V;
182     }
183
184     Value *visitMulExpr(SCEVMulExpr *S);
185
186     Value *visitUDivExpr(SCEVUDivExpr *S) {
187       const Type *Ty = S->getType();
188       Value *LHS = expandInTy(S->getLHS(), Ty);
189       Value *RHS = expandInTy(S->getRHS(), Ty);
190       return BinaryOperator::create(Instruction::Div, LHS, RHS, "tmp.",
191                                     InsertPt);
192     }
193
194     Value *visitAddRecExpr(SCEVAddRecExpr *S);
195
196     Value *visitUnknown(SCEVUnknown *S) {
197       return S->getValue();
198     }
199   };
200 }
201
202 Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
203   const Type *Ty = S->getType();
204   int FirstOp = 0;  // Set if we should emit a subtract.
205   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
206     if (SC->getValue()->isAllOnesValue())
207       FirstOp = 1;
208     
209   int i = S->getNumOperands()-2;
210   Value *V = expandInTy(S->getOperand(i+1), Ty);
211     
212   // Emit a bunch of multiply instructions
213   for (; i >= FirstOp; --i)
214     V = BinaryOperator::create(Instruction::Mul, V,
215                                expandInTy(S->getOperand(i), Ty),
216                                "tmp.", InsertPt);
217   // -1 * ...  --->  0 - ...
218   if (FirstOp == 1)
219     V = BinaryOperator::create(Instruction::Sub, Constant::getNullValue(Ty),
220                                V, "tmp.", InsertPt);
221   return V;
222 }
223
224 Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
225   const Type *Ty = S->getType();
226   const Loop *L = S->getLoop();
227   // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
228   assert(Ty->isIntegral() && "Cannot expand fp recurrences yet!");
229
230   // {X,+,F} --> X + {0,+,F}
231   if (!isa<SCEVConstant>(S->getStart()) ||
232       !cast<SCEVConstant>(S->getStart())->getValue()->isNullValue()) {
233     Value *Start = expandInTy(S->getStart(), Ty);
234     std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
235     NewOps[0] = SCEVUnknown::getIntegerSCEV(0, Ty);
236     Value *Rest = expandInTy(SCEVAddRecExpr::get(NewOps, L), Ty);
237
238     // FIXME: look for an existing add to use.
239     return BinaryOperator::create(Instruction::Add, Rest, Start, "tmp.",
240                                   InsertPt);
241   }
242
243   // {0,+,1} --> Insert a canonical induction variable into the loop!
244   if (S->getNumOperands() == 2 &&
245       S->getOperand(1) == SCEVUnknown::getIntegerSCEV(1, Ty)) {
246     // Create and insert the PHI node for the induction variable in the
247     // specified loop.
248     BasicBlock *Header = L->getHeader();
249     PHINode *PN = new PHINode(Ty, "indvar", Header->begin());
250     PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
251
252     pred_iterator HPI = pred_begin(Header);
253     assert(HPI != pred_end(Header) && "Loop with zero preds???");
254     if (!L->contains(*HPI)) ++HPI;
255     assert(HPI != pred_end(Header) && L->contains(*HPI) &&
256            "No backedge in loop?");
257
258     // Insert a unit add instruction right before the terminator corresponding
259     // to the back-edge.
260     Constant *One = Ty->isFloatingPoint() ? (Constant*)ConstantFP::get(Ty, 1.0)
261                                           : ConstantInt::get(Ty, 1);
262     Instruction *Add = BinaryOperator::create(Instruction::Add, PN, One,
263                                               "indvar.next",
264                                               (*HPI)->getTerminator());
265
266     pred_iterator PI = pred_begin(Header);
267     if (*PI == L->getLoopPreheader())
268       ++PI;
269     PN->addIncoming(Add, *PI);
270     return PN;
271   }
272
273   // Get the canonical induction variable I for this loop.
274   Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
275
276   if (S->getNumOperands() == 2) {   // {0,+,F} --> i*F
277     Value *F = expandInTy(S->getOperand(1), Ty);
278     return BinaryOperator::create(Instruction::Mul, I, F, "tmp.", InsertPt);
279   }
280
281   // If this is a chain of recurrences, turn it into a closed form, using the
282   // folders, then expandCodeFor the closed form.  This allows the folders to
283   // simplify the expression without having to build a bunch of special code
284   // into this folder.
285   SCEVHandle IH = SCEVUnknown::get(I);   // Get I as a "symbolic" SCEV.
286
287   SCEVHandle V = S->evaluateAtIteration(IH);
288   //std::cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
289
290   return expandInTy(V, Ty);
291 }
292
293
294 namespace {
295   Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
296   Statistic<> NumPointer ("indvars", "Number of pointer indvars promoted");
297   Statistic<> NumInserted("indvars", "Number of canonical indvars added");
298   Statistic<> NumReplaced("indvars", "Number of exit values replaced");
299   Statistic<> NumLFTR    ("indvars", "Number of loop exit tests replaced");
300
301   class IndVarSimplify : public FunctionPass {
302     LoopInfo        *LI;
303     ScalarEvolution *SE;
304     bool Changed;
305   public:
306     virtual bool runOnFunction(Function &) {
307       LI = &getAnalysis<LoopInfo>();
308       SE = &getAnalysis<ScalarEvolution>();
309       Changed = false;
310
311       // Induction Variables live in the header nodes of loops
312       for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
313         runOnLoop(*I);
314       return Changed;
315     }
316
317     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
318       AU.addRequiredID(LoopSimplifyID);
319       AU.addRequired<ScalarEvolution>();
320       AU.addRequired<LoopInfo>();
321       AU.addPreservedID(LoopSimplifyID);
322       AU.setPreservesCFG();
323     }
324   private:
325     void runOnLoop(Loop *L);
326     void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
327                                     std::set<Instruction*> &DeadInsts);
328     void LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
329                                    SCEVExpander &RW);
330     void RewriteLoopExitValues(Loop *L);
331
332     void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
333   };
334   RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
335 }
336
337 Pass *llvm::createIndVarSimplifyPass() {
338   return new IndVarSimplify();
339 }
340
341 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
342 /// specified set are trivially dead, delete them and see if this makes any of
343 /// their operands subsequently dead.
344 void IndVarSimplify::
345 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
346   while (!Insts.empty()) {
347     Instruction *I = *Insts.begin();
348     Insts.erase(Insts.begin());
349     if (isInstructionTriviallyDead(I)) {
350       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
351         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
352           Insts.insert(U);
353       SE->deleteInstructionFromRecords(I);
354       I->getParent()->getInstList().erase(I);
355       Changed = true;
356     }
357   }
358 }
359
360
361 /// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
362 /// recurrence.  If so, change it into an integer recurrence, permitting
363 /// analysis by the SCEV routines.
364 void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN, 
365                                                 BasicBlock *Preheader,
366                                             std::set<Instruction*> &DeadInsts) {
367   assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
368   unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
369   unsigned BackedgeIdx = PreheaderIdx^1;
370   if (GetElementPtrInst *GEPI =
371       dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
372     if (GEPI->getOperand(0) == PN) {
373       assert(GEPI->getNumOperands() == 2 && "GEP types must mismatch!");
374           
375       // Okay, we found a pointer recurrence.  Transform this pointer
376       // recurrence into an integer recurrence.  Compute the value that gets
377       // added to the pointer at every iteration.
378       Value *AddedVal = GEPI->getOperand(1);
379
380       // Insert a new integer PHI node into the top of the block.
381       PHINode *NewPhi = new PHINode(AddedVal->getType(),
382                                     PN->getName()+".rec", PN);
383       NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()),
384                           Preheader);
385       // Create the new add instruction.
386       Value *NewAdd = BinaryOperator::create(Instruction::Add, NewPhi,
387                                              AddedVal,
388                                              GEPI->getName()+".rec", GEPI);
389       NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
390           
391       // Update the existing GEP to use the recurrence.
392       GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
393           
394       // Update the GEP to use the new recurrence we just inserted.
395       GEPI->setOperand(1, NewAdd);
396
397       // Finally, if there are any other users of the PHI node, we must
398       // insert a new GEP instruction that uses the pre-incremented version
399       // of the induction amount.
400       if (!PN->use_empty()) {
401         BasicBlock::iterator InsertPos = PN; ++InsertPos;
402         while (isa<PHINode>(InsertPos)) ++InsertPos;
403         std::string Name = PN->getName(); PN->setName("");
404         Value *PreInc =
405           new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
406                                 std::vector<Value*>(1, NewPhi), Name,
407                                 InsertPos);
408         PN->replaceAllUsesWith(PreInc);
409       }
410
411       // Delete the old PHI for sure, and the GEP if its otherwise unused.
412       DeadInsts.insert(PN);
413
414       ++NumPointer;
415       Changed = true;
416     }
417 }
418
419 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
420 /// loop to be a canonical != comparison against the incremented loop induction
421 /// variable.  This pass is able to rewrite the exit tests of any loop where the
422 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
423 /// is actually a much broader range than just linear tests.
424 void IndVarSimplify::LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
425                                                SCEVExpander &RW) {
426   // Find the exit block for the loop.  We can currently only handle loops with
427   // a single exit.
428   std::vector<BasicBlock*> ExitBlocks;
429   L->getExitBlocks(ExitBlocks);
430   if (ExitBlocks.size() != 1) return;
431   BasicBlock *ExitBlock = ExitBlocks[0];
432
433   // Make sure there is only one predecessor block in the loop.
434   BasicBlock *ExitingBlock = 0;
435   for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
436        PI != PE; ++PI)
437     if (L->contains(*PI)) {
438       if (ExitingBlock == 0)
439         ExitingBlock = *PI;
440       else
441         return;  // Multiple exits from loop to this block.
442     }
443   assert(ExitingBlock && "Loop info is broken");
444
445   if (!isa<BranchInst>(ExitingBlock->getTerminator()))
446     return;  // Can't rewrite non-branch yet
447   BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
448   assert(BI->isConditional() && "Must be conditional to be part of loop!");
449
450   std::set<Instruction*> InstructionsToDelete;
451   if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()))
452     InstructionsToDelete.insert(Cond);
453
454   // If the exiting block is not the same as the backedge block, we must compare
455   // against the preincremented value, otherwise we prefer to compare against
456   // the post-incremented value.
457   BasicBlock *Header = L->getHeader();
458   pred_iterator HPI = pred_begin(Header);
459   assert(HPI != pred_end(Header) && "Loop with zero preds???");
460   if (!L->contains(*HPI)) ++HPI;
461   assert(HPI != pred_end(Header) && L->contains(*HPI) &&
462          "No backedge in loop?");
463
464   SCEVHandle TripCount = IterationCount;
465   Value *IndVar;
466   if (*HPI == ExitingBlock) {
467     // The IterationCount expression contains the number of times that the
468     // backedge actually branches to the loop header.  This is one less than the
469     // number of times the loop executes, so add one to it.
470     Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
471     TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
472     IndVar = L->getCanonicalInductionVariableIncrement();
473   } else {
474     // We have to use the preincremented value...
475     IndVar = L->getCanonicalInductionVariable();
476   }
477
478   // Expand the code for the iteration count into the preheader of the loop.
479   BasicBlock *Preheader = L->getLoopPreheader();
480   Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
481                                     IndVar->getType());
482
483   // Insert a new setne or seteq instruction before the branch.
484   Instruction::BinaryOps Opcode;
485   if (L->contains(BI->getSuccessor(0)))
486     Opcode = Instruction::SetNE;
487   else
488     Opcode = Instruction::SetEQ;
489
490   Value *Cond = new SetCondInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
491   BI->setCondition(Cond);
492   ++NumLFTR;
493   Changed = true;
494
495   DeleteTriviallyDeadInstructions(InstructionsToDelete);
496 }
497
498
499 /// RewriteLoopExitValues - Check to see if this loop has a computable
500 /// loop-invariant execution count.  If so, this means that we can compute the
501 /// final value of any expressions that are recurrent in the loop, and
502 /// substitute the exit values from the loop into any instructions outside of
503 /// the loop that use the final values of the current expressions.
504 void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
505   BasicBlock *Preheader = L->getLoopPreheader();
506
507   // Scan all of the instructions in the loop, looking at those that have
508   // extra-loop users and which are recurrences.
509   SCEVExpander Rewriter(*SE, *LI);
510
511   // We insert the code into the preheader of the loop if the loop contains
512   // multiple exit blocks, or in the exit block if there is exactly one.
513   BasicBlock *BlockToInsertInto;
514   std::vector<BasicBlock*> ExitBlocks;
515   L->getExitBlocks(ExitBlocks);
516   if (ExitBlocks.size() == 1)
517     BlockToInsertInto = ExitBlocks[0];
518   else
519     BlockToInsertInto = Preheader;
520   BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
521   while (isa<PHINode>(InsertPt)) ++InsertPt;
522
523   bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
524
525   std::set<Instruction*> InstructionsToDelete;
526   
527   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
528     if (LI->getLoopFor(L->getBlocks()[i]) == L) {  // Not in a subloop...
529       BasicBlock *BB = L->getBlocks()[i];
530       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
531         if (I->getType()->isInteger()) {      // Is an integer instruction
532           SCEVHandle SH = SE->getSCEV(I);
533           if (SH->hasComputableLoopEvolution(L) ||    // Varies predictably
534               HasConstantItCount) {
535             // Find out if this predictably varying value is actually used
536             // outside of the loop.  "extra" as opposed to "intra".
537             std::vector<User*> ExtraLoopUsers;
538             for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
539                  UI != E; ++UI)
540               if (!L->contains(cast<Instruction>(*UI)->getParent()))
541                 ExtraLoopUsers.push_back(*UI);
542             if (!ExtraLoopUsers.empty()) {
543               // Okay, this instruction has a user outside of the current loop
544               // and varies predictably in this loop.  Evaluate the value it
545               // contains when the loop exits, and insert code for it.
546               SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
547               if (!isa<SCEVCouldNotCompute>(ExitValue)) {
548                 Changed = true;
549                 ++NumReplaced;
550                 Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
551                                                        I->getType());
552
553                 // Rewrite any users of the computed value outside of the loop
554                 // with the newly computed value.
555                 for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i)
556                   ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
557
558                 // If this instruction is dead now, schedule it to be removed.
559                 if (I->use_empty())
560                   InstructionsToDelete.insert(I);
561               }
562             }
563           }
564         }
565     }
566
567   DeleteTriviallyDeadInstructions(InstructionsToDelete);
568 }
569
570
571 void IndVarSimplify::runOnLoop(Loop *L) {
572   // First step.  Check to see if there are any trivial GEP pointer recurrences.
573   // If there are, change them into integer recurrences, permitting analysis by
574   // the SCEV routines.
575   //
576   BasicBlock *Header    = L->getHeader();
577   BasicBlock *Preheader = L->getLoopPreheader();
578   
579   std::set<Instruction*> DeadInsts;
580   for (BasicBlock::iterator I = Header->begin();
581        PHINode *PN = dyn_cast<PHINode>(I); ++I)
582     if (isa<PointerType>(PN->getType()))
583       EliminatePointerRecurrence(PN, Preheader, DeadInsts);
584
585   if (!DeadInsts.empty())
586     DeleteTriviallyDeadInstructions(DeadInsts);
587
588
589   // Next, transform all loops nesting inside of this loop.
590   for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
591     runOnLoop(*I);
592
593   // Check to see if this loop has a computable loop-invariant execution count.
594   // If so, this means that we can compute the final value of any expressions
595   // that are recurrent in the loop, and substitute the exit values from the
596   // loop into any instructions outside of the loop that use the final values of
597   // the current expressions.
598   //
599   SCEVHandle IterationCount = SE->getIterationCount(L);
600   if (!isa<SCEVCouldNotCompute>(IterationCount))
601     RewriteLoopExitValues(L);
602
603   // Next, analyze all of the induction variables in the loop, canonicalizing
604   // auxillary induction variables.
605   std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
606
607   for (BasicBlock::iterator I = Header->begin();
608        PHINode *PN = dyn_cast<PHINode>(I); ++I)
609     if (PN->getType()->isInteger()) {  // FIXME: when we have fast-math, enable!
610       SCEVHandle SCEV = SE->getSCEV(PN);
611       if (SCEV->hasComputableLoopEvolution(L))
612         if (SE->shouldSubstituteIndVar(SCEV))  // HACK!
613           IndVars.push_back(std::make_pair(PN, SCEV));
614     }
615
616   // If there are no induction variables in the loop, there is nothing more to
617   // do.
618   if (IndVars.empty()) {
619     // Actually, if we know how many times the loop iterates, lets insert a
620     // canonical induction variable to help subsequent passes.
621     if (!isa<SCEVCouldNotCompute>(IterationCount)) {
622       SCEVExpander Rewriter(*SE, *LI);
623       Rewriter.getOrInsertCanonicalInductionVariable(L,
624                                                      IterationCount->getType());
625       LinearFunctionTestReplace(L, IterationCount, Rewriter);
626     }
627     return;
628   }
629
630   // Compute the type of the largest recurrence expression.
631   //
632   const Type *LargestType = IndVars[0].first->getType();
633   bool DifferingSizes = false;
634   for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
635     const Type *Ty = IndVars[i].first->getType();
636     DifferingSizes |= Ty->getPrimitiveSize() != LargestType->getPrimitiveSize();
637     if (Ty->getPrimitiveSize() > LargestType->getPrimitiveSize())
638       LargestType = Ty;
639   }
640
641   // Create a rewriter object which we'll use to transform the code with.
642   SCEVExpander Rewriter(*SE, *LI);
643
644   // Now that we know the largest of of the induction variables in this loop,
645   // insert a canonical induction variable of the largest size.
646   LargestType = LargestType->getUnsignedVersion();
647   Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
648   ++NumInserted;
649   Changed = true;
650
651   if (!isa<SCEVCouldNotCompute>(IterationCount))
652     LinearFunctionTestReplace(L, IterationCount, Rewriter);
653
654   // Now that we have a canonical induction variable, we can rewrite any
655   // recurrences in terms of the induction variable.  Start with the auxillary
656   // induction variables, and recursively rewrite any of their uses.
657   BasicBlock::iterator InsertPt = Header->begin();
658   while (isa<PHINode>(InsertPt)) ++InsertPt;
659
660   // If there were induction variables of other sizes, cast the primary
661   // induction variable to the right size for them, avoiding the need for the
662   // code evaluation methods to insert induction variables of different sizes.
663   if (DifferingSizes) {
664     bool InsertedSizes[17] = { false };
665     InsertedSizes[LargestType->getPrimitiveSize()] = true;
666     for (unsigned i = 0, e = IndVars.size(); i != e; ++i)
667       if (!InsertedSizes[IndVars[i].first->getType()->getPrimitiveSize()]) {
668         PHINode *PN = IndVars[i].first;
669         InsertedSizes[PN->getType()->getPrimitiveSize()] = true;
670         Instruction *New = new CastInst(IndVar,
671                                         PN->getType()->getUnsignedVersion(),
672                                         "indvar", InsertPt);
673         Rewriter.addInsertedValue(New, SE->getSCEV(New));
674       }
675   }
676
677   // If there were induction variables of other sizes, cast the primary
678   // induction variable to the right size for them, avoiding the need for the
679   // code evaluation methods to insert induction variables of different sizes.
680   std::map<unsigned, Value*> InsertedSizes;
681   while (!IndVars.empty()) {
682     PHINode *PN = IndVars.back().first;
683     Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
684                                            PN->getType());
685     std::string Name = PN->getName();
686     PN->setName("");
687     NewVal->setName(Name);
688
689     // Replace the old PHI Node with the inserted computation.
690     PN->replaceAllUsesWith(NewVal);
691     DeadInsts.insert(PN);
692     IndVars.pop_back();
693     ++NumRemoved;
694     Changed = true;
695   }
696
697 #if 0
698   // Now replace all derived expressions in the loop body with simpler
699   // expressions.
700   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
701     if (LI->getLoopFor(L->getBlocks()[i]) == L) {  // Not in a subloop...
702       BasicBlock *BB = L->getBlocks()[i];
703       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
704         if (I->getType()->isInteger() &&      // Is an integer instruction
705             !I->use_empty() &&
706             !Rewriter.isInsertedInstruction(I)) {
707           SCEVHandle SH = SE->getSCEV(I);
708           Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
709           if (V != I) {
710             if (isa<Instruction>(V)) {
711               std::string Name = I->getName();
712               I->setName("");
713               V->setName(Name);
714             }
715             I->replaceAllUsesWith(V);
716             DeadInsts.insert(I);
717             ++NumRemoved;
718             Changed = true;
719           }          
720         }
721     }
722 #endif
723
724   DeleteTriviallyDeadInstructions(DeadInsts);
725 }