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