b828c0da2a9beb9145df72730d92078703bb4728
[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/BasicBlockUtils.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Debug.h"
34 #include <algorithm>
35 #include <set>
36 using namespace llvm;
37
38 namespace {
39   Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
40   Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
41   Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
42
43   /// IVStrideUse - Keep track of one use of a strided induction variable, where
44   /// the stride is stored externally.  The Offset member keeps track of the 
45   /// offset from the IV, User is the actual user of the operand, and 'Operand'
46   /// is the operand # of the User that is the use.
47   struct IVStrideUse {
48     SCEVHandle Offset;
49     Instruction *User;
50     Value *OperandValToReplace;
51
52     // isUseOfPostIncrementedValue - True if this should use the
53     // post-incremented version of this IV, not the preincremented version.
54     // This can only be set in special cases, such as the terminating setcc
55     // instruction for a loop or uses dominated by the loop.
56     bool isUseOfPostIncrementedValue;
57     
58     IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
59       : Offset(Offs), User(U), OperandValToReplace(O),
60         isUseOfPostIncrementedValue(false) {}
61   };
62   
63   /// IVUsersOfOneStride - This structure keeps track of all instructions that
64   /// have an operand that is based on the trip count multiplied by some stride.
65   /// The stride for all of these users is common and kept external to this
66   /// structure.
67   struct IVUsersOfOneStride {
68     /// Users - Keep track of all of the users of this stride as well as the
69     /// initial value and the operand that uses the IV.
70     std::vector<IVStrideUse> Users;
71     
72     void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
73       Users.push_back(IVStrideUse(Offset, User, Operand));
74     }
75   };
76
77
78   class LoopStrengthReduce : public FunctionPass {
79     LoopInfo *LI;
80     DominatorSet *DS;
81     ScalarEvolution *SE;
82     const TargetData *TD;
83     const Type *UIntPtrTy;
84     bool Changed;
85
86     /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
87     /// target can handle for free with its addressing modes.
88     unsigned MaxTargetAMSize;
89
90     /// IVUsesByStride - Keep track of all uses of induction variables that we
91     /// are interested in.  The key of the map is the stride of the access.
92     std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
93
94     /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
95     /// We use this to iterate over the IVUsesByStride collection without being
96     /// dependent on random ordering of pointers in the process.
97     std::vector<SCEVHandle> StrideOrder;
98
99     /// CastedValues - As we need to cast values to uintptr_t, this keeps track
100     /// of the casted version of each value.  This is accessed by
101     /// getCastedVersionOf.
102     std::map<Value*, Value*> CastedPointers;
103
104     /// DeadInsts - Keep track of instructions we may have made dead, so that
105     /// we can remove them after we are done working.
106     std::set<Instruction*> DeadInsts;
107   public:
108     LoopStrengthReduce(unsigned MTAMS = 1)
109       : MaxTargetAMSize(MTAMS) {
110     }
111
112     virtual bool runOnFunction(Function &) {
113       LI = &getAnalysis<LoopInfo>();
114       DS = &getAnalysis<DominatorSet>();
115       SE = &getAnalysis<ScalarEvolution>();
116       TD = &getAnalysis<TargetData>();
117       UIntPtrTy = TD->getIntPtrType();
118       Changed = false;
119
120       for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
121         runOnLoop(*I);
122       
123       return Changed;
124     }
125
126     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
127       // We split critical edges, so we change the CFG.  However, we do update
128       // many analyses if they are around.
129       AU.addPreservedID(LoopSimplifyID);
130       AU.addPreserved<LoopInfo>();
131       AU.addPreserved<DominatorSet>();
132       AU.addPreserved<ImmediateDominators>();
133       AU.addPreserved<DominanceFrontier>();
134       AU.addPreserved<DominatorTree>();
135
136       AU.addRequiredID(LoopSimplifyID);
137       AU.addRequired<LoopInfo>();
138       AU.addRequired<DominatorSet>();
139       AU.addRequired<TargetData>();
140       AU.addRequired<ScalarEvolution>();
141     }
142     
143     /// getCastedVersionOf - Return the specified value casted to uintptr_t.
144     ///
145     Value *getCastedVersionOf(Value *V);
146 private:
147     void runOnLoop(Loop *L);
148     bool AddUsersIfInteresting(Instruction *I, Loop *L,
149                                std::set<Instruction*> &Processed);
150     SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
151
152     void OptimizeIndvars(Loop *L);
153
154     void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
155                                       IVUsersOfOneStride &Uses,
156                                       Loop *L, bool isOnlyStride);
157     void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
158   };
159   RegisterOpt<LoopStrengthReduce> X("loop-reduce",
160                                     "Loop Strength Reduction");
161 }
162
163 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
164   return new LoopStrengthReduce(MaxTargetAMSize);
165 }
166
167 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
168 ///
169 Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
170   if (V->getType() == UIntPtrTy) return V;
171   if (Constant *CB = dyn_cast<Constant>(V))
172     return ConstantExpr::getCast(CB, UIntPtrTy);
173
174   Value *&New = CastedPointers[V];
175   if (New) return New;
176   
177   BasicBlock::iterator InsertPt;
178   if (Argument *Arg = dyn_cast<Argument>(V)) {
179     // Insert into the entry of the function, after any allocas.
180     InsertPt = Arg->getParent()->begin()->begin();
181     while (isa<AllocaInst>(InsertPt)) ++InsertPt;
182   } else {
183     if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
184       InsertPt = II->getNormalDest()->begin();
185     } else {
186       InsertPt = cast<Instruction>(V);
187       ++InsertPt;
188     }
189
190     // Do not insert casts into the middle of PHI node blocks.
191     while (isa<PHINode>(InsertPt)) ++InsertPt;
192   }
193   
194   New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
195   DeadInsts.insert(cast<Instruction>(New));
196   return New;
197 }
198
199
200 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
201 /// specified set are trivially dead, delete them and see if this makes any of
202 /// their operands subsequently dead.
203 void LoopStrengthReduce::
204 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
205   while (!Insts.empty()) {
206     Instruction *I = *Insts.begin();
207     Insts.erase(Insts.begin());
208     if (isInstructionTriviallyDead(I)) {
209       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
210         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
211           Insts.insert(U);
212       SE->deleteInstructionFromRecords(I);
213       I->eraseFromParent();
214       Changed = true;
215     }
216   }
217 }
218
219
220 /// GetExpressionSCEV - Compute and return the SCEV for the specified
221 /// instruction.
222 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
223   // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
224   // If this is a GEP that SE doesn't know about, compute it now and insert it.
225   // If this is not a GEP, or if we have already done this computation, just let
226   // SE figure it out.
227   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
228   if (!GEP || SE->hasSCEV(GEP))
229     return SE->getSCEV(Exp);
230     
231   // Analyze all of the subscripts of this getelementptr instruction, looking
232   // for uses that are determined by the trip count of L.  First, skip all
233   // operands the are not dependent on the IV.
234
235   // Build up the base expression.  Insert an LLVM cast of the pointer to
236   // uintptr_t first.
237   SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
238
239   gep_type_iterator GTI = gep_type_begin(GEP);
240   
241   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
242     // If this is a use of a recurrence that we can analyze, and it comes before
243     // Op does in the GEP operand list, we will handle this when we process this
244     // operand.
245     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
246       const StructLayout *SL = TD->getStructLayout(STy);
247       unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
248       uint64_t Offset = SL->MemberOffsets[Idx];
249       GEPVal = SCEVAddExpr::get(GEPVal,
250                                 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
251     } else {
252       Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
253       SCEVHandle Idx = SE->getSCEV(OpVal);
254
255       uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
256       if (TypeSize != 1)
257         Idx = SCEVMulExpr::get(Idx,
258                                SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
259                                                                    TypeSize)));
260       GEPVal = SCEVAddExpr::get(GEPVal, Idx);
261     }
262   }
263
264   SE->setSCEV(GEP, GEPVal);
265   return GEPVal;
266 }
267
268 /// getSCEVStartAndStride - Compute the start and stride of this expression,
269 /// returning false if the expression is not a start/stride pair, or true if it
270 /// is.  The stride must be a loop invariant expression, but the start may be
271 /// a mix of loop invariant and loop variant expressions.
272 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
273                                   SCEVHandle &Start, SCEVHandle &Stride) {
274   SCEVHandle TheAddRec = Start;   // Initialize to zero.
275
276   // If the outer level is an AddExpr, the operands are all start values except
277   // for a nested AddRecExpr.
278   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
279     for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
280       if (SCEVAddRecExpr *AddRec =
281              dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
282         if (AddRec->getLoop() == L)
283           TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
284         else
285           return false;  // Nested IV of some sort?
286       } else {
287         Start = SCEVAddExpr::get(Start, AE->getOperand(i));
288       }
289         
290   } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
291     TheAddRec = SH;
292   } else {
293     return false;  // not analyzable.
294   }
295   
296   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
297   if (!AddRec || AddRec->getLoop() != L) return false;
298   
299   // FIXME: Generalize to non-affine IV's.
300   if (!AddRec->isAffine()) return false;
301
302   Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
303   
304   if (!isa<SCEVConstant>(AddRec->getOperand(1)))
305     DEBUG(std::cerr << "[" << L->getHeader()->getName()
306                     << "] Variable stride: " << *AddRec << "\n");
307
308   Stride = AddRec->getOperand(1);
309   // Check that all constant strides are the unsigned type, we don't want to
310   // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
311   // merged.
312   assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
313          "Constants should be canonicalized to unsigned!");
314
315   return true;
316 }
317
318 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
319 /// and now we need to decide whether the user should use the preinc or post-inc
320 /// value.  If this user should use the post-inc version of the IV, return true.
321 ///
322 /// Choosing wrong here can break dominance properties (if we choose to use the
323 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
324 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
325 /// should use the post-inc value).
326 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
327                                        Loop *L, DominatorSet *DS, Pass *P) {
328   // If the user is in the loop, use the preinc value.
329   if (L->contains(User->getParent())) return false;
330   
331   BasicBlock *LatchBlock = L->getLoopLatch();
332   
333   // Ok, the user is outside of the loop.  If it is dominated by the latch
334   // block, use the post-inc value.
335   if (DS->dominates(LatchBlock, User->getParent()))
336     return true;
337
338   // There is one case we have to be careful of: PHI nodes.  These little guys
339   // can live in blocks that do not dominate the latch block, but (since their
340   // uses occur in the predecessor block, not the block the PHI lives in) should
341   // still use the post-inc value.  Check for this case now.
342   PHINode *PN = dyn_cast<PHINode>(User);
343   if (!PN) return false;  // not a phi, not dominated by latch block.
344   
345   // Look at all of the uses of IV by the PHI node.  If any use corresponds to
346   // a block that is not dominated by the latch block, give up and use the
347   // preincremented value.
348   unsigned NumUses = 0;
349   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
350     if (PN->getIncomingValue(i) == IV) {
351       ++NumUses;
352       if (!DS->dominates(LatchBlock, PN->getIncomingBlock(i)))
353         return false;
354     }
355
356   // Okay, all uses of IV by PN are in predecessor blocks that really are
357   // dominated by the latch block.  Split the critical edges and use the
358   // post-incremented value.
359   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
360     if (PN->getIncomingValue(i) == IV) {
361       SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
362       if (--NumUses == 0) break;
363     }
364   
365   return true;
366 }
367
368   
369
370 /// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
371 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
372 /// return true.  Otherwise, return false.
373 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
374                                             std::set<Instruction*> &Processed) {
375   if (I->getType() == Type::VoidTy) return false;
376   if (!Processed.insert(I).second)
377     return true;    // Instruction already handled.
378   
379   // Get the symbolic expression for this instruction.
380   SCEVHandle ISE = GetExpressionSCEV(I, L);
381   if (isa<SCEVCouldNotCompute>(ISE)) return false;
382   
383   // Get the start and stride for this expression.
384   SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
385   SCEVHandle Stride = Start;
386   if (!getSCEVStartAndStride(ISE, L, Start, Stride))
387     return false;  // Non-reducible symbolic expression, bail out.
388   
389   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
390     Instruction *User = cast<Instruction>(*UI);
391
392     // Do not infinitely recurse on PHI nodes.
393     if (isa<PHINode>(User) && Processed.count(User))
394       continue;
395
396     // If this is an instruction defined in a nested loop, or outside this loop,
397     // don't recurse into it.
398     bool AddUserToIVUsers = false;
399     if (LI->getLoopFor(User->getParent()) != L) {
400       DEBUG(std::cerr << "FOUND USER in other loop: " << *User
401             << "   OF SCEV: " << *ISE << "\n");
402       AddUserToIVUsers = true;
403     } else if (!AddUsersIfInteresting(User, L, Processed)) {
404       DEBUG(std::cerr << "FOUND USER: " << *User
405             << "   OF SCEV: " << *ISE << "\n");
406       AddUserToIVUsers = true;
407     }
408
409     if (AddUserToIVUsers) {
410       IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
411       if (StrideUses.Users.empty())     // First occurance of this stride?
412         StrideOrder.push_back(Stride);
413       
414       // Okay, we found a user that we cannot reduce.  Analyze the instruction
415       // and decide what to do with it.  If we are a use inside of the loop, use
416       // the value before incrementation, otherwise use it after incrementation.
417       if (IVUseShouldUsePostIncValue(User, I, L, DS, this)) {
418         // The value used will be incremented by the stride more than we are
419         // expecting, so subtract this off.
420         SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
421         StrideUses.addUser(NewStart, User, I);
422         StrideUses.Users.back().isUseOfPostIncrementedValue = true;
423         DEBUG(std::cerr << "   USING POSTINC SCEV, START=" << *NewStart<< "\n");
424       } else {        
425         StrideUses.addUser(Start, User, I);
426       }
427     }
428   }
429   return true;
430 }
431
432 namespace {
433   /// BasedUser - For a particular base value, keep information about how we've
434   /// partitioned the expression so far.
435   struct BasedUser {
436     /// Base - The Base value for the PHI node that needs to be inserted for
437     /// this use.  As the use is processed, information gets moved from this
438     /// field to the Imm field (below).  BasedUser values are sorted by this
439     /// field.
440     SCEVHandle Base;
441     
442     /// Inst - The instruction using the induction variable.
443     Instruction *Inst;
444
445     /// OperandValToReplace - The operand value of Inst to replace with the
446     /// EmittedBase.
447     Value *OperandValToReplace;
448
449     /// Imm - The immediate value that should be added to the base immediately
450     /// before Inst, because it will be folded into the imm field of the
451     /// instruction.
452     SCEVHandle Imm;
453
454     /// EmittedBase - The actual value* to use for the base value of this
455     /// operation.  This is null if we should just use zero so far.
456     Value *EmittedBase;
457
458     // isUseOfPostIncrementedValue - True if this should use the
459     // post-incremented version of this IV, not the preincremented version.
460     // This can only be set in special cases, such as the terminating setcc
461     // instruction for a loop and uses outside the loop that are dominated by
462     // the loop.
463     bool isUseOfPostIncrementedValue;
464     
465     BasedUser(IVStrideUse &IVSU)
466       : Base(IVSU.Offset), Inst(IVSU.User), 
467         OperandValToReplace(IVSU.OperandValToReplace), 
468         Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
469         isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
470
471     // Once we rewrite the code to insert the new IVs we want, update the
472     // operands of Inst to use the new expression 'NewBase', with 'Imm' added
473     // to it.
474     void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
475                                         SCEVExpander &Rewriter, Loop *L,
476                                         Pass *P);
477
478     // Sort by the Base field.
479     bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
480
481     void dump() const;
482   };
483 }
484
485 void BasedUser::dump() const {
486   std::cerr << " Base=" << *Base;
487   std::cerr << " Imm=" << *Imm;
488   if (EmittedBase)
489     std::cerr << "  EB=" << *EmittedBase;
490
491   std::cerr << "   Inst: " << *Inst;
492 }
493
494 // Once we rewrite the code to insert the new IVs we want, update the
495 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
496 // to it.
497 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
498                                                SCEVExpander &Rewriter,
499                                                Loop *L, Pass *P) {
500   if (!isa<PHINode>(Inst)) {
501     SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
502     Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
503                                            OperandValToReplace->getType());
504     // Replace the use of the operand Value with the new Phi we just created.
505     Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
506     DEBUG(std::cerr << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst);
507     return;
508   }
509   
510   // PHI nodes are more complex.  We have to insert one copy of the NewBase+Imm
511   // expression into each operand block that uses it.  Note that PHI nodes can
512   // have multiple entries for the same predecessor.  We use a map to make sure
513   // that a PHI node only has a single Value* for each predecessor (which also
514   // prevents us from inserting duplicate code in some blocks).
515   std::map<BasicBlock*, Value*> InsertedCode;
516   PHINode *PN = cast<PHINode>(Inst);
517   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
518     if (PN->getIncomingValue(i) == OperandValToReplace) {
519       // If this is a critical edge, split the edge so that we do not insert the
520       // code on all predecessor/successor paths.  We do this unless this is the
521       // canonical backedge for this loop, as this can make some inserted code
522       // be in an illegal position.
523       BasicBlock *PHIPred = PN->getIncomingBlock(i);
524       if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
525           (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
526         
527         // First step, split the critical edge.
528         SplitCriticalEdge(PHIPred, PN->getParent(), P);
529             
530         // Next step: move the basic block.  In particular, if the PHI node
531         // is outside of the loop, and PredTI is in the loop, we want to
532         // move the block to be immediately before the PHI block, not
533         // immediately after PredTI.
534         if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
535           BasicBlock *NewBB = PN->getIncomingBlock(i);
536           NewBB->moveBefore(PN->getParent());
537         }
538       }
539
540       Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
541       if (!Code) {
542         // Insert the code into the end of the predecessor block.
543         BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
544       
545         SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
546         Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
547                                       OperandValToReplace->getType());
548       }
549       
550       // Replace the use of the operand Value with the new Phi we just created.
551       PN->setIncomingValue(i, Code);
552       Rewriter.clear();
553     }
554   }
555   DEBUG(std::cerr << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst);
556 }
557
558
559 /// isTargetConstant - Return true if the following can be referenced by the
560 /// immediate field of a target instruction.
561 static bool isTargetConstant(const SCEVHandle &V) {
562
563   // FIXME: Look at the target to decide if &GV is a legal constant immediate.
564   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
565     // PPC allows a sign-extended 16-bit immediate field.
566     if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
567         (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
568       return true;
569     return false;
570   }
571
572   return false;     // ENABLE this for x86
573
574   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
575     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
576       if (CE->getOpcode() == Instruction::Cast)
577         if (isa<GlobalValue>(CE->getOperand(0)))
578           // FIXME: should check to see that the dest is uintptr_t!
579           return true;
580   return false;
581 }
582
583 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
584 /// loop varying to the Imm operand.
585 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
586                                             Loop *L) {
587   if (Val->isLoopInvariant(L)) return;  // Nothing to do.
588   
589   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
590     std::vector<SCEVHandle> NewOps;
591     NewOps.reserve(SAE->getNumOperands());
592     
593     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
594       if (!SAE->getOperand(i)->isLoopInvariant(L)) {
595         // If this is a loop-variant expression, it must stay in the immediate
596         // field of the expression.
597         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
598       } else {
599         NewOps.push_back(SAE->getOperand(i));
600       }
601
602     if (NewOps.empty())
603       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
604     else
605       Val = SCEVAddExpr::get(NewOps);
606   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
607     // Try to pull immediates out of the start value of nested addrec's.
608     SCEVHandle Start = SARE->getStart();
609     MoveLoopVariantsToImediateField(Start, Imm, L);
610     
611     std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
612     Ops[0] = Start;
613     Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
614   } else {
615     // Otherwise, all of Val is variant, move the whole thing over.
616     Imm = SCEVAddExpr::get(Imm, Val);
617     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
618   }
619 }
620
621
622 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
623 /// that can fit into the immediate field of instructions in the target.
624 /// Accumulate these immediate values into the Imm value.
625 static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
626                                 bool isAddress, Loop *L) {
627   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
628     std::vector<SCEVHandle> NewOps;
629     NewOps.reserve(SAE->getNumOperands());
630     
631     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
632       if (isAddress && isTargetConstant(SAE->getOperand(i))) {
633         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
634       } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
635         // If this is a loop-variant expression, it must stay in the immediate
636         // field of the expression.
637         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
638       } else {
639         NewOps.push_back(SAE->getOperand(i));
640       }
641
642     if (NewOps.empty())
643       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
644     else
645       Val = SCEVAddExpr::get(NewOps);
646     return;
647   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
648     // Try to pull immediates out of the start value of nested addrec's.
649     SCEVHandle Start = SARE->getStart();
650     MoveImmediateValues(Start, Imm, isAddress, L);
651     
652     if (Start != SARE->getStart()) {
653       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
654       Ops[0] = Start;
655       Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
656     }
657     return;
658   }
659
660   // Loop-variant expressions must stay in the immediate field of the
661   // expression.
662   if ((isAddress && isTargetConstant(Val)) ||
663       !Val->isLoopInvariant(L)) {
664     Imm = SCEVAddExpr::get(Imm, Val);
665     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
666     return;
667   }
668
669   // Otherwise, no immediates to move.
670 }
671
672
673 /// IncrementAddExprUses - Decompose the specified expression into its added
674 /// subexpressions, and increment SubExpressionUseCounts for each of these
675 /// decomposed parts.
676 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
677                              SCEVHandle Expr) {
678   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
679     for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
680       SeparateSubExprs(SubExprs, AE->getOperand(j));
681   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
682     SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
683     if (SARE->getOperand(0) == Zero) {
684       SubExprs.push_back(Expr);
685     } else {
686       // Compute the addrec with zero as its base.
687       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
688       Ops[0] = Zero;   // Start with zero base.
689       SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
690       
691
692       SeparateSubExprs(SubExprs, SARE->getOperand(0));
693     }
694   } else if (!isa<SCEVConstant>(Expr) ||
695              !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
696     // Do not add zero.
697     SubExprs.push_back(Expr);
698   }
699 }
700
701
702 /// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
703 /// removing any common subexpressions from it.  Anything truly common is
704 /// removed, accumulated, and returned.  This looks for things like (a+b+c) and
705 /// (a+c+d) -> (a+c).  The common expression is *removed* from the Bases.
706 static SCEVHandle 
707 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
708   unsigned NumUses = Uses.size();
709
710   // Only one use?  Use its base, regardless of what it is!
711   SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
712   SCEVHandle Result = Zero;
713   if (NumUses == 1) {
714     std::swap(Result, Uses[0].Base);
715     return Result;
716   }
717
718   // To find common subexpressions, count how many of Uses use each expression.
719   // If any subexpressions are used Uses.size() times, they are common.
720   std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
721   
722   std::vector<SCEVHandle> SubExprs;
723   for (unsigned i = 0; i != NumUses; ++i) {
724     // If the base is zero (which is common), return zero now, there are no
725     // CSEs we can find.
726     if (Uses[i].Base == Zero) return Zero;
727
728     // Split the expression into subexprs.
729     SeparateSubExprs(SubExprs, Uses[i].Base);
730     // Add one to SubExpressionUseCounts for each subexpr present.
731     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
732       SubExpressionUseCounts[SubExprs[j]]++;
733     SubExprs.clear();
734   }
735
736
737   // Now that we know how many times each is used, build Result.
738   for (std::map<SCEVHandle, unsigned>::iterator I =
739        SubExpressionUseCounts.begin(), E = SubExpressionUseCounts.end();
740        I != E; )
741     if (I->second == NumUses) {  // Found CSE!
742       Result = SCEVAddExpr::get(Result, I->first);
743       ++I;
744     } else {
745       // Remove non-cse's from SubExpressionUseCounts.
746       SubExpressionUseCounts.erase(I++);
747     }
748   
749   // If we found no CSE's, return now.
750   if (Result == Zero) return Result;
751   
752   // Otherwise, remove all of the CSE's we found from each of the base values.
753   for (unsigned i = 0; i != NumUses; ++i) {
754     // Split the expression into subexprs.
755     SeparateSubExprs(SubExprs, Uses[i].Base);
756
757     // Remove any common subexpressions.
758     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
759       if (SubExpressionUseCounts.count(SubExprs[j])) {
760         SubExprs.erase(SubExprs.begin()+j);
761         --j; --e;
762       }
763     
764     // Finally, the non-shared expressions together.
765     if (SubExprs.empty())
766       Uses[i].Base = Zero;
767     else
768       Uses[i].Base = SCEVAddExpr::get(SubExprs);
769     SubExprs.clear();
770   }
771  
772   return Result;
773 }
774
775
776 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
777 /// stride of IV.  All of the users may have different starting values, and this
778 /// may not be the only stride (we know it is if isOnlyStride is true).
779 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
780                                                       IVUsersOfOneStride &Uses,
781                                                       Loop *L,
782                                                       bool isOnlyStride) {
783   // Transform our list of users and offsets to a bit more complex table.  In
784   // this new vector, each 'BasedUser' contains 'Base' the base of the
785   // strided accessas well as the old information from Uses.  We progressively
786   // move information from the Base field to the Imm field, until we eventually
787   // have the full access expression to rewrite the use.
788   std::vector<BasedUser> UsersToProcess;
789   UsersToProcess.reserve(Uses.Users.size());
790   for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
791     UsersToProcess.push_back(Uses.Users[i]);
792     
793     // Move any loop invariant operands from the offset field to the immediate
794     // field of the use, so that we don't try to use something before it is
795     // computed.
796     MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
797                                     UsersToProcess.back().Imm, L);
798     assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
799            "Base value is not loop invariant!");
800   }
801   
802   // We now have a whole bunch of uses of like-strided induction variables, but
803   // they might all have different bases.  We want to emit one PHI node for this
804   // stride which we fold as many common expressions (between the IVs) into as
805   // possible.  Start by identifying the common expressions in the base values 
806   // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
807   // "A+B"), emit it to the preheader, then remove the expression from the
808   // UsersToProcess base values.
809   SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
810   
811   // Next, figure out what we can represent in the immediate fields of
812   // instructions.  If we can represent anything there, move it to the imm
813   // fields of the BasedUsers.  We do this so that it increases the commonality
814   // of the remaining uses.
815   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
816     // If the user is not in the current loop, this means it is using the exit
817     // value of the IV.  Do not put anything in the base, make sure it's all in
818     // the immediate field to allow as much factoring as possible.
819     if (!L->contains(UsersToProcess[i].Inst->getParent())) {
820       UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
821                                                UsersToProcess[i].Base);
822       UsersToProcess[i].Base = 
823         SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
824     } else {
825       
826       // Addressing modes can be folded into loads and stores.  Be careful that
827       // the store is through the expression, not of the expression though.
828       bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
829       if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
830         if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
831           isAddress = true;
832       
833       MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
834                           isAddress, L);
835     }
836   }
837  
838   // Now that we know what we need to do, insert the PHI node itself.
839   //
840   DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
841         << *CommonExprs << " :\n");
842     
843   SCEVExpander Rewriter(*SE, *LI);
844   SCEVExpander PreheaderRewriter(*SE, *LI);
845   
846   BasicBlock  *Preheader = L->getLoopPreheader();
847   Instruction *PreInsertPt = Preheader->getTerminator();
848   Instruction *PhiInsertBefore = L->getHeader()->begin();
849   
850   BasicBlock *LatchBlock = L->getLoopLatch();
851   
852   // Create a new Phi for this base, and stick it in the loop header.
853   const Type *ReplacedTy = CommonExprs->getType();
854   PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
855   ++NumInserted;
856   
857   // Insert the stride into the preheader.
858   Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
859                                                    ReplacedTy);
860   if (!isa<ConstantInt>(StrideV)) ++NumVariable;
861
862
863   // Emit the initial base value into the loop preheader, and add it to the
864   // Phi node.
865   Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
866                                                     ReplacedTy);
867   NewPHI->addIncoming(PHIBaseV, Preheader);
868   
869   // Emit the increment of the base value before the terminator of the loop
870   // latch block, and add it to the Phi node.
871   SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
872                                        SCEVUnknown::get(StrideV));
873   
874   Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
875                                        ReplacedTy);
876   IncV->setName(NewPHI->getName()+".inc");
877   NewPHI->addIncoming(IncV, LatchBlock);
878
879   // Sort by the base value, so that all IVs with identical bases are next to
880   // each other.
881   std::sort(UsersToProcess.begin(), UsersToProcess.end());
882   while (!UsersToProcess.empty()) {
883     SCEVHandle Base = UsersToProcess.front().Base;
884
885     DEBUG(std::cerr << "  INSERTING code for BASE = " << *Base << ":\n");
886    
887     // Emit the code for Base into the preheader.
888     Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
889                                                    ReplacedTy);
890     
891     // If BaseV is a constant other than 0, make sure that it gets inserted into
892     // the preheader, instead of being forward substituted into the uses.  We do
893     // this by forcing a noop cast to be inserted into the preheader in this
894     // case.
895     if (Constant *C = dyn_cast<Constant>(BaseV))
896       if (!C->isNullValue() && !isTargetConstant(Base)) {
897         // We want this constant emitted into the preheader!
898         BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
899                              PreInsertPt);       
900       }
901     
902     // Emit the code to add the immediate offset to the Phi value, just before
903     // the instructions that we identified as using this stride and base.
904     while (!UsersToProcess.empty() && UsersToProcess.front().Base == Base) {
905       BasedUser &User = UsersToProcess.front();
906
907       // If this instruction wants to use the post-incremented value, move it
908       // after the post-inc and use its value instead of the PHI.
909       Value *RewriteOp = NewPHI;
910       if (User.isUseOfPostIncrementedValue) {
911         RewriteOp = IncV;
912
913         // If this user is in the loop, make sure it is the last thing in the
914         // loop to ensure it is dominated by the increment.
915         if (L->contains(User.Inst->getParent()))
916           User.Inst->moveBefore(LatchBlock->getTerminator());
917       }
918       SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
919
920       // Clear the SCEVExpander's expression map so that we are guaranteed
921       // to have the code emitted where we expect it.
922       Rewriter.clear();
923      
924       // Now that we know what we need to do, insert code before User for the
925       // immediate and any loop-variant expressions.
926       if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
927         // Add BaseV to the PHI value if needed.
928         RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
929       
930       User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
931
932       // Mark old value we replaced as possibly dead, so that it is elminated
933       // if we just replaced the last use of that value.
934       DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
935
936       UsersToProcess.erase(UsersToProcess.begin());
937       ++NumReduced;
938     }
939     // TODO: Next, find out which base index is the most common, pull it out.
940   }
941
942   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
943   // different starting values, into different PHIs.
944 }
945
946 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
947 // uses in the loop, look to see if we can eliminate some, in favor of using
948 // common indvars for the different uses.
949 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
950   // TODO: implement optzns here.
951
952
953
954
955   // Finally, get the terminating condition for the loop if possible.  If we
956   // can, we want to change it to use a post-incremented version of its
957   // induction variable, to allow coallescing the live ranges for the IV into
958   // one register value.
959   PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
960   BasicBlock  *Preheader = L->getLoopPreheader();
961   BasicBlock *LatchBlock =
962    SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
963   BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
964   if (!TermBr || TermBr->isUnconditional() ||
965       !isa<SetCondInst>(TermBr->getCondition()))
966     return;
967   SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
968
969   // Search IVUsesByStride to find Cond's IVUse if there is one.
970   IVStrideUse *CondUse = 0;
971   const SCEVHandle *CondStride = 0;
972
973   for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator 
974          I = IVUsesByStride.begin(), E = IVUsesByStride.end();
975        I != E && !CondUse; ++I)
976     for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
977            E = I->second.Users.end(); UI != E; ++UI)
978       if (UI->User == Cond) {
979         CondUse = &*UI;
980         CondStride = &I->first;
981         // NOTE: we could handle setcc instructions with multiple uses here, but
982         // InstCombine does it as well for simple uses, it's not clear that it
983         // occurs enough in real life to handle.
984         break;
985       }
986   if (!CondUse) return;  // setcc doesn't use the IV.
987
988   // setcc stride is complex, don't mess with users.
989   // FIXME: Evaluate whether this is a good idea or not.
990   if (!isa<SCEVConstant>(*CondStride)) return;
991
992   // It's possible for the setcc instruction to be anywhere in the loop, and
993   // possible for it to have multiple users.  If it is not immediately before
994   // the latch block branch, move it.
995   if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
996     if (Cond->hasOneUse()) {   // Condition has a single use, just move it.
997       Cond->moveBefore(TermBr);
998     } else {
999       // Otherwise, clone the terminating condition and insert into the loopend.
1000       Cond = cast<SetCondInst>(Cond->clone());
1001       Cond->setName(L->getHeader()->getName() + ".termcond");
1002       LatchBlock->getInstList().insert(TermBr, Cond);
1003       
1004       // Clone the IVUse, as the old use still exists!
1005       IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
1006                                          CondUse->OperandValToReplace);
1007       CondUse = &IVUsesByStride[*CondStride].Users.back();
1008     }
1009   }
1010
1011   // If we get to here, we know that we can transform the setcc instruction to
1012   // use the post-incremented version of the IV, allowing us to coallesce the
1013   // live ranges for the IV correctly.
1014   CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
1015   CondUse->isUseOfPostIncrementedValue = true;
1016 }
1017
1018 void LoopStrengthReduce::runOnLoop(Loop *L) {
1019   // First step, transform all loops nesting inside of this loop.
1020   for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1021     runOnLoop(*I);
1022
1023   // Next, find all uses of induction variables in this loop, and catagorize
1024   // them by stride.  Start by finding all of the PHI nodes in the header for
1025   // this loop.  If they are induction variables, inspect their uses.
1026   std::set<Instruction*> Processed;   // Don't reprocess instructions.
1027   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
1028     AddUsersIfInteresting(I, L, Processed);
1029
1030   // If we have nothing to do, return.
1031   if (IVUsesByStride.empty()) return;
1032
1033   // Optimize induction variables.  Some indvar uses can be transformed to use
1034   // strides that will be needed for other purposes.  A common example of this
1035   // is the exit test for the loop, which can often be rewritten to use the
1036   // computation of some other indvar to decide when to terminate the loop.
1037   OptimizeIndvars(L);
1038
1039
1040   // FIXME: We can widen subreg IV's here for RISC targets.  e.g. instead of
1041   // doing computation in byte values, promote to 32-bit values if safe.
1042
1043   // FIXME: Attempt to reuse values across multiple IV's.  In particular, we
1044   // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1045   // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.  Need
1046   // to be careful that IV's are all the same type.  Only works for intptr_t
1047   // indvars.
1048
1049   // If we only have one stride, we can more aggressively eliminate some things.
1050   bool HasOneStride = IVUsesByStride.size() == 1;
1051   
1052   if (IVUsesByStride.size() == 123)
1053     std::cerr << "FOO!\n";
1054
1055   // Note: this processes each stride/type pair individually.  All users passed
1056   // into StrengthReduceStridedIVUsers have the same type AND stride.  Also,
1057   // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1058   // This extra layer of indirection makes the ordering of strides deterministic
1059   // - not dependent on map order.
1060   for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1061     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
1062       IVUsesByStride.find(StrideOrder[Stride]);
1063     assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1064     StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1065   }
1066
1067   // Clean up after ourselves
1068   if (!DeadInsts.empty()) {
1069     DeleteTriviallyDeadInstructions(DeadInsts);
1070
1071     BasicBlock::iterator I = L->getHeader()->begin();
1072     PHINode *PN;
1073     while ((PN = dyn_cast<PHINode>(I))) {
1074       ++I;  // Preincrement iterator to avoid invalidating it when deleting PN.
1075       
1076       // At this point, we know that we have killed one or more GEP
1077       // instructions.  It is worth checking to see if the cann indvar is also
1078       // dead, so that we can remove it as well.  The requirements for the cann
1079       // indvar to be considered dead are:
1080       // 1. the cann indvar has one use
1081       // 2. the use is an add instruction
1082       // 3. the add has one use
1083       // 4. the add is used by the cann indvar
1084       // If all four cases above are true, then we can remove both the add and
1085       // the cann indvar.
1086       // FIXME: this needs to eliminate an induction variable even if it's being
1087       // compared against some value to decide loop termination.
1088       if (PN->hasOneUse()) {
1089         BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
1090         if (BO && BO->hasOneUse()) {
1091           if (PN == *(BO->use_begin())) {
1092             DeadInsts.insert(BO);
1093             // Break the cycle, then delete the PHI.
1094             PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1095             SE->deleteInstructionFromRecords(PN);
1096             PN->eraseFromParent();
1097           }
1098         }
1099       }
1100     }
1101     DeleteTriviallyDeadInstructions(DeadInsts);
1102   }
1103
1104   CastedPointers.clear();
1105   IVUsesByStride.clear();
1106   StrideOrder.clear();
1107   return;
1108 }