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