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