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