Remove some more dead code.
[oota-llvm.git] / lib / Transforms / Scalar / LoopStrengthReduce.cpp
1 //===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Nate Begeman and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs a strength reduction on array references inside loops that
11 // have as one or more of their components the loop induction variable.  This is
12 // accomplished by creating a new Value to hold the initial value of the array
13 // access for the first iteration, and then creating a new GEP instruction in
14 // the loop to increment the value by the appropriate amount.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "loop-reduce"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Type.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/ScalarEvolutionExpander.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/GetElementPtrTypeIterator.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/Debug.h"
33 #include <algorithm>
34 #include <set>
35 using namespace llvm;
36
37 namespace {
38   Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
39
40   /// IVStrideUse - Keep track of one use of a strided induction variable, where
41   /// the stride is stored externally.  The Offset member keeps track of the 
42   /// offset from the IV, User is the actual user of the operand, and 'Operand'
43   /// is the operand # of the User that is the use.
44   struct IVStrideUse {
45     SCEVHandle Offset;
46     Instruction *User;
47     Value *OperandValToReplace;
48     
49     IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
50       : Offset(Offs), User(U), OperandValToReplace(O) {}
51   };
52   
53   /// IVUsersOfOneStride - This structure keeps track of all instructions that
54   /// have an operand that is based on the trip count multiplied by some stride.
55   /// The stride for all of these users is common and kept external to this
56   /// structure.
57   struct IVUsersOfOneStride {
58     /// Users - Keep track of all of the users of this stride as well as the
59     /// initial value and the operand that uses the IV.
60     std::vector<IVStrideUse> Users;
61     
62     void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
63       Users.push_back(IVStrideUse(Offset, User, Operand));
64     }
65   };
66
67
68   class LoopStrengthReduce : public FunctionPass {
69     LoopInfo *LI;
70     DominatorSet *DS;
71     ScalarEvolution *SE;
72     const TargetData *TD;
73     const Type *UIntPtrTy;
74     bool Changed;
75
76     /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
77     /// target can handle for free with its addressing modes.
78     unsigned MaxTargetAMSize;
79
80     /// IVUsesByStride - Keep track of all uses of induction variables that we
81     /// are interested in.  The key of the map is the stride of the access.
82     std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
83
84     /// CastedValues - As we need to cast values to uintptr_t, this keeps track
85     /// of the casted version of each value.  This is accessed by
86     /// getCastedVersionOf.
87     std::map<Value*, Value*> CastedPointers;
88
89     /// DeadInsts - Keep track of instructions we may have made dead, so that
90     /// we can remove them after we are done working.
91     std::set<Instruction*> DeadInsts;
92   public:
93     LoopStrengthReduce(unsigned MTAMS = 1)
94       : MaxTargetAMSize(MTAMS) {
95     }
96
97     virtual bool runOnFunction(Function &) {
98       LI = &getAnalysis<LoopInfo>();
99       DS = &getAnalysis<DominatorSet>();
100       SE = &getAnalysis<ScalarEvolution>();
101       TD = &getAnalysis<TargetData>();
102       UIntPtrTy = TD->getIntPtrType();
103       Changed = false;
104
105       for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
106         runOnLoop(*I);
107       
108       CastedPointers.clear();
109       return Changed;
110     }
111
112     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
113       AU.setPreservesCFG();
114       AU.addRequiredID(LoopSimplifyID);
115       AU.addRequired<LoopInfo>();
116       AU.addRequired<DominatorSet>();
117       AU.addRequired<TargetData>();
118       AU.addRequired<ScalarEvolution>();
119     }
120     
121     /// getCastedVersionOf - Return the specified value casted to uintptr_t.
122     ///
123     Value *getCastedVersionOf(Value *V);
124 private:
125     void runOnLoop(Loop *L);
126     bool AddUsersIfInteresting(Instruction *I, Loop *L,
127                                std::set<Instruction*> &Processed);
128     SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
129
130
131     void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
132                                       Loop *L, bool isOnlyStride);
133     void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
134   };
135   RegisterOpt<LoopStrengthReduce> X("loop-reduce",
136                                     "Strength Reduce GEP Uses of Ind. Vars");
137 }
138
139 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
140   return new LoopStrengthReduce(MaxTargetAMSize);
141 }
142
143 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
144 ///
145 Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
146   if (V->getType() == UIntPtrTy) return V;
147   if (Constant *CB = dyn_cast<Constant>(V))
148     return ConstantExpr::getCast(CB, UIntPtrTy);
149
150   Value *&New = CastedPointers[V];
151   if (New) return New;
152   
153   BasicBlock::iterator InsertPt;
154   if (Argument *Arg = dyn_cast<Argument>(V)) {
155     // Insert into the entry of the function, after any allocas.
156     InsertPt = Arg->getParent()->begin()->begin();
157     while (isa<AllocaInst>(InsertPt)) ++InsertPt;
158   } else {
159     if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
160       InsertPt = II->getNormalDest()->begin();
161     } else {
162       InsertPt = cast<Instruction>(V);
163       ++InsertPt;
164     }
165
166     // Do not insert casts into the middle of PHI node blocks.
167     while (isa<PHINode>(InsertPt)) ++InsertPt;
168   }
169     
170   return New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
171 }
172
173
174 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
175 /// specified set are trivially dead, delete them and see if this makes any of
176 /// their operands subsequently dead.
177 void LoopStrengthReduce::
178 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
179   while (!Insts.empty()) {
180     Instruction *I = *Insts.begin();
181     Insts.erase(Insts.begin());
182     if (isInstructionTriviallyDead(I)) {
183       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
184         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
185           Insts.insert(U);
186       SE->deleteInstructionFromRecords(I);
187       I->eraseFromParent();
188       Changed = true;
189     }
190   }
191 }
192
193
194 /// CanReduceSCEV - Return true if we can strength reduce this scalar evolution
195 /// in the specified loop.
196 static bool CanReduceSCEV(const SCEVHandle &SH, Loop *L) {
197   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH);
198   if (!AddRec || AddRec->getLoop() != L) return false;
199
200   // FIXME: Generalize to non-affine IV's.
201   if (!AddRec->isAffine()) return false;
202
203   // FIXME: generalize to IV's with more complex strides (must emit stride
204   // expression outside of loop!)
205   if (isa<SCEVConstant>(AddRec->getOperand(1)))
206     return true;
207
208   // We handle steps by unsigned values, because we know we won't have to insert
209   // a cast for them.
210   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(AddRec->getOperand(1)))
211     if (SU->getValue()->getType()->isUnsigned())
212       return true;
213
214   // Otherwise, no, we can't handle it yet.
215   return false;
216 }
217
218 /// GetExpressionSCEV - Compute and return the SCEV for the specified
219 /// instruction.
220 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
221   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
222   if (!GEP)
223     return SE->getSCEV(Exp);
224     
225   // Analyze all of the subscripts of this getelementptr instruction, looking
226   // for uses that are determined by the trip count of L.  First, skip all
227   // operands the are not dependent on the IV.
228
229   // Build up the base expression.  Insert an LLVM cast of the pointer to
230   // uintptr_t first.
231   SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
232
233   gep_type_iterator GTI = gep_type_begin(GEP);
234   
235   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
236     // If this is a use of a recurrence that we can analyze, and it comes before
237     // Op does in the GEP operand list, we will handle this when we process this
238     // operand.
239     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
240       const StructLayout *SL = TD->getStructLayout(STy);
241       unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
242       uint64_t Offset = SL->MemberOffsets[Idx];
243       GEPVal = SCEVAddExpr::get(GEPVal,
244                                 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
245     } else {
246       SCEVHandle Idx = SE->getSCEV(getCastedVersionOf(GEP->getOperand(i)));
247       uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
248       if (TypeSize != 1)
249         Idx = SCEVMulExpr::get(Idx,
250                                SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
251                                                                    TypeSize)));
252       GEPVal = SCEVAddExpr::get(GEPVal, Idx);
253     }
254   }
255
256   //assert(CanReduceSCEV(GEPVal, L) && "Cannot reduce this use of IV?");  
257   return GEPVal;
258 }
259
260 /// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
261 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
262 /// return true.  Otherwise, return false.
263 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
264                                             std::set<Instruction*> &Processed) {
265   if (I->getType() == Type::VoidTy) return false;
266   if (!Processed.insert(I).second)
267     return true;    // Instruction already handled.
268   
269   SCEVHandle ISE = GetExpressionSCEV(I, L);
270   if (!CanReduceSCEV(ISE, L))
271     return false;  // Non-analyzable expression, e.g. a rem instr.
272   
273   // NOT SAFE with generalized EXPRS
274   SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(ISE);
275   SCEVHandle Start = AR->getStart();
276
277   // Get the step value, canonicalizing to an unsigned integer type so that
278   // lookups in the map will match.
279   Value *Step = 0;   // Step of ISE.
280   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(AR->getOperand(1)))
281     /// Always get the step value as an unsigned value.
282     Step = ConstantExpr::getCast(SC->getValue(),
283                                SC->getValue()->getType()->getUnsignedVersion());
284   else
285     Step = cast<SCEVUnknown>(AR->getOperand(1))->getValue();
286   assert(Step->getType()->isUnsigned() && "Bad step value!");
287
288   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
289     Instruction *User = cast<Instruction>(*UI);
290
291     // Do not infinitely recurse on PHI nodes.
292     if (isa<PHINode>(User) && User->getParent() == L->getHeader())
293       continue;
294
295     // If this is an instruction defined in a nested loop, or outside this loop,
296     // don't recurse into it.
297     if (LI->getLoopFor(User->getParent()) != L) {
298       DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
299             << "   OF SCEV: " << *ISE << "\n");
300       
301       // Okay, we found a user that we cannot reduce.  Analyze the instruction
302       // and decide what to do with it.
303       IVUsesByStride[Step].addUser(Start, User, I);
304     } else if (!AddUsersIfInteresting(User, L, Processed)) {
305       DEBUG(std::cerr << "FOUND USER: " << *User
306             << "   OF SCEV: " << *ISE << "\n");
307
308       // Okay, we found a user that we cannot reduce.  Analyze the instruction
309       // and decide what to do with it.
310       IVUsesByStride[Step].addUser(Start, User, I);
311     }
312   }
313   return true;
314 }
315
316 namespace {
317   /// BasedUser - For a particular base value, keep information about how we've
318   /// partitioned the expression so far.
319   struct BasedUser {
320     /// Inst - The instruction using the induction variable.
321     Instruction *Inst;
322
323     /// OperandValToReplace - The operand value of Inst to replace with the
324     /// EmittedBase.
325     Value *OperandValToReplace;
326
327     /// Imm - The immediate value that should be added to the base immediately
328     /// before Inst, because it will be folded into the imm field of the
329     /// instruction.
330     SCEVHandle Imm;
331
332     /// EmittedBase - The actual value* to use for the base value of this
333     /// operation.  This is null if we should just use zero so far.
334     Value *EmittedBase;
335
336     BasedUser(Instruction *I, Value *Op, const SCEVHandle &IMM)
337       : Inst(I), OperandValToReplace(Op), Imm(IMM), EmittedBase(0) {}
338
339
340     // No need to compare these.
341     bool operator<(const BasedUser &BU) const { return 0; }
342
343     void dump() const;
344   };
345 }
346
347 void BasedUser::dump() const {
348   std::cerr << " Imm=" << *Imm;
349   if (EmittedBase)
350     std::cerr << "  EB=" << *EmittedBase;
351
352   std::cerr << "   Inst: " << *Inst;
353 }
354
355 /// isTargetConstant - Return true if the following can be referenced by the
356 /// immediate field of a target instruction.
357 static bool isTargetConstant(const SCEVHandle &V) {
358
359   // FIXME: Look at the target to decide if &GV is a legal constant immediate.
360   if (isa<SCEVConstant>(V)) return true;
361
362   return false;     // ENABLE this for x86
363
364   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
365     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
366       if (CE->getOpcode() == Instruction::Cast)
367         if (isa<GlobalValue>(CE->getOperand(0)))
368           // FIXME: should check to see that the dest is uintptr_t!
369           return true;
370   return false;
371 }
372
373 /// GetImmediateValues - Look at Val, and pull out any additions of constants
374 /// that can fit into the immediate field of instructions in the target.
375 static SCEVHandle GetImmediateValues(SCEVHandle Val, bool isAddress) {
376   if (!isAddress)
377     return SCEVUnknown::getIntegerSCEV(0, Val->getType());
378   if (isTargetConstant(Val))
379     return Val;
380
381   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
382     unsigned i = 0;
383     for (; i != SAE->getNumOperands(); ++i)
384       if (isTargetConstant(SAE->getOperand(i))) {
385         SCEVHandle ImmVal = SAE->getOperand(i);
386
387         // If there are any other immediates that we can handle here, pull them
388         // out too.
389         for (++i; i != SAE->getNumOperands(); ++i)
390           if (isTargetConstant(SAE->getOperand(i)))
391             ImmVal = SCEVAddExpr::get(ImmVal, SAE->getOperand(i));
392         return ImmVal;
393       }
394   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
395     // Try to pull immediates out of the start value of nested addrec's.
396     return GetImmediateValues(SARE->getStart(), isAddress);
397   }
398
399   return SCEVUnknown::getIntegerSCEV(0, Val->getType());
400 }
401
402 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
403 /// stride of IV.  All of the users may have different starting values, and this
404 /// may not be the only stride (we know it is if isOnlyStride is true).
405 void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
406                                                       IVUsersOfOneStride &Uses,
407                                                       Loop *L,
408                                                       bool isOnlyStride) {
409   // Transform our list of users and offsets to a bit more complex table.  In
410   // this new vector, the first entry for each element is the base of the
411   // strided access, and the second is the BasedUser object for the use.  We
412   // progressively move information from the first to the second entry, until we
413   // eventually emit the object.
414   std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess;
415   UsersToProcess.reserve(Uses.Users.size());
416
417   SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0,
418                                               Uses.Users[0].Offset->getType());
419
420   for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i)
421     UsersToProcess.push_back(std::make_pair(Uses.Users[i].Offset,
422                                             BasedUser(Uses.Users[i].User,
423                                              Uses.Users[i].OperandValToReplace,
424                                                       ZeroBase)));
425
426   // First pass, figure out what we can represent in the immediate fields of
427   // instructions.  If we can represent anything there, move it to the imm
428   // fields of the BasedUsers.
429   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
430     bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst) ||
431                      isa<StoreInst>(UsersToProcess[i].second.Inst);
432     UsersToProcess[i].second.Imm = GetImmediateValues(UsersToProcess[i].first,
433                                                       isAddress);
434     UsersToProcess[i].first = SCEV::getMinusSCEV(UsersToProcess[i].first,
435                                                  UsersToProcess[i].second.Imm);
436
437     DEBUG(std::cerr << "BASE: " << *UsersToProcess[i].first);
438     DEBUG(UsersToProcess[i].second.dump());
439   }
440
441   SCEVExpander Rewriter(*SE, *LI);
442   BasicBlock  *Preheader = L->getLoopPreheader();
443   Instruction *PreInsertPt = Preheader->getTerminator();
444   Instruction *PhiInsertBefore = L->getHeader()->begin();
445
446   assert(isa<PHINode>(PhiInsertBefore) &&
447          "How could this loop have IV's without any phis?");
448   PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
449   assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
450          "This loop isn't canonicalized right");
451   BasicBlock *LatchBlock =
452    SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
453
454   DEBUG(std::cerr << "INSERTING IVs of STRIDE " << *Stride << ":\n");
455   
456   // FIXME: This loop needs increasing levels of intelligence.
457   // STAGE 0: just emit everything as its own base.
458   // STAGE 1: factor out common vars from bases, and try and push resulting
459   //          constants into Imm field.  <-- We are here
460   // STAGE 2: factor out large constants to try and make more constants
461   //          acceptable for target loads and stores.
462
463   // Sort by the base value, so that all IVs with identical bases are next to
464   // each other.  
465   std::sort(UsersToProcess.begin(), UsersToProcess.end());
466   while (!UsersToProcess.empty()) {
467     SCEVHandle Base = UsersToProcess.front().first;
468
469     DEBUG(std::cerr << "  INSERTING PHI with BASE = " << *Base << ":\n");
470    
471     // Create a new Phi for this base, and stick it in the loop header.
472     const Type *ReplacedTy = Base->getType();
473     PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
474
475     // Emit the initial base value into the loop preheader, and add it to the
476     // Phi node.
477     Value *BaseV = Rewriter.expandCodeFor(Base, PreInsertPt, ReplacedTy);
478     NewPHI->addIncoming(BaseV, Preheader);
479
480     // Emit the increment of the base value before the terminator of the loop
481     // latch block, and add it to the Phi node.
482     SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
483                                       SCEVUnknown::get(Stride));
484
485     Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(),
486                                          ReplacedTy);
487     IncV->setName(NewPHI->getName()+".inc");
488     NewPHI->addIncoming(IncV, LatchBlock);
489
490     // Emit the code to add the immediate offset to the Phi value, just before
491     // the instructions that we identified as using this stride and base.
492     while (!UsersToProcess.empty() && UsersToProcess.front().first == Base) {
493       BasedUser &User = UsersToProcess.front().second;
494
495       // Clear the SCEVExpander's expression map so that we are guaranteed
496       // to have the code emitted where we expect it.
497       Rewriter.clear();
498       SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
499                                                User.Imm);
500       Value *Replaced = User.OperandValToReplace;
501       Value *newVal = Rewriter.expandCodeFor(NewValSCEV, User.Inst,
502                                              Replaced->getType());
503
504       // Replace the use of the operand Value with the new Phi we just created.
505       User.Inst->replaceUsesOfWith(Replaced, newVal);
506       DEBUG(std::cerr << "    CHANGED: IMM =" << *User.Imm << "  Inst = "
507             << *User.Inst);
508
509       // Mark old value we replaced as possibly dead, so that it is elminated
510       // if we just replaced the last use of that value.
511       DeadInsts.insert(cast<Instruction>(Replaced));
512
513       UsersToProcess.erase(UsersToProcess.begin());
514       ++NumReduced;
515     }
516     // TODO: Next, find out which base index is the most common, pull it out.
517   }
518
519   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
520   // different starting values, into different PHIs.
521
522   // BEFORE writing this, it's probably useful to handle GEP's.
523
524   // NOTE: pull all constants together, for REG+IMM addressing, include &GV in
525   // 'IMM' if the target supports it.
526 }
527
528
529 void LoopStrengthReduce::runOnLoop(Loop *L) {
530   // First step, transform all loops nesting inside of this loop.
531   for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
532     runOnLoop(*I);
533
534   // Next, find all uses of induction variables in this loop, and catagorize
535   // them by stride.  Start by finding all of the PHI nodes in the header for
536   // this loop.  If they are induction variables, inspect their uses.
537   std::set<Instruction*> Processed;   // Don't reprocess instructions.
538   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
539     AddUsersIfInteresting(I, L, Processed);
540
541   // If we have nothing to do, return.
542   //if (IVUsesByStride.empty()) return;
543
544   // FIXME: We can widen subreg IV's here for RISC targets.  e.g. instead of
545   // doing computation in byte values, promote to 32-bit values if safe.
546
547   // FIXME: Attempt to reuse values across multiple IV's.  In particular, we
548   // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
549   // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.  Need
550   // to be careful that IV's are all the same type.  Only works for intptr_t
551   // indvars.
552
553   // If we only have one stride, we can more aggressively eliminate some things.
554   bool HasOneStride = IVUsesByStride.size() == 1;
555
556   for (std::map<Value*, IVUsersOfOneStride>::iterator SI
557         = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
558     StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
559
560   // Clean up after ourselves
561   if (!DeadInsts.empty()) {
562     DeleteTriviallyDeadInstructions(DeadInsts);
563
564     BasicBlock::iterator I = L->getHeader()->begin();
565     PHINode *PN;
566     while ((PN = dyn_cast<PHINode>(I))) {
567       ++I;  // Preincrement iterator to avoid invalidating it when deleting PN.
568       
569       // At this point, we know that we have killed one or more GEP instructions.
570       // It is worth checking to see if the cann indvar is also dead, so that we
571       // can remove it as well.  The requirements for the cann indvar to be
572       // considered dead are:
573       // 1. the cann indvar has one use
574       // 2. the use is an add instruction
575       // 3. the add has one use
576       // 4. the add is used by the cann indvar
577       // If all four cases above are true, then we can remove both the add and
578       // the cann indvar.
579       // FIXME: this needs to eliminate an induction variable even if it's being
580       // compared against some value to decide loop termination.
581       if (PN->hasOneUse()) {
582         BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
583         if (BO && BO->hasOneUse()) {
584           if (PN == *(BO->use_begin())) {
585             DeadInsts.insert(BO);
586             // Break the cycle, then delete the PHI.
587             PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
588             SE->deleteInstructionFromRecords(PN);
589             PN->eraseFromParent();
590           }
591         }
592       }
593     }
594     DeleteTriviallyDeadInstructions(DeadInsts);
595   }
596
597   IVUsesByStride.clear();
598   return;
599 }