5c007551afb629e18b0f8d7fdba74eae0f4d6ad4
[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   // If we are inserting the base and imm values in the same block, make sure to
565   // adjust the IP position if insertion reused a result.
566   if (IP == BaseInsertPt)
567     IP = Rewriter.getInsertionPoint();
568   
569   // Always emit the immediate (if non-zero) into the same block as the user.
570   SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
571   return Rewriter.expandCodeFor(NewValSCEV, IP,
572                                 OperandValToReplace->getType());
573   
574 }
575
576
577 // Once we rewrite the code to insert the new IVs we want, update the
578 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
579 // to it.
580 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
581                                                SCEVExpander &Rewriter,
582                                                Loop *L, Pass *P) {
583   if (!isa<PHINode>(Inst)) {
584     // By default, insert code at the user instruction.
585     BasicBlock::iterator InsertPt = Inst;
586     
587     // However, if the Operand is itself an instruction, the (potentially
588     // complex) inserted code may be shared by many users.  Because of this, we
589     // want to emit code for the computation of the operand right before its old
590     // computation.  This is usually safe, because we obviously used to use the
591     // computation when it was computed in its current block.  However, in some
592     // cases (e.g. use of a post-incremented induction variable) the NewBase
593     // value will be pinned to live somewhere after the original computation.
594     // In this case, we have to back off.
595     if (!isUseOfPostIncrementedValue) {
596       if (Instruction *OpInst = dyn_cast<Instruction>(OperandValToReplace)) { 
597         InsertPt = OpInst;
598         while (isa<PHINode>(InsertPt)) ++InsertPt;
599       }
600     }
601     Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
602     // Replace the use of the operand Value with the new Phi we just created.
603     Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
604     DOUT << "    CHANGED: IMM =" << *Imm;
605     DOUT << "  \tNEWBASE =" << *NewBase;
606     DOUT << "  \tInst = " << *Inst;
607     return;
608   }
609   
610   // PHI nodes are more complex.  We have to insert one copy of the NewBase+Imm
611   // expression into each operand block that uses it.  Note that PHI nodes can
612   // have multiple entries for the same predecessor.  We use a map to make sure
613   // that a PHI node only has a single Value* for each predecessor (which also
614   // prevents us from inserting duplicate code in some blocks).
615   std::map<BasicBlock*, Value*> InsertedCode;
616   PHINode *PN = cast<PHINode>(Inst);
617   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
618     if (PN->getIncomingValue(i) == OperandValToReplace) {
619       // If this is a critical edge, split the edge so that we do not insert the
620       // code on all predecessor/successor paths.  We do this unless this is the
621       // canonical backedge for this loop, as this can make some inserted code
622       // be in an illegal position.
623       BasicBlock *PHIPred = PN->getIncomingBlock(i);
624       if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
625           (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
626         
627         // First step, split the critical edge.
628         SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
629             
630         // Next step: move the basic block.  In particular, if the PHI node
631         // is outside of the loop, and PredTI is in the loop, we want to
632         // move the block to be immediately before the PHI block, not
633         // immediately after PredTI.
634         if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
635           BasicBlock *NewBB = PN->getIncomingBlock(i);
636           NewBB->moveBefore(PN->getParent());
637         }
638         
639         // Splitting the edge can reduce the number of PHI entries we have.
640         e = PN->getNumIncomingValues();
641       }
642
643       Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
644       if (!Code) {
645         // Insert the code into the end of the predecessor block.
646         Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
647         Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
648       }
649       
650       // Replace the use of the operand Value with the new Phi we just created.
651       PN->setIncomingValue(i, Code);
652       Rewriter.clear();
653     }
654   }
655   DOUT << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst;
656 }
657
658
659 /// isTargetConstant - Return true if the following can be referenced by the
660 /// immediate field of a target instruction.
661 static bool isTargetConstant(const SCEVHandle &V, const Type *UseTy,
662                              const TargetLowering *TLI) {
663   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
664     int64_t VC = SC->getValue()->getSExtValue();
665     if (TLI) {
666       TargetLowering::AddrMode AM;
667       AM.BaseOffs = VC;
668       return TLI->isLegalAddressingMode(AM, UseTy);
669     } else {
670       // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
671       return (VC > -(1 << 16) && VC < (1 << 16)-1);
672     }
673   }
674
675   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
676     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
677       if (TLI && CE->getOpcode() == Instruction::PtrToInt) {
678         Constant *Op0 = CE->getOperand(0);
679         if (GlobalValue *GV = dyn_cast<GlobalValue>(Op0)) {
680           TargetLowering::AddrMode AM;
681           AM.BaseGV = GV;
682           return TLI->isLegalAddressingMode(AM, UseTy);
683         }
684       }
685   return false;
686 }
687
688 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
689 /// loop varying to the Imm operand.
690 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
691                                             Loop *L) {
692   if (Val->isLoopInvariant(L)) return;  // Nothing to do.
693   
694   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
695     std::vector<SCEVHandle> NewOps;
696     NewOps.reserve(SAE->getNumOperands());
697     
698     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
699       if (!SAE->getOperand(i)->isLoopInvariant(L)) {
700         // If this is a loop-variant expression, it must stay in the immediate
701         // field of the expression.
702         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
703       } else {
704         NewOps.push_back(SAE->getOperand(i));
705       }
706
707     if (NewOps.empty())
708       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
709     else
710       Val = SCEVAddExpr::get(NewOps);
711   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
712     // Try to pull immediates out of the start value of nested addrec's.
713     SCEVHandle Start = SARE->getStart();
714     MoveLoopVariantsToImediateField(Start, Imm, L);
715     
716     std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
717     Ops[0] = Start;
718     Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
719   } else {
720     // Otherwise, all of Val is variant, move the whole thing over.
721     Imm = SCEVAddExpr::get(Imm, Val);
722     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
723   }
724 }
725
726
727 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
728 /// that can fit into the immediate field of instructions in the target.
729 /// Accumulate these immediate values into the Imm value.
730 static void MoveImmediateValues(const TargetLowering *TLI,
731                                 Instruction *User,
732                                 SCEVHandle &Val, SCEVHandle &Imm,
733                                 bool isAddress, Loop *L) {
734   const Type *UseTy = User->getType();
735   if (StoreInst *SI = dyn_cast<StoreInst>(User))
736     UseTy = SI->getOperand(0)->getType();
737
738   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
739     std::vector<SCEVHandle> NewOps;
740     NewOps.reserve(SAE->getNumOperands());
741     
742     for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
743       SCEVHandle NewOp = SAE->getOperand(i);
744       MoveImmediateValues(TLI, User, NewOp, Imm, isAddress, L);
745       
746       if (!NewOp->isLoopInvariant(L)) {
747         // If this is a loop-variant expression, it must stay in the immediate
748         // field of the expression.
749         Imm = SCEVAddExpr::get(Imm, NewOp);
750       } else {
751         NewOps.push_back(NewOp);
752       }
753     }
754
755     if (NewOps.empty())
756       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
757     else
758       Val = SCEVAddExpr::get(NewOps);
759     return;
760   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
761     // Try to pull immediates out of the start value of nested addrec's.
762     SCEVHandle Start = SARE->getStart();
763     MoveImmediateValues(TLI, User, Start, Imm, isAddress, L);
764     
765     if (Start != SARE->getStart()) {
766       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
767       Ops[0] = Start;
768       Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
769     }
770     return;
771   } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
772     // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
773     if (isAddress && isTargetConstant(SME->getOperand(0), UseTy, TLI) &&
774         SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
775
776       SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
777       SCEVHandle NewOp = SME->getOperand(1);
778       MoveImmediateValues(TLI, User, NewOp, SubImm, isAddress, L);
779       
780       // If we extracted something out of the subexpressions, see if we can 
781       // simplify this!
782       if (NewOp != SME->getOperand(1)) {
783         // Scale SubImm up by "8".  If the result is a target constant, we are
784         // good.
785         SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
786         if (isTargetConstant(SubImm, UseTy, TLI)) {
787           // Accumulate the immediate.
788           Imm = SCEVAddExpr::get(Imm, SubImm);
789           
790           // Update what is left of 'Val'.
791           Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
792           return;
793         }
794       }
795     }
796   }
797
798   // Loop-variant expressions must stay in the immediate field of the
799   // expression.
800   if ((isAddress && isTargetConstant(Val, UseTy, TLI)) ||
801       !Val->isLoopInvariant(L)) {
802     Imm = SCEVAddExpr::get(Imm, Val);
803     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
804     return;
805   }
806
807   // Otherwise, no immediates to move.
808 }
809
810
811 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
812 /// added together.  This is used to reassociate common addition subexprs
813 /// together for maximal sharing when rewriting bases.
814 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
815                              SCEVHandle Expr) {
816   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
817     for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
818       SeparateSubExprs(SubExprs, AE->getOperand(j));
819   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
820     SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
821     if (SARE->getOperand(0) == Zero) {
822       SubExprs.push_back(Expr);
823     } else {
824       // Compute the addrec with zero as its base.
825       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
826       Ops[0] = Zero;   // Start with zero base.
827       SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
828       
829
830       SeparateSubExprs(SubExprs, SARE->getOperand(0));
831     }
832   } else if (!isa<SCEVConstant>(Expr) ||
833              !cast<SCEVConstant>(Expr)->getValue()->isZero()) {
834     // Do not add zero.
835     SubExprs.push_back(Expr);
836   }
837 }
838
839
840 /// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
841 /// removing any common subexpressions from it.  Anything truly common is
842 /// removed, accumulated, and returned.  This looks for things like (a+b+c) and
843 /// (a+c+d) -> (a+c).  The common expression is *removed* from the Bases.
844 static SCEVHandle 
845 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
846   unsigned NumUses = Uses.size();
847
848   // Only one use?  Use its base, regardless of what it is!
849   SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
850   SCEVHandle Result = Zero;
851   if (NumUses == 1) {
852     std::swap(Result, Uses[0].Base);
853     return Result;
854   }
855
856   // To find common subexpressions, count how many of Uses use each expression.
857   // If any subexpressions are used Uses.size() times, they are common.
858   std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
859   
860   // UniqueSubExprs - Keep track of all of the subexpressions we see in the
861   // order we see them.
862   std::vector<SCEVHandle> UniqueSubExprs;
863
864   std::vector<SCEVHandle> SubExprs;
865   for (unsigned i = 0; i != NumUses; ++i) {
866     // If the base is zero (which is common), return zero now, there are no
867     // CSEs we can find.
868     if (Uses[i].Base == Zero) return Zero;
869
870     // Split the expression into subexprs.
871     SeparateSubExprs(SubExprs, Uses[i].Base);
872     // Add one to SubExpressionUseCounts for each subexpr present.
873     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
874       if (++SubExpressionUseCounts[SubExprs[j]] == 1)
875         UniqueSubExprs.push_back(SubExprs[j]);
876     SubExprs.clear();
877   }
878
879   // Now that we know how many times each is used, build Result.  Iterate over
880   // UniqueSubexprs so that we have a stable ordering.
881   for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
882     std::map<SCEVHandle, unsigned>::iterator I = 
883        SubExpressionUseCounts.find(UniqueSubExprs[i]);
884     assert(I != SubExpressionUseCounts.end() && "Entry not found?");
885     if (I->second == NumUses) {  // Found CSE!
886       Result = SCEVAddExpr::get(Result, I->first);
887     } else {
888       // Remove non-cse's from SubExpressionUseCounts.
889       SubExpressionUseCounts.erase(I);
890     }
891   }
892   
893   // If we found no CSE's, return now.
894   if (Result == Zero) return Result;
895   
896   // Otherwise, remove all of the CSE's we found from each of the base values.
897   for (unsigned i = 0; i != NumUses; ++i) {
898     // Split the expression into subexprs.
899     SeparateSubExprs(SubExprs, Uses[i].Base);
900
901     // Remove any common subexpressions.
902     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
903       if (SubExpressionUseCounts.count(SubExprs[j])) {
904         SubExprs.erase(SubExprs.begin()+j);
905         --j; --e;
906       }
907     
908     // Finally, the non-shared expressions together.
909     if (SubExprs.empty())
910       Uses[i].Base = Zero;
911     else
912       Uses[i].Base = SCEVAddExpr::get(SubExprs);
913     SubExprs.clear();
914   }
915  
916   return Result;
917 }
918
919 /// isZero - returns true if the scalar evolution expression is zero.
920 ///
921 static bool isZero(SCEVHandle &V) {
922   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
923     return SC->getValue()->isZero();
924   return false;
925 }
926
927 /// ValidStride - Check whether the given Scale is valid for all loads and 
928 /// stores in UsersToProcess.
929 ///
930 bool LoopStrengthReduce::ValidStride(int64_t Scale, 
931                                const std::vector<BasedUser>& UsersToProcess) {
932   for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
933     // If this is a load or other access, pass the type of the access in.
934     const Type *AccessTy = Type::VoidTy;
935     if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
936       AccessTy = SI->getOperand(0)->getType();
937     else if (LoadInst *LI = dyn_cast<LoadInst>(UsersToProcess[i].Inst))
938       AccessTy = LI->getType();
939     
940     TargetLowering::AddrMode AM;
941     if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
942       AM.BaseOffs = SC->getValue()->getSExtValue();
943     AM.Scale = Scale;
944
945     // If load[imm+r*scale] is illegal, bail out.
946     if (!TLI->isLegalAddressingMode(AM, AccessTy))
947       return false;
948   }
949   return true;
950 }
951
952 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
953 /// of a previous stride and it is a legal value for the target addressing
954 /// mode scale component. This allows the users of this stride to be rewritten
955 /// as prev iv * factor. It returns 0 if no reuse is possible.
956 unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride, 
957                                 IVExpr &IV, const Type *Ty,
958                                 const std::vector<BasedUser>& UsersToProcess) {
959   if (!TLI) return 0;
960
961   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
962     int64_t SInt = SC->getValue()->getSExtValue();
963     if (SInt == 1) return 0;
964
965     for (std::map<SCEVHandle, IVsOfOneStride>::iterator SI= IVsByStride.begin(),
966            SE = IVsByStride.end(); SI != SE; ++SI) {
967       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
968       if (SInt != -SSInt &&
969           (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
970         continue;
971       int64_t Scale = SInt / SSInt;
972       // Check that this stride is valid for all the types used for loads and
973       // stores; if it can be used for some and not others, we might as well use
974       // the original stride everywhere, since we have to create the IV for it
975       // anyway.
976       if (ValidStride(Scale, UsersToProcess))
977         for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
978                IE = SI->second.IVs.end(); II != IE; ++II)
979           // FIXME: Only handle base == 0 for now.
980           // Only reuse previous IV if it would not require a type conversion.
981           if (isZero(II->Base) && II->Base->getType() == Ty) {
982             IV = *II;
983             return Scale;
984           }
985     }
986   }
987   return 0;
988 }
989
990 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
991 /// returns true if Val's isUseOfPostIncrementedValue is true.
992 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
993   return Val.isUseOfPostIncrementedValue;
994 }
995
996 /// isNonConstantNegative - REturn true if the specified scev is negated, but
997 /// not a constant.
998 static bool isNonConstantNegative(const SCEVHandle &Expr) {
999   SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1000   if (!Mul) return false;
1001   
1002   // If there is a constant factor, it will be first.
1003   SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1004   if (!SC) return false;
1005   
1006   // Return true if the value is negative, this matches things like (-42 * V).
1007   return SC->getValue()->getValue().isNegative();
1008 }
1009
1010 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1011 /// stride of IV.  All of the users may have different starting values, and this
1012 /// may not be the only stride (we know it is if isOnlyStride is true).
1013 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1014                                                       IVUsersOfOneStride &Uses,
1015                                                       Loop *L,
1016                                                       bool isOnlyStride) {
1017   // Transform our list of users and offsets to a bit more complex table.  In
1018   // this new vector, each 'BasedUser' contains 'Base' the base of the
1019   // strided accessas well as the old information from Uses.  We progressively
1020   // move information from the Base field to the Imm field, until we eventually
1021   // have the full access expression to rewrite the use.
1022   std::vector<BasedUser> UsersToProcess;
1023   UsersToProcess.reserve(Uses.Users.size());
1024   for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
1025     UsersToProcess.push_back(Uses.Users[i]);
1026     
1027     // Move any loop invariant operands from the offset field to the immediate
1028     // field of the use, so that we don't try to use something before it is
1029     // computed.
1030     MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
1031                                     UsersToProcess.back().Imm, L);
1032     assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1033            "Base value is not loop invariant!");
1034   }
1035
1036   // We now have a whole bunch of uses of like-strided induction variables, but
1037   // they might all have different bases.  We want to emit one PHI node for this
1038   // stride which we fold as many common expressions (between the IVs) into as
1039   // possible.  Start by identifying the common expressions in the base values 
1040   // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1041   // "A+B"), emit it to the preheader, then remove the expression from the
1042   // UsersToProcess base values.
1043   SCEVHandle CommonExprs =
1044     RemoveCommonExpressionsFromUseBases(UsersToProcess);
1045   
1046   // Next, figure out what we can represent in the immediate fields of
1047   // instructions.  If we can represent anything there, move it to the imm
1048   // fields of the BasedUsers.  We do this so that it increases the commonality
1049   // of the remaining uses.
1050   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1051     // If the user is not in the current loop, this means it is using the exit
1052     // value of the IV.  Do not put anything in the base, make sure it's all in
1053     // the immediate field to allow as much factoring as possible.
1054     if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1055       UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
1056                                                UsersToProcess[i].Base);
1057       UsersToProcess[i].Base = 
1058         SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1059     } else {
1060       
1061       // Addressing modes can be folded into loads and stores.  Be careful that
1062       // the store is through the expression, not of the expression though.
1063       bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
1064       if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst)) {
1065         if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1066           isAddress = true;
1067       } else if (IntrinsicInst *II =
1068                    dyn_cast<IntrinsicInst>(UsersToProcess[i].Inst)) {
1069         // Addressing modes can also be folded into prefetches.
1070         if (II->getIntrinsicID() == Intrinsic::prefetch &&
1071             II->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1072           isAddress = true;
1073       }
1074       
1075       MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1076                           UsersToProcess[i].Imm, isAddress, L);
1077     }
1078   }
1079
1080   // Check if it is possible to reuse a IV with stride that is factor of this
1081   // stride. And the multiple is a number that can be encoded in the scale
1082   // field of the target addressing mode.  And we will have a valid
1083   // instruction after this substition, including the immediate field, if any.
1084   PHINode *NewPHI = NULL;
1085   Value   *IncV   = NULL;
1086   IVExpr   ReuseIV;
1087   unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
1088                                            CommonExprs->getType(),
1089                                            UsersToProcess);
1090   if (RewriteFactor != 0) {
1091     DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
1092          << " and BASE " << *ReuseIV.Base << " :\n";
1093     NewPHI = ReuseIV.PHI;
1094     IncV   = ReuseIV.IncV;
1095   }
1096
1097   const Type *ReplacedTy = CommonExprs->getType();
1098   
1099   // Now that we know what we need to do, insert the PHI node itself.
1100   //
1101   DOUT << "INSERTING IV of TYPE " << *ReplacedTy << " of STRIDE "
1102        << *Stride << " and BASE " << *CommonExprs << ": ";
1103
1104   SCEVExpander Rewriter(*SE, *LI);
1105   SCEVExpander PreheaderRewriter(*SE, *LI);
1106   
1107   BasicBlock  *Preheader = L->getLoopPreheader();
1108   Instruction *PreInsertPt = Preheader->getTerminator();
1109   Instruction *PhiInsertBefore = L->getHeader()->begin();
1110   
1111   BasicBlock *LatchBlock = L->getLoopLatch();
1112
1113
1114   // Emit the initial base value into the loop preheader.
1115   Value *CommonBaseV
1116     = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1117                                       ReplacedTy);
1118
1119   if (RewriteFactor == 0) {
1120     // Create a new Phi for this base, and stick it in the loop header.
1121     NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1122     ++NumInserted;
1123   
1124     // Add common base to the new Phi node.
1125     NewPHI->addIncoming(CommonBaseV, Preheader);
1126
1127     // If the stride is negative, insert a sub instead of an add for the
1128     // increment.
1129     bool isNegative = isNonConstantNegative(Stride);
1130     SCEVHandle IncAmount = Stride;
1131     if (isNegative)
1132       IncAmount = SCEV::getNegativeSCEV(Stride);
1133     
1134     // Insert the stride into the preheader.
1135     Value *StrideV = PreheaderRewriter.expandCodeFor(IncAmount, PreInsertPt,
1136                                                      ReplacedTy);
1137     if (!isa<ConstantInt>(StrideV)) ++NumVariable;
1138
1139     // Emit the increment of the base value before the terminator of the loop
1140     // latch block, and add it to the Phi node.
1141     SCEVHandle IncExp = SCEVUnknown::get(StrideV);
1142     if (isNegative)
1143       IncExp = SCEV::getNegativeSCEV(IncExp);
1144     IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI), IncExp);
1145   
1146     IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1147                                   ReplacedTy);
1148     IncV->setName(NewPHI->getName()+".inc");
1149     NewPHI->addIncoming(IncV, LatchBlock);
1150
1151     // Remember this in case a later stride is multiple of this.
1152     IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
1153     
1154     DOUT << " IV=%" << NewPHI->getNameStr() << " INC=%" << IncV->getNameStr();
1155   } else {
1156     Constant *C = dyn_cast<Constant>(CommonBaseV);
1157     if (!C ||
1158         (!C->isNullValue() &&
1159          !isTargetConstant(SCEVUnknown::get(CommonBaseV), ReplacedTy, TLI)))
1160       // We want the common base emitted into the preheader! This is just
1161       // using cast as a copy so BitCast (no-op cast) is appropriate
1162       CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(), 
1163                                     "commonbase", PreInsertPt);
1164   }
1165   DOUT << "\n";
1166
1167   // We want to emit code for users inside the loop first.  To do this, we
1168   // rearrange BasedUser so that the entries at the end have
1169   // isUseOfPostIncrementedValue = false, because we pop off the end of the
1170   // vector (so we handle them first).
1171   std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1172                  PartitionByIsUseOfPostIncrementedValue);
1173   
1174   // Sort this by base, so that things with the same base are handled
1175   // together.  By partitioning first and stable-sorting later, we are
1176   // guaranteed that within each base we will pop off users from within the
1177   // loop before users outside of the loop with a particular base.
1178   //
1179   // We would like to use stable_sort here, but we can't.  The problem is that
1180   // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1181   // we don't have anything to do a '<' comparison on.  Because we think the
1182   // number of uses is small, do a horrible bubble sort which just relies on
1183   // ==.
1184   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1185     // Get a base value.
1186     SCEVHandle Base = UsersToProcess[i].Base;
1187     
1188     // Compact everything with this base to be consequetive with this one.
1189     for (unsigned j = i+1; j != e; ++j) {
1190       if (UsersToProcess[j].Base == Base) {
1191         std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1192         ++i;
1193       }
1194     }
1195   }
1196
1197   // Process all the users now.  This outer loop handles all bases, the inner
1198   // loop handles all users of a particular base.
1199   while (!UsersToProcess.empty()) {
1200     SCEVHandle Base = UsersToProcess.back().Base;
1201
1202     // Emit the code for Base into the preheader.
1203     Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1204                                                    ReplacedTy);
1205
1206     DOUT << "  INSERTING code for BASE = " << *Base << ":";
1207     if (BaseV->hasName())
1208       DOUT << " Result value name = %" << BaseV->getNameStr();
1209     DOUT << "\n";
1210
1211     // If BaseV is a constant other than 0, make sure that it gets inserted into
1212     // the preheader, instead of being forward substituted into the uses.  We do
1213     // this by forcing a BitCast (noop cast) to be inserted into the preheader 
1214     // in this case.
1215     if (Constant *C = dyn_cast<Constant>(BaseV)) {
1216       if (!C->isNullValue() && !isTargetConstant(Base, ReplacedTy, TLI)) {
1217         // We want this constant emitted into the preheader! This is just
1218         // using cast as a copy so BitCast (no-op cast) is appropriate
1219         BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1220                              PreInsertPt);       
1221       }
1222     }
1223
1224     // Emit the code to add the immediate offset to the Phi value, just before
1225     // the instructions that we identified as using this stride and base.
1226     do {
1227       // FIXME: Use emitted users to emit other users.
1228       BasedUser &User = UsersToProcess.back();
1229
1230       // If this instruction wants to use the post-incremented value, move it
1231       // after the post-inc and use its value instead of the PHI.
1232       Value *RewriteOp = NewPHI;
1233       if (User.isUseOfPostIncrementedValue) {
1234         RewriteOp = IncV;
1235
1236         // If this user is in the loop, make sure it is the last thing in the
1237         // loop to ensure it is dominated by the increment.
1238         if (L->contains(User.Inst->getParent()))
1239           User.Inst->moveBefore(LatchBlock->getTerminator());
1240       }
1241       if (RewriteOp->getType() != ReplacedTy) {
1242         Instruction::CastOps opcode = Instruction::Trunc;
1243         if (ReplacedTy->getPrimitiveSizeInBits() ==
1244             RewriteOp->getType()->getPrimitiveSizeInBits())
1245           opcode = Instruction::BitCast;
1246         RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1247       }
1248
1249       SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1250
1251       // Clear the SCEVExpander's expression map so that we are guaranteed
1252       // to have the code emitted where we expect it.
1253       Rewriter.clear();
1254
1255       // If we are reusing the iv, then it must be multiplied by a constant
1256       // factor take advantage of addressing mode scale component.
1257       if (RewriteFactor != 0) {
1258         RewriteExpr =
1259           SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
1260                                                        RewriteExpr->getType()),
1261                            RewriteExpr);
1262
1263         // The common base is emitted in the loop preheader. But since we
1264         // are reusing an IV, it has not been used to initialize the PHI node.
1265         // Add it to the expression used to rewrite the uses.
1266         if (!isa<ConstantInt>(CommonBaseV) ||
1267             !cast<ConstantInt>(CommonBaseV)->isZero())
1268           RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1269                                          SCEVUnknown::get(CommonBaseV));
1270       }
1271
1272       // Now that we know what we need to do, insert code before User for the
1273       // immediate and any loop-variant expressions.
1274       if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
1275         // Add BaseV to the PHI value if needed.
1276         RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
1277
1278       User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
1279
1280       // Mark old value we replaced as possibly dead, so that it is elminated
1281       // if we just replaced the last use of that value.
1282       DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
1283
1284       UsersToProcess.pop_back();
1285       ++NumReduced;
1286
1287       // If there are any more users to process with the same base, process them
1288       // now.  We sorted by base above, so we just have to check the last elt.
1289     } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1290     // TODO: Next, find out which base index is the most common, pull it out.
1291   }
1292
1293   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1294   // different starting values, into different PHIs.
1295 }
1296
1297 /// FindIVForUser - If Cond has an operand that is an expression of an IV,
1298 /// set the IV user and stride information and return true, otherwise return
1299 /// false.
1300 bool LoopStrengthReduce::FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
1301                                        const SCEVHandle *&CondStride) {
1302   for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1303        ++Stride) {
1304     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
1305     IVUsesByStride.find(StrideOrder[Stride]);
1306     assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1307     
1308     for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1309          E = SI->second.Users.end(); UI != E; ++UI)
1310       if (UI->User == Cond) {
1311         // NOTE: we could handle setcc instructions with multiple uses here, but
1312         // InstCombine does it as well for simple uses, it's not clear that it
1313         // occurs enough in real life to handle.
1314         CondUse = &*UI;
1315         CondStride = &SI->first;
1316         return true;
1317       }
1318   }
1319   return false;
1320 }    
1321
1322 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1323 // uses in the loop, look to see if we can eliminate some, in favor of using
1324 // common indvars for the different uses.
1325 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1326   // TODO: implement optzns here.
1327
1328   // Finally, get the terminating condition for the loop if possible.  If we
1329   // can, we want to change it to use a post-incremented version of its
1330   // induction variable, to allow coalescing the live ranges for the IV into
1331   // one register value.
1332   PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1333   BasicBlock  *Preheader = L->getLoopPreheader();
1334   BasicBlock *LatchBlock =
1335    SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1336   BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1337   if (!TermBr || TermBr->isUnconditional() || 
1338       !isa<ICmpInst>(TermBr->getCondition()))
1339     return;
1340   ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1341
1342   // Search IVUsesByStride to find Cond's IVUse if there is one.
1343   IVStrideUse *CondUse = 0;
1344   const SCEVHandle *CondStride = 0;
1345
1346   if (!FindIVForUser(Cond, CondUse, CondStride))
1347     return; // setcc doesn't use the IV.
1348   
1349
1350   // It's possible for the setcc instruction to be anywhere in the loop, and
1351   // possible for it to have multiple users.  If it is not immediately before
1352   // the latch block branch, move it.
1353   if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1354     if (Cond->hasOneUse()) {   // Condition has a single use, just move it.
1355       Cond->moveBefore(TermBr);
1356     } else {
1357       // Otherwise, clone the terminating condition and insert into the loopend.
1358       Cond = cast<ICmpInst>(Cond->clone());
1359       Cond->setName(L->getHeader()->getName() + ".termcond");
1360       LatchBlock->getInstList().insert(TermBr, Cond);
1361       
1362       // Clone the IVUse, as the old use still exists!
1363       IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
1364                                          CondUse->OperandValToReplace);
1365       CondUse = &IVUsesByStride[*CondStride].Users.back();
1366     }
1367   }
1368
1369   // If we get to here, we know that we can transform the setcc instruction to
1370   // use the post-incremented version of the IV, allowing us to coalesce the
1371   // live ranges for the IV correctly.
1372   CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
1373   CondUse->isUseOfPostIncrementedValue = true;
1374 }
1375
1376 namespace {
1377   // Constant strides come first which in turns are sorted by their absolute
1378   // values. If absolute values are the same, then positive strides comes first.
1379   // e.g.
1380   // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1381   struct StrideCompare {
1382     bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1383       SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1384       SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1385       if (LHSC && RHSC) {
1386         int64_t  LV = LHSC->getValue()->getSExtValue();
1387         int64_t  RV = RHSC->getValue()->getSExtValue();
1388         uint64_t ALV = (LV < 0) ? -LV : LV;
1389         uint64_t ARV = (RV < 0) ? -RV : RV;
1390         if (ALV == ARV)
1391           return LV > RV;
1392         else
1393           return ALV < ARV;
1394       }
1395       return (LHSC && !RHSC);
1396     }
1397   };
1398 }
1399
1400 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
1401
1402   LI = &getAnalysis<LoopInfo>();
1403   EF = &getAnalysis<ETForest>();
1404   SE = &getAnalysis<ScalarEvolution>();
1405   TD = &getAnalysis<TargetData>();
1406   UIntPtrTy = TD->getIntPtrType();
1407
1408   // Find all uses of induction variables in this loop, and catagorize
1409   // them by stride.  Start by finding all of the PHI nodes in the header for
1410   // this loop.  If they are induction variables, inspect their uses.
1411   std::set<Instruction*> Processed;   // Don't reprocess instructions.
1412   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
1413     AddUsersIfInteresting(I, L, Processed);
1414
1415   // If we have nothing to do, return.
1416   if (IVUsesByStride.empty()) return false;
1417
1418   // Optimize induction variables.  Some indvar uses can be transformed to use
1419   // strides that will be needed for other purposes.  A common example of this
1420   // is the exit test for the loop, which can often be rewritten to use the
1421   // computation of some other indvar to decide when to terminate the loop.
1422   OptimizeIndvars(L);
1423
1424
1425   // FIXME: We can widen subreg IV's here for RISC targets.  e.g. instead of
1426   // doing computation in byte values, promote to 32-bit values if safe.
1427
1428   // FIXME: Attempt to reuse values across multiple IV's.  In particular, we
1429   // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1430   // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.  Need
1431   // to be careful that IV's are all the same type.  Only works for intptr_t
1432   // indvars.
1433
1434   // If we only have one stride, we can more aggressively eliminate some things.
1435   bool HasOneStride = IVUsesByStride.size() == 1;
1436
1437 #ifndef NDEBUG
1438   DOUT << "\nLSR on ";
1439   DEBUG(L->dump());
1440 #endif
1441
1442   // IVsByStride keeps IVs for one particular loop.
1443   IVsByStride.clear();
1444
1445   // Sort the StrideOrder so we process larger strides first.
1446   std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1447
1448   // Note: this processes each stride/type pair individually.  All users passed
1449   // into StrengthReduceStridedIVUsers have the same type AND stride.  Also,
1450   // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1451   // This extra layer of indirection makes the ordering of strides deterministic
1452   // - not dependent on map order.
1453   for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1454     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
1455       IVUsesByStride.find(StrideOrder[Stride]);
1456     assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1457     StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1458   }
1459
1460   // Clean up after ourselves
1461   if (!DeadInsts.empty()) {
1462     DeleteTriviallyDeadInstructions(DeadInsts);
1463
1464     BasicBlock::iterator I = L->getHeader()->begin();
1465     PHINode *PN;
1466     while ((PN = dyn_cast<PHINode>(I))) {
1467       ++I;  // Preincrement iterator to avoid invalidating it when deleting PN.
1468       
1469       // At this point, we know that we have killed one or more GEP
1470       // instructions.  It is worth checking to see if the cann indvar is also
1471       // dead, so that we can remove it as well.  The requirements for the cann
1472       // indvar to be considered dead are:
1473       // 1. the cann indvar has one use
1474       // 2. the use is an add instruction
1475       // 3. the add has one use
1476       // 4. the add is used by the cann indvar
1477       // If all four cases above are true, then we can remove both the add and
1478       // the cann indvar.
1479       // FIXME: this needs to eliminate an induction variable even if it's being
1480       // compared against some value to decide loop termination.
1481       if (PN->hasOneUse()) {
1482         Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1483         if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1484           if (BO->hasOneUse() && PN == *(BO->use_begin())) {
1485             DeadInsts.insert(BO);
1486             // Break the cycle, then delete the PHI.
1487             PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1488             SE->deleteInstructionFromRecords(PN);
1489             PN->eraseFromParent();
1490           }
1491         }
1492       }
1493     }
1494     DeleteTriviallyDeadInstructions(DeadInsts);
1495   }
1496
1497   CastedPointers.clear();
1498   IVUsesByStride.clear();
1499   StrideOrder.clear();
1500   return false;
1501 }