Expand GEPs in ScalarEvolution expressions. SCEV expressions can now
[oota-llvm.git] / lib / Transforms / Scalar / LoopStrengthReduce.cpp
1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "loop-reduce"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Type.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/LoopPass.h"
25 #include "llvm/Analysis/ScalarEvolutionExpander.h"
26 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include <algorithm>
39 using namespace llvm;
40
41 STATISTIC(NumReduced ,    "Number of GEPs strength reduced");
42 STATISTIC(NumInserted,    "Number of PHIs inserted");
43 STATISTIC(NumVariable,    "Number of PHIs with variable strides");
44 STATISTIC(NumEliminated,  "Number of strides eliminated");
45 STATISTIC(NumShadow,      "Number of Shadow IVs optimized");
46 STATISTIC(NumImmSunk,     "Number of common expr immediates sunk into uses");
47
48 static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
49                                        cl::init(false),
50                                        cl::Hidden);
51
52 namespace {
53
54   struct BasedUser;
55
56   /// IVStrideUse - Keep track of one use of a strided induction variable, where
57   /// the stride is stored externally.  The Offset member keeps track of the 
58   /// offset from the IV, User is the actual user of the operand, and
59   /// 'OperandValToReplace' is the operand of the User that is the use.
60   struct VISIBILITY_HIDDEN IVStrideUse {
61     SCEVHandle Offset;
62     Instruction *User;
63     Value *OperandValToReplace;
64
65     // isUseOfPostIncrementedValue - True if this should use the
66     // post-incremented version of this IV, not the preincremented version.
67     // This can only be set in special cases, such as the terminating setcc
68     // instruction for a loop or uses dominated by the loop.
69     bool isUseOfPostIncrementedValue;
70     
71     IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
72       : Offset(Offs), User(U), OperandValToReplace(O),
73         isUseOfPostIncrementedValue(false) {}
74   };
75   
76   /// IVUsersOfOneStride - This structure keeps track of all instructions that
77   /// have an operand that is based on the trip count multiplied by some stride.
78   /// The stride for all of these users is common and kept external to this
79   /// structure.
80   struct VISIBILITY_HIDDEN IVUsersOfOneStride {
81     /// Users - Keep track of all of the users of this stride as well as the
82     /// initial value and the operand that uses the IV.
83     std::vector<IVStrideUse> Users;
84     
85     void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
86       Users.push_back(IVStrideUse(Offset, User, Operand));
87     }
88   };
89
90   /// IVInfo - This structure keeps track of one IV expression inserted during
91   /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
92   /// well as the PHI node and increment value created for rewrite.
93   struct VISIBILITY_HIDDEN IVExpr {
94     SCEVHandle  Stride;
95     SCEVHandle  Base;
96     PHINode    *PHI;
97
98     IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi)
99       : Stride(stride), Base(base), PHI(phi) {}
100   };
101
102   /// IVsOfOneStride - This structure keeps track of all IV expression inserted
103   /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
104   struct VISIBILITY_HIDDEN IVsOfOneStride {
105     std::vector<IVExpr> IVs;
106
107     void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI) {
108       IVs.push_back(IVExpr(Stride, Base, PHI));
109     }
110   };
111
112   class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
113     LoopInfo *LI;
114     DominatorTree *DT;
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     SmallVector<SCEVHandle, 16> StrideOrder;
132
133     /// DeadInsts - Keep track of instructions we may have made dead, so that
134     /// we can remove them after we are done working.
135     SmallVector<Instruction*, 16> DeadInsts;
136
137     /// TLI - Keep a pointer of a TargetLowering to consult for determining
138     /// transformation profitability.
139     const TargetLowering *TLI;
140
141   public:
142     static char ID; // Pass ID, replacement for typeid
143     explicit LoopStrengthReduce(const TargetLowering *tli = NULL) : 
144       LoopPass(&ID), TLI(tli) {
145     }
146
147     bool runOnLoop(Loop *L, LPPassManager &LPM);
148
149     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
150       // We split critical edges, so we change the CFG.  However, we do update
151       // many analyses if they are around.
152       AU.addPreservedID(LoopSimplifyID);
153       AU.addPreserved<LoopInfo>();
154       AU.addPreserved<DominanceFrontier>();
155       AU.addPreserved<DominatorTree>();
156
157       AU.addRequiredID(LoopSimplifyID);
158       AU.addRequired<LoopInfo>();
159       AU.addRequired<DominatorTree>();
160       AU.addRequired<TargetData>();
161       AU.addRequired<ScalarEvolution>();
162       AU.addPreserved<ScalarEvolution>();
163     }
164
165 private:
166     bool AddUsersIfInteresting(Instruction *I, Loop *L,
167                                SmallPtrSet<Instruction*,16> &Processed);
168     ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
169                                   IVStrideUse* &CondUse,
170                                   const SCEVHandle* &CondStride);
171     void OptimizeIndvars(Loop *L);
172
173     /// OptimizeShadowIV - If IV is used in a int-to-float cast
174     /// inside the loop then try to eliminate the cast opeation.
175     void OptimizeShadowIV(Loop *L);
176
177     /// OptimizeSMax - Rewrite the loop's terminating condition
178     /// if it uses an smax computation.
179     ICmpInst *OptimizeSMax(Loop *L, ICmpInst *Cond,
180                            IVStrideUse* &CondUse);
181
182     bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
183                            const SCEVHandle *&CondStride);
184     bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
185     SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
186                              IVExpr&, const Type*,
187                              const std::vector<BasedUser>& UsersToProcess);
188     bool ValidStride(bool, int64_t,
189                      const std::vector<BasedUser>& UsersToProcess);
190     SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
191                               IVUsersOfOneStride &Uses,
192                               Loop *L,
193                               bool &AllUsesAreAddresses,
194                               bool &AllUsesAreOutsideLoop,
195                               std::vector<BasedUser> &UsersToProcess);
196     bool ShouldUseFullStrengthReductionMode(
197                                 const std::vector<BasedUser> &UsersToProcess,
198                                 const Loop *L,
199                                 bool AllUsesAreAddresses,
200                                 SCEVHandle Stride);
201     void PrepareToStrengthReduceFully(
202                              std::vector<BasedUser> &UsersToProcess,
203                              SCEVHandle Stride,
204                              SCEVHandle CommonExprs,
205                              const Loop *L,
206                              SCEVExpander &PreheaderRewriter);
207     void PrepareToStrengthReduceFromSmallerStride(
208                                          std::vector<BasedUser> &UsersToProcess,
209                                          Value *CommonBaseV,
210                                          const IVExpr &ReuseIV,
211                                          Instruction *PreInsertPt);
212     void PrepareToStrengthReduceWithNewPhi(
213                                   std::vector<BasedUser> &UsersToProcess,
214                                   SCEVHandle Stride,
215                                   SCEVHandle CommonExprs,
216                                   Value *CommonBaseV,
217                                   const Loop *L,
218                                   SCEVExpander &PreheaderRewriter);
219     void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
220                                       IVUsersOfOneStride &Uses,
221                                       Loop *L);
222     void DeleteTriviallyDeadInstructions();
223   };
224 }
225
226 char LoopStrengthReduce::ID = 0;
227 static RegisterPass<LoopStrengthReduce>
228 X("loop-reduce", "Loop Strength Reduction");
229
230 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
231   return new LoopStrengthReduce(TLI);
232 }
233
234 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
235 /// specified set are trivially dead, delete them and see if this makes any of
236 /// their operands subsequently dead.
237 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
238   if (DeadInsts.empty()) return;
239   
240   // Sort the deadinsts list so that we can trivially eliminate duplicates as we
241   // go.  The code below never adds a non-dead instruction to the worklist, but
242   // callers may not be so careful.
243   array_pod_sort(DeadInsts.begin(), DeadInsts.end());
244
245   // Drop duplicate instructions and those with uses.
246   for (unsigned i = 0, e = DeadInsts.size()-1; i < e; ++i) {
247     Instruction *I = DeadInsts[i];
248     if (!I->use_empty()) DeadInsts[i] = 0;
249     while (i != e && DeadInsts[i+1] == I)
250       DeadInsts[++i] = 0;
251   }
252   
253   while (!DeadInsts.empty()) {
254     Instruction *I = DeadInsts.back();
255     DeadInsts.pop_back();
256     
257     if (I == 0 || !isInstructionTriviallyDead(I))
258       continue;
259
260     SE->deleteValueFromRecords(I);
261
262     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
263       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
264         *OI = 0;
265         if (U->use_empty())
266           DeadInsts.push_back(U);
267       }
268     }
269     
270     I->eraseFromParent();
271     Changed = true;
272   }
273 }
274
275 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a 
276 /// subexpression that is an AddRec from a loop other than L.  An outer loop 
277 /// of L is OK, but not an inner loop nor a disjoint loop.
278 static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
279   // This is very common, put it first.
280   if (isa<SCEVConstant>(S))
281     return false;
282   if (SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
283     for (unsigned int i=0; i< AE->getNumOperands(); i++)
284       if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
285         return true;
286     return false;
287   }
288   if (SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
289     if (const Loop *newLoop = AE->getLoop()) {
290       if (newLoop == L)
291         return false;
292       // if newLoop is an outer loop of L, this is OK.
293       if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
294         return false;
295     }
296     return true;
297   }
298   if (SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
299     return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
300            containsAddRecFromDifferentLoop(DE->getRHS(), L);
301 #if 0
302   // SCEVSDivExpr has been backed out temporarily, but will be back; we'll 
303   // need this when it is.
304   if (SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
305     return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
306            containsAddRecFromDifferentLoop(DE->getRHS(), L);
307 #endif
308   if (SCEVTruncateExpr *TE = dyn_cast<SCEVTruncateExpr>(S))
309     return containsAddRecFromDifferentLoop(TE->getOperand(), L);
310   if (SCEVZeroExtendExpr *ZE = dyn_cast<SCEVZeroExtendExpr>(S))
311     return containsAddRecFromDifferentLoop(ZE->getOperand(), L);
312   if (SCEVSignExtendExpr *SE = dyn_cast<SCEVSignExtendExpr>(S))
313     return containsAddRecFromDifferentLoop(SE->getOperand(), L);
314   return false;
315 }
316
317 /// getSCEVStartAndStride - Compute the start and stride of this expression,
318 /// returning false if the expression is not a start/stride pair, or true if it
319 /// is.  The stride must be a loop invariant expression, but the start may be
320 /// a mix of loop invariant and loop variant expressions.  The start cannot,
321 /// however, contain an AddRec from a different loop, unless that loop is an
322 /// outer loop of the current loop.
323 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
324                                   SCEVHandle &Start, SCEVHandle &Stride,
325                                   ScalarEvolution *SE, DominatorTree *DT) {
326   SCEVHandle TheAddRec = Start;   // Initialize to zero.
327
328   // If the outer level is an AddExpr, the operands are all start values except
329   // for a nested AddRecExpr.
330   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
331     for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
332       if (SCEVAddRecExpr *AddRec =
333              dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
334         if (AddRec->getLoop() == L)
335           TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
336         else
337           return false;  // Nested IV of some sort?
338       } else {
339         Start = SE->getAddExpr(Start, AE->getOperand(i));
340       }
341         
342   } else if (isa<SCEVAddRecExpr>(SH)) {
343     TheAddRec = SH;
344   } else {
345     return false;  // not analyzable.
346   }
347   
348   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
349   if (!AddRec || AddRec->getLoop() != L) return false;
350   
351   // FIXME: Generalize to non-affine IV's.
352   if (!AddRec->isAffine()) return false;
353
354   // If Start contains an SCEVAddRecExpr from a different loop, other than an
355   // outer loop of the current loop, reject it.  SCEV has no concept of 
356   // operating on more than one loop at a time so don't confuse it with such
357   // expressions.
358   if (containsAddRecFromDifferentLoop(AddRec->getOperand(0), L))
359     return false;
360
361   Start = SE->getAddExpr(Start, AddRec->getOperand(0));
362   
363   if (!isa<SCEVConstant>(AddRec->getOperand(1))) {
364     // If stride is an instruction, make sure it dominates the loop preheader.
365     // Otherwise we could end up with a use before def situation.
366     BasicBlock *Preheader = L->getLoopPreheader();
367     if (!AddRec->getOperand(1)->dominates(Preheader, DT))
368       return false;
369
370     DOUT << "[" << L->getHeader()->getName()
371          << "] Variable stride: " << *AddRec << "\n";
372   }
373
374   Stride = AddRec->getOperand(1);
375   return true;
376 }
377
378 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
379 /// and now we need to decide whether the user should use the preinc or post-inc
380 /// value.  If this user should use the post-inc version of the IV, return true.
381 ///
382 /// Choosing wrong here can break dominance properties (if we choose to use the
383 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
384 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
385 /// should use the post-inc value).
386 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
387                                        Loop *L, DominatorTree *DT, Pass *P,
388                                       SmallVectorImpl<Instruction*> &DeadInsts){
389   // If the user is in the loop, use the preinc value.
390   if (L->contains(User->getParent())) return false;
391   
392   BasicBlock *LatchBlock = L->getLoopLatch();
393   
394   // Ok, the user is outside of the loop.  If it is dominated by the latch
395   // block, use the post-inc value.
396   if (DT->dominates(LatchBlock, User->getParent()))
397     return true;
398
399   // There is one case we have to be careful of: PHI nodes.  These little guys
400   // can live in blocks that do not dominate the latch block, but (since their
401   // uses occur in the predecessor block, not the block the PHI lives in) should
402   // still use the post-inc value.  Check for this case now.
403   PHINode *PN = dyn_cast<PHINode>(User);
404   if (!PN) return false;  // not a phi, not dominated by latch block.
405   
406   // Look at all of the uses of IV by the PHI node.  If any use corresponds to
407   // a block that is not dominated by the latch block, give up and use the
408   // preincremented value.
409   unsigned NumUses = 0;
410   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
411     if (PN->getIncomingValue(i) == IV) {
412       ++NumUses;
413       if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
414         return false;
415     }
416
417   // Okay, all uses of IV by PN are in predecessor blocks that really are
418   // dominated by the latch block.  Split the critical edges and use the
419   // post-incremented value.
420   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
421     if (PN->getIncomingValue(i) == IV) {
422       SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P, false);
423       // Splitting the critical edge can reduce the number of entries in this
424       // PHI.
425       e = PN->getNumIncomingValues();
426       if (--NumUses == 0) break;
427     }
428
429   // PHI node might have become a constant value after SplitCriticalEdge.
430   DeadInsts.push_back(User);
431   
432   return true;
433 }
434
435 /// isAddressUse - Returns true if the specified instruction is using the
436 /// specified value as an address.
437 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
438   bool isAddress = isa<LoadInst>(Inst);
439   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
440     if (SI->getOperand(1) == OperandVal)
441       isAddress = true;
442   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
443     // Addressing modes can also be folded into prefetches and a variety
444     // of intrinsics.
445     switch (II->getIntrinsicID()) {
446       default: break;
447       case Intrinsic::prefetch:
448       case Intrinsic::x86_sse2_loadu_dq:
449       case Intrinsic::x86_sse2_loadu_pd:
450       case Intrinsic::x86_sse_loadu_ps:
451       case Intrinsic::x86_sse_storeu_ps:
452       case Intrinsic::x86_sse2_storeu_pd:
453       case Intrinsic::x86_sse2_storeu_dq:
454       case Intrinsic::x86_sse2_storel_dq:
455         if (II->getOperand(1) == OperandVal)
456           isAddress = true;
457         break;
458     }
459   }
460   return isAddress;
461 }
462
463 /// getAccessType - Return the type of the memory being accessed.
464 static const Type *getAccessType(const Instruction *Inst) {
465   const Type *UseTy = Inst->getType();
466   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
467     UseTy = SI->getOperand(0)->getType();
468   else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
469     // Addressing modes can also be folded into prefetches and a variety
470     // of intrinsics.
471     switch (II->getIntrinsicID()) {
472     default: break;
473     case Intrinsic::x86_sse_storeu_ps:
474     case Intrinsic::x86_sse2_storeu_pd:
475     case Intrinsic::x86_sse2_storeu_dq:
476     case Intrinsic::x86_sse2_storel_dq:
477       UseTy = II->getOperand(1)->getType();
478       break;
479     }
480   }
481   return UseTy;
482 }
483
484 /// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
485 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
486 /// return true.  Otherwise, return false.
487 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
488                                       SmallPtrSet<Instruction*,16> &Processed) {
489   if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
490     return false;   // Void and FP expressions cannot be reduced.
491
492   // LSR is not APInt clean, do not touch integers bigger than 64-bits.
493   if (I->getType()->isInteger() && 
494       I->getType()->getPrimitiveSizeInBits() > 64)
495     return false;
496   
497   if (!Processed.insert(I))
498     return true;    // Instruction already handled.
499   
500   // Get the symbolic expression for this instruction.
501   SCEVHandle ISE = SE->getSCEV(I);
502   if (isa<SCEVCouldNotCompute>(ISE)) return false;
503   
504   // Get the start and stride for this expression.
505   SCEVHandle Start = SE->getIntegerSCEV(0, ISE->getType());
506   SCEVHandle Stride = Start;
507   if (!getSCEVStartAndStride(ISE, L, Start, Stride, SE, DT))
508     return false;  // Non-reducible symbolic expression, bail out.
509
510   std::vector<Instruction *> IUsers;
511   // Collect all I uses now because IVUseShouldUsePostIncValue may 
512   // invalidate use_iterator.
513   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
514     IUsers.push_back(cast<Instruction>(*UI));
515
516   for (unsigned iused_index = 0, iused_size = IUsers.size(); 
517        iused_index != iused_size; ++iused_index) {
518
519     Instruction *User = IUsers[iused_index];
520
521     // Do not infinitely recurse on PHI nodes.
522     if (isa<PHINode>(User) && Processed.count(User))
523       continue;
524
525     // Descend recursively, but not into PHI nodes outside the current loop.
526     // It's important to see the entire expression outside the loop to get
527     // choices that depend on addressing mode use right, although we won't
528     // consider references ouside the loop in all cases.
529     // If User is already in Processed, we don't want to recurse into it again,
530     // but do want to record a second reference in the same instruction.
531     bool AddUserToIVUsers = false;
532     if (LI->getLoopFor(User->getParent()) != L) {
533       if (isa<PHINode>(User) || Processed.count(User) ||
534           !AddUsersIfInteresting(User, L, Processed)) {
535         DOUT << "FOUND USER in other loop: " << *User
536              << "   OF SCEV: " << *ISE << "\n";
537         AddUserToIVUsers = true;
538       }
539     } else if (Processed.count(User) || 
540                !AddUsersIfInteresting(User, L, Processed)) {
541       DOUT << "FOUND USER: " << *User
542            << "   OF SCEV: " << *ISE << "\n";
543       AddUserToIVUsers = true;
544     }
545
546     if (AddUserToIVUsers) {
547       IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
548       if (StrideUses.Users.empty())     // First occurrence of this stride?
549         StrideOrder.push_back(Stride);
550       
551       // Okay, we found a user that we cannot reduce.  Analyze the instruction
552       // and decide what to do with it.  If we are a use inside of the loop, use
553       // the value before incrementation, otherwise use it after incrementation.
554       if (IVUseShouldUsePostIncValue(User, I, L, DT, this, DeadInsts)) {
555         // The value used will be incremented by the stride more than we are
556         // expecting, so subtract this off.
557         SCEVHandle NewStart = SE->getMinusSCEV(Start, Stride);
558         StrideUses.addUser(NewStart, User, I);
559         StrideUses.Users.back().isUseOfPostIncrementedValue = true;
560         DOUT << "   USING POSTINC SCEV, START=" << *NewStart<< "\n";
561       } else {        
562         StrideUses.addUser(Start, User, I);
563       }
564     }
565   }
566   return true;
567 }
568
569 namespace {
570   /// BasedUser - For a particular base value, keep information about how we've
571   /// partitioned the expression so far.
572   struct BasedUser {
573     /// SE - The current ScalarEvolution object.
574     ScalarEvolution *SE;
575
576     /// Base - The Base value for the PHI node that needs to be inserted for
577     /// this use.  As the use is processed, information gets moved from this
578     /// field to the Imm field (below).  BasedUser values are sorted by this
579     /// field.
580     SCEVHandle Base;
581     
582     /// Inst - The instruction using the induction variable.
583     Instruction *Inst;
584
585     /// OperandValToReplace - The operand value of Inst to replace with the
586     /// EmittedBase.
587     Value *OperandValToReplace;
588
589     /// Imm - The immediate value that should be added to the base immediately
590     /// before Inst, because it will be folded into the imm field of the
591     /// instruction.  This is also sometimes used for loop-variant values that
592     /// must be added inside the loop.
593     SCEVHandle Imm;
594
595     /// Phi - The induction variable that performs the striding that
596     /// should be used for this user.
597     PHINode *Phi;
598
599     // isUseOfPostIncrementedValue - True if this should use the
600     // post-incremented version of this IV, not the preincremented version.
601     // This can only be set in special cases, such as the terminating setcc
602     // instruction for a loop and uses outside the loop that are dominated by
603     // the loop.
604     bool isUseOfPostIncrementedValue;
605     
606     BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
607       : SE(se), Base(IVSU.Offset), Inst(IVSU.User), 
608         OperandValToReplace(IVSU.OperandValToReplace), 
609         Imm(SE->getIntegerSCEV(0, Base->getType())), 
610         isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
611
612     // Once we rewrite the code to insert the new IVs we want, update the
613     // operands of Inst to use the new expression 'NewBase', with 'Imm' added
614     // to it.
615     void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
616                                         Instruction *InsertPt,
617                                        SCEVExpander &Rewriter, Loop *L, Pass *P,
618                                       SmallVectorImpl<Instruction*> &DeadInsts);
619     
620     Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase, 
621                                        const Type *Ty,
622                                        SCEVExpander &Rewriter,
623                                        Instruction *IP, Loop *L);
624     void dump() const;
625   };
626 }
627
628 void BasedUser::dump() const {
629   cerr << " Base=" << *Base;
630   cerr << " Imm=" << *Imm;
631   cerr << "   Inst: " << *Inst;
632 }
633
634 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase, 
635                                               const Type *Ty,
636                                               SCEVExpander &Rewriter,
637                                               Instruction *IP, Loop *L) {
638   // Figure out where we *really* want to insert this code.  In particular, if
639   // the user is inside of a loop that is nested inside of L, we really don't
640   // want to insert this expression before the user, we'd rather pull it out as
641   // many loops as possible.
642   LoopInfo &LI = Rewriter.getLoopInfo();
643   Instruction *BaseInsertPt = IP;
644   
645   // Figure out the most-nested loop that IP is in.
646   Loop *InsertLoop = LI.getLoopFor(IP->getParent());
647   
648   // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
649   // the preheader of the outer-most loop where NewBase is not loop invariant.
650   if (L->contains(IP->getParent()))
651     while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
652       BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
653       InsertLoop = InsertLoop->getParentLoop();
654     }
655   
656   Value *Base = Rewriter.expandCodeFor(NewBase, Ty, BaseInsertPt);
657
658   // If there is no immediate value, skip the next part.
659   if (Imm->isZero())
660     return Base;
661
662   // If we are inserting the base and imm values in the same block, make sure to
663   // adjust the IP position if insertion reused a result.
664   if (IP == BaseInsertPt)
665     IP = Rewriter.getInsertionPoint();
666   
667   // Always emit the immediate (if non-zero) into the same block as the user.
668   SCEVHandle NewValSCEV = SE->getAddExpr(SE->getUnknown(Base), Imm);
669   return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
670 }
671
672
673 // Once we rewrite the code to insert the new IVs we want, update the
674 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
675 // to it. NewBasePt is the last instruction which contributes to the
676 // value of NewBase in the case that it's a diffferent instruction from
677 // the PHI that NewBase is computed from, or null otherwise.
678 //
679 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
680                                                Instruction *NewBasePt,
681                                       SCEVExpander &Rewriter, Loop *L, Pass *P,
682                                       SmallVectorImpl<Instruction*> &DeadInsts){
683   if (!isa<PHINode>(Inst)) {
684     // By default, insert code at the user instruction.
685     BasicBlock::iterator InsertPt = Inst;
686     
687     // However, if the Operand is itself an instruction, the (potentially
688     // complex) inserted code may be shared by many users.  Because of this, we
689     // want to emit code for the computation of the operand right before its old
690     // computation.  This is usually safe, because we obviously used to use the
691     // computation when it was computed in its current block.  However, in some
692     // cases (e.g. use of a post-incremented induction variable) the NewBase
693     // value will be pinned to live somewhere after the original computation.
694     // In this case, we have to back off.
695     //
696     // If this is a use outside the loop (which means after, since it is based
697     // on a loop indvar) we use the post-incremented value, so that we don't
698     // artificially make the preinc value live out the bottom of the loop. 
699     if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
700       if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
701         InsertPt = NewBasePt;
702         ++InsertPt;
703       } else if (Instruction *OpInst
704                  = dyn_cast<Instruction>(OperandValToReplace)) {
705         InsertPt = OpInst;
706         while (isa<PHINode>(InsertPt)) ++InsertPt;
707       }
708     }
709     Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
710                                                 OperandValToReplace->getType(),
711                                                 Rewriter, InsertPt, L);
712     // Replace the use of the operand Value with the new Phi we just created.
713     Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
714
715     DOUT << "      Replacing with ";
716     DEBUG(WriteAsOperand(*DOUT, NewVal, /*PrintType=*/false));
717     DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
718     return;
719   }
720
721   // PHI nodes are more complex.  We have to insert one copy of the NewBase+Imm
722   // expression into each operand block that uses it.  Note that PHI nodes can
723   // have multiple entries for the same predecessor.  We use a map to make sure
724   // that a PHI node only has a single Value* for each predecessor (which also
725   // prevents us from inserting duplicate code in some blocks).
726   DenseMap<BasicBlock*, Value*> InsertedCode;
727   PHINode *PN = cast<PHINode>(Inst);
728   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
729     if (PN->getIncomingValue(i) == OperandValToReplace) {
730       // If the original expression is outside the loop, put the replacement
731       // code in the same place as the original expression,
732       // which need not be an immediate predecessor of this PHI.  This way we 
733       // need only one copy of it even if it is referenced multiple times in
734       // the PHI.  We don't do this when the original expression is inside the
735       // loop because multiple copies sometimes do useful sinking of code in
736       // that case(?).
737       Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
738       if (L->contains(OldLoc->getParent())) {
739         // If this is a critical edge, split the edge so that we do not insert
740         // the code on all predecessor/successor paths.  We do this unless this
741         // is the canonical backedge for this loop, as this can make some
742         // inserted code be in an illegal position.
743         BasicBlock *PHIPred = PN->getIncomingBlock(i);
744         if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
745             (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
746
747           // First step, split the critical edge.
748           SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
749
750           // Next step: move the basic block.  In particular, if the PHI node
751           // is outside of the loop, and PredTI is in the loop, we want to
752           // move the block to be immediately before the PHI block, not
753           // immediately after PredTI.
754           if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
755             BasicBlock *NewBB = PN->getIncomingBlock(i);
756             NewBB->moveBefore(PN->getParent());
757           }
758
759           // Splitting the edge can reduce the number of PHI entries we have.
760           e = PN->getNumIncomingValues();
761         }
762       }
763       Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
764       if (!Code) {
765         // Insert the code into the end of the predecessor block.
766         Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
767                                 PN->getIncomingBlock(i)->getTerminator() :
768                                 OldLoc->getParent()->getTerminator();
769         Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
770                                            Rewriter, InsertPt, L);
771
772         DOUT << "      Changing PHI use to ";
773         DEBUG(WriteAsOperand(*DOUT, Code, /*PrintType=*/false));
774         DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
775       }
776
777       // Replace the use of the operand Value with the new Phi we just created.
778       PN->setIncomingValue(i, Code);
779       Rewriter.clear();
780     }
781   }
782
783   // PHI node might have become a constant value after SplitCriticalEdge.
784   DeadInsts.push_back(Inst);
785 }
786
787
788 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
789 /// mode, and does not need to be put in a register first.
790 static bool fitsInAddressMode(const SCEVHandle &V, const Type *UseTy,
791                              const TargetLowering *TLI, bool HasBaseReg) {
792   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
793     int64_t VC = SC->getValue()->getSExtValue();
794     if (TLI) {
795       TargetLowering::AddrMode AM;
796       AM.BaseOffs = VC;
797       AM.HasBaseReg = HasBaseReg;
798       return TLI->isLegalAddressingMode(AM, UseTy);
799     } else {
800       // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
801       return (VC > -(1 << 16) && VC < (1 << 16)-1);
802     }
803   }
804
805   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
806     if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
807       TargetLowering::AddrMode AM;
808       AM.BaseGV = GV;
809       AM.HasBaseReg = HasBaseReg;
810       return TLI->isLegalAddressingMode(AM, UseTy);
811     }
812
813   return false;
814 }
815
816 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
817 /// loop varying to the Imm operand.
818 static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
819                                             Loop *L, ScalarEvolution *SE) {
820   if (Val->isLoopInvariant(L)) return;  // Nothing to do.
821   
822   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
823     std::vector<SCEVHandle> NewOps;
824     NewOps.reserve(SAE->getNumOperands());
825     
826     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
827       if (!SAE->getOperand(i)->isLoopInvariant(L)) {
828         // If this is a loop-variant expression, it must stay in the immediate
829         // field of the expression.
830         Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
831       } else {
832         NewOps.push_back(SAE->getOperand(i));
833       }
834
835     if (NewOps.empty())
836       Val = SE->getIntegerSCEV(0, Val->getType());
837     else
838       Val = SE->getAddExpr(NewOps);
839   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
840     // Try to pull immediates out of the start value of nested addrec's.
841     SCEVHandle Start = SARE->getStart();
842     MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
843     
844     std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
845     Ops[0] = Start;
846     Val = SE->getAddRecExpr(Ops, SARE->getLoop());
847   } else {
848     // Otherwise, all of Val is variant, move the whole thing over.
849     Imm = SE->getAddExpr(Imm, Val);
850     Val = SE->getIntegerSCEV(0, Val->getType());
851   }
852 }
853
854
855 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
856 /// that can fit into the immediate field of instructions in the target.
857 /// Accumulate these immediate values into the Imm value.
858 static void MoveImmediateValues(const TargetLowering *TLI,
859                                 const Type *UseTy,
860                                 SCEVHandle &Val, SCEVHandle &Imm,
861                                 bool isAddress, Loop *L,
862                                 ScalarEvolution *SE) {
863   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
864     std::vector<SCEVHandle> NewOps;
865     NewOps.reserve(SAE->getNumOperands());
866     
867     for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
868       SCEVHandle NewOp = SAE->getOperand(i);
869       MoveImmediateValues(TLI, UseTy, NewOp, Imm, isAddress, L, SE);
870       
871       if (!NewOp->isLoopInvariant(L)) {
872         // If this is a loop-variant expression, it must stay in the immediate
873         // field of the expression.
874         Imm = SE->getAddExpr(Imm, NewOp);
875       } else {
876         NewOps.push_back(NewOp);
877       }
878     }
879
880     if (NewOps.empty())
881       Val = SE->getIntegerSCEV(0, Val->getType());
882     else
883       Val = SE->getAddExpr(NewOps);
884     return;
885   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
886     // Try to pull immediates out of the start value of nested addrec's.
887     SCEVHandle Start = SARE->getStart();
888     MoveImmediateValues(TLI, UseTy, Start, Imm, isAddress, L, SE);
889     
890     if (Start != SARE->getStart()) {
891       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
892       Ops[0] = Start;
893       Val = SE->getAddRecExpr(Ops, SARE->getLoop());
894     }
895     return;
896   } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
897     // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
898     if (isAddress && fitsInAddressMode(SME->getOperand(0), UseTy, TLI, false) &&
899         SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
900
901       SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
902       SCEVHandle NewOp = SME->getOperand(1);
903       MoveImmediateValues(TLI, UseTy, NewOp, SubImm, isAddress, L, SE);
904       
905       // If we extracted something out of the subexpressions, see if we can 
906       // simplify this!
907       if (NewOp != SME->getOperand(1)) {
908         // Scale SubImm up by "8".  If the result is a target constant, we are
909         // good.
910         SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
911         if (fitsInAddressMode(SubImm, UseTy, TLI, false)) {
912           // Accumulate the immediate.
913           Imm = SE->getAddExpr(Imm, SubImm);
914           
915           // Update what is left of 'Val'.
916           Val = SE->getMulExpr(SME->getOperand(0), NewOp);
917           return;
918         }
919       }
920     }
921   }
922
923   // Loop-variant expressions must stay in the immediate field of the
924   // expression.
925   if ((isAddress && fitsInAddressMode(Val, UseTy, TLI, false)) ||
926       !Val->isLoopInvariant(L)) {
927     Imm = SE->getAddExpr(Imm, Val);
928     Val = SE->getIntegerSCEV(0, Val->getType());
929     return;
930   }
931
932   // Otherwise, no immediates to move.
933 }
934
935 static void MoveImmediateValues(const TargetLowering *TLI,
936                                 Instruction *User,
937                                 SCEVHandle &Val, SCEVHandle &Imm,
938                                 bool isAddress, Loop *L,
939                                 ScalarEvolution *SE) {
940   const Type *UseTy = getAccessType(User);
941   MoveImmediateValues(TLI, UseTy, Val, Imm, isAddress, L, SE);
942 }
943
944 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
945 /// added together.  This is used to reassociate common addition subexprs
946 /// together for maximal sharing when rewriting bases.
947 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
948                              SCEVHandle Expr,
949                              ScalarEvolution *SE) {
950   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
951     for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
952       SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
953   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
954     SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
955     if (SARE->getOperand(0) == Zero) {
956       SubExprs.push_back(Expr);
957     } else {
958       // Compute the addrec with zero as its base.
959       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
960       Ops[0] = Zero;   // Start with zero base.
961       SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
962       
963
964       SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
965     }
966   } else if (!Expr->isZero()) {
967     // Do not add zero.
968     SubExprs.push_back(Expr);
969   }
970 }
971
972 // This is logically local to the following function, but C++ says we have 
973 // to make it file scope.
974 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
975
976 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
977 /// the Uses, removing any common subexpressions, except that if all such
978 /// subexpressions can be folded into an addressing mode for all uses inside
979 /// the loop (this case is referred to as "free" in comments herein) we do
980 /// not remove anything.  This looks for things like (a+b+c) and
981 /// (a+c+d) and computes the common (a+c) subexpression.  The common expression
982 /// is *removed* from the Bases and returned.
983 static SCEVHandle 
984 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
985                                     ScalarEvolution *SE, Loop *L,
986                                     const TargetLowering *TLI) {
987   unsigned NumUses = Uses.size();
988
989   // Only one use?  This is a very common case, so we handle it specially and
990   // cheaply.
991   SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
992   SCEVHandle Result = Zero;
993   SCEVHandle FreeResult = Zero;
994   if (NumUses == 1) {
995     // If the use is inside the loop, use its base, regardless of what it is:
996     // it is clearly shared across all the IV's.  If the use is outside the loop
997     // (which means after it) we don't want to factor anything *into* the loop,
998     // so just use 0 as the base.
999     if (L->contains(Uses[0].Inst->getParent()))
1000       std::swap(Result, Uses[0].Base);
1001     return Result;
1002   }
1003
1004   // To find common subexpressions, count how many of Uses use each expression.
1005   // If any subexpressions are used Uses.size() times, they are common.
1006   // Also track whether all uses of each expression can be moved into an
1007   // an addressing mode "for free"; such expressions are left within the loop.
1008   // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
1009   std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
1010   
1011   // UniqueSubExprs - Keep track of all of the subexpressions we see in the
1012   // order we see them.
1013   std::vector<SCEVHandle> UniqueSubExprs;
1014
1015   std::vector<SCEVHandle> SubExprs;
1016   unsigned NumUsesInsideLoop = 0;
1017   for (unsigned i = 0; i != NumUses; ++i) {
1018     // If the user is outside the loop, just ignore it for base computation.
1019     // Since the user is outside the loop, it must be *after* the loop (if it
1020     // were before, it could not be based on the loop IV).  We don't want users
1021     // after the loop to affect base computation of values *inside* the loop,
1022     // because we can always add their offsets to the result IV after the loop
1023     // is done, ensuring we get good code inside the loop.
1024     if (!L->contains(Uses[i].Inst->getParent()))
1025       continue;
1026     NumUsesInsideLoop++;
1027     
1028     // If the base is zero (which is common), return zero now, there are no
1029     // CSEs we can find.
1030     if (Uses[i].Base == Zero) return Zero;
1031
1032     // If this use is as an address we may be able to put CSEs in the addressing
1033     // mode rather than hoisting them.
1034     bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
1035     // We may need the UseTy below, but only when isAddrUse, so compute it
1036     // only in that case.
1037     const Type *UseTy = 0;
1038     if (isAddrUse)
1039       UseTy = getAccessType(Uses[i].Inst);
1040
1041     // Split the expression into subexprs.
1042     SeparateSubExprs(SubExprs, Uses[i].Base, SE);
1043     // Add one to SubExpressionUseData.Count for each subexpr present, and
1044     // if the subexpr is not a valid immediate within an addressing mode use,
1045     // set SubExpressionUseData.notAllUsesAreFree.  We definitely want to
1046     // hoist these out of the loop (if they are common to all uses).
1047     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1048       if (++SubExpressionUseData[SubExprs[j]].Count == 1)
1049         UniqueSubExprs.push_back(SubExprs[j]);
1050       if (!isAddrUse || !fitsInAddressMode(SubExprs[j], UseTy, TLI, false))
1051         SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
1052     }
1053     SubExprs.clear();
1054   }
1055
1056   // Now that we know how many times each is used, build Result.  Iterate over
1057   // UniqueSubexprs so that we have a stable ordering.
1058   for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
1059     std::map<SCEVHandle, SubExprUseData>::iterator I = 
1060        SubExpressionUseData.find(UniqueSubExprs[i]);
1061     assert(I != SubExpressionUseData.end() && "Entry not found?");
1062     if (I->second.Count == NumUsesInsideLoop) { // Found CSE! 
1063       if (I->second.notAllUsesAreFree)
1064         Result = SE->getAddExpr(Result, I->first);
1065       else 
1066         FreeResult = SE->getAddExpr(FreeResult, I->first);
1067     } else
1068       // Remove non-cse's from SubExpressionUseData.
1069       SubExpressionUseData.erase(I);
1070   }
1071
1072   if (FreeResult != Zero) {
1073     // We have some subexpressions that can be subsumed into addressing
1074     // modes in every use inside the loop.  However, it's possible that
1075     // there are so many of them that the combined FreeResult cannot
1076     // be subsumed, or that the target cannot handle both a FreeResult
1077     // and a Result in the same instruction (for example because it would
1078     // require too many registers).  Check this.
1079     for (unsigned i=0; i<NumUses; ++i) {
1080       if (!L->contains(Uses[i].Inst->getParent()))
1081         continue;
1082       // We know this is an addressing mode use; if there are any uses that
1083       // are not, FreeResult would be Zero.
1084       const Type *UseTy = getAccessType(Uses[i].Inst);
1085       if (!fitsInAddressMode(FreeResult, UseTy, TLI, Result!=Zero)) {
1086         // FIXME:  could split up FreeResult into pieces here, some hoisted
1087         // and some not.  There is no obvious advantage to this.
1088         Result = SE->getAddExpr(Result, FreeResult);
1089         FreeResult = Zero;
1090         break;
1091       }
1092     }
1093   }
1094
1095   // If we found no CSE's, return now.
1096   if (Result == Zero) return Result;
1097   
1098   // If we still have a FreeResult, remove its subexpressions from
1099   // SubExpressionUseData.  This means they will remain in the use Bases.
1100   if (FreeResult != Zero) {
1101     SeparateSubExprs(SubExprs, FreeResult, SE);
1102     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1103       std::map<SCEVHandle, SubExprUseData>::iterator I = 
1104          SubExpressionUseData.find(SubExprs[j]);
1105       SubExpressionUseData.erase(I);
1106     }
1107     SubExprs.clear();
1108   }
1109
1110   // Otherwise, remove all of the CSE's we found from each of the base values.
1111   for (unsigned i = 0; i != NumUses; ++i) {
1112     // Uses outside the loop don't necessarily include the common base, but
1113     // the final IV value coming into those uses does.  Instead of trying to
1114     // remove the pieces of the common base, which might not be there,
1115     // subtract off the base to compensate for this.
1116     if (!L->contains(Uses[i].Inst->getParent())) {
1117       Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
1118       continue;
1119     }
1120
1121     // Split the expression into subexprs.
1122     SeparateSubExprs(SubExprs, Uses[i].Base, SE);
1123
1124     // Remove any common subexpressions.
1125     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
1126       if (SubExpressionUseData.count(SubExprs[j])) {
1127         SubExprs.erase(SubExprs.begin()+j);
1128         --j; --e;
1129       }
1130     
1131     // Finally, add the non-shared expressions together.
1132     if (SubExprs.empty())
1133       Uses[i].Base = Zero;
1134     else
1135       Uses[i].Base = SE->getAddExpr(SubExprs);
1136     SubExprs.clear();
1137   }
1138  
1139   return Result;
1140 }
1141
1142 /// ValidStride - Check whether the given Scale is valid for all loads and 
1143 /// stores in UsersToProcess.
1144 ///
1145 bool LoopStrengthReduce::ValidStride(bool HasBaseReg,
1146                                int64_t Scale, 
1147                                const std::vector<BasedUser>& UsersToProcess) {
1148   if (!TLI)
1149     return true;
1150
1151   for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
1152     // If this is a load or other access, pass the type of the access in.
1153     const Type *AccessTy = Type::VoidTy;
1154     if (isAddressUse(UsersToProcess[i].Inst,
1155                      UsersToProcess[i].OperandValToReplace))
1156       AccessTy = getAccessType(UsersToProcess[i].Inst);
1157     else if (isa<PHINode>(UsersToProcess[i].Inst))
1158       continue;
1159     
1160     TargetLowering::AddrMode AM;
1161     if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
1162       AM.BaseOffs = SC->getValue()->getSExtValue();
1163     AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
1164     AM.Scale = Scale;
1165
1166     // If load[imm+r*scale] is illegal, bail out.
1167     if (!TLI->isLegalAddressingMode(AM, AccessTy))
1168       return false;
1169   }
1170   return true;
1171 }
1172
1173 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
1174 /// a nop.
1175 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
1176                                                 const Type *Ty2) {
1177   if (Ty1 == Ty2)
1178     return false;
1179   if (Ty1->canLosslesslyBitCastTo(Ty2))
1180     return false;
1181   if (TLI && TLI->isTruncateFree(Ty1, Ty2))
1182     return false;
1183   if (isa<PointerType>(Ty2) && Ty1->canLosslesslyBitCastTo(UIntPtrTy))
1184     return false;
1185   if (isa<PointerType>(Ty1) && Ty2->canLosslesslyBitCastTo(UIntPtrTy))
1186     return false;
1187   return true;
1188 }
1189
1190 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
1191 /// of a previous stride and it is a legal value for the target addressing
1192 /// mode scale component and optional base reg. This allows the users of
1193 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
1194 /// reuse is possible.  Factors can be negative on same targets, e.g. ARM.
1195 ///
1196 /// If all uses are outside the loop, we don't require that all multiplies
1197 /// be folded into the addressing mode, nor even that the factor be constant; 
1198 /// a multiply (executed once) outside the loop is better than another IV 
1199 /// within.  Well, usually.
1200 SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
1201                                 bool AllUsesAreAddresses,
1202                                 bool AllUsesAreOutsideLoop,
1203                                 const SCEVHandle &Stride, 
1204                                 IVExpr &IV, const Type *Ty,
1205                                 const std::vector<BasedUser>& UsersToProcess) {
1206   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
1207     int64_t SInt = SC->getValue()->getSExtValue();
1208     for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1209          ++NewStride) {
1210       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
1211                 IVsByStride.find(StrideOrder[NewStride]);
1212       if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1213         continue;
1214       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1215       if (SI->first != Stride &&
1216           (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
1217         continue;
1218       int64_t Scale = SInt / SSInt;
1219       // Check that this stride is valid for all the types used for loads and
1220       // stores; if it can be used for some and not others, we might as well use
1221       // the original stride everywhere, since we have to create the IV for it
1222       // anyway. If the scale is 1, then we don't need to worry about folding
1223       // multiplications.
1224       if (Scale == 1 ||
1225           (AllUsesAreAddresses &&
1226            ValidStride(HasBaseReg, Scale, UsersToProcess)))
1227         for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1228                IE = SI->second.IVs.end(); II != IE; ++II)
1229           // FIXME: Only handle base == 0 for now.
1230           // Only reuse previous IV if it would not require a type conversion.
1231           if (II->Base->isZero() &&
1232               !RequiresTypeConversion(II->Base->getType(), Ty)) {
1233             IV = *II;
1234             return SE->getIntegerSCEV(Scale, Stride->getType());
1235           }
1236     }
1237   } else if (AllUsesAreOutsideLoop) {
1238     // Accept nonconstant strides here; it is really really right to substitute
1239     // an existing IV if we can.
1240     for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1241          ++NewStride) {
1242       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
1243                 IVsByStride.find(StrideOrder[NewStride]);
1244       if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1245         continue;
1246       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1247       if (SI->first != Stride && SSInt != 1)
1248         continue;
1249       for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1250              IE = SI->second.IVs.end(); II != IE; ++II)
1251         // Accept nonzero base here.
1252         // Only reuse previous IV if it would not require a type conversion.
1253         if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1254           IV = *II;
1255           return Stride;
1256         }
1257     }
1258     // Special case, old IV is -1*x and this one is x.  Can treat this one as
1259     // -1*old.
1260     for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1261          ++NewStride) {
1262       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
1263                 IVsByStride.find(StrideOrder[NewStride]);
1264       if (SI == IVsByStride.end()) 
1265         continue;
1266       if (SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1267         if (SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
1268           if (Stride == ME->getOperand(1) &&
1269               SC->getValue()->getSExtValue() == -1LL)
1270             for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1271                    IE = SI->second.IVs.end(); II != IE; ++II)
1272               // Accept nonzero base here.
1273               // Only reuse previous IV if it would not require type conversion.
1274               if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1275                 IV = *II;
1276                 return SE->getIntegerSCEV(-1LL, Stride->getType());
1277               }
1278     }
1279   }
1280   return SE->getIntegerSCEV(0, Stride->getType());
1281 }
1282
1283 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1284 /// returns true if Val's isUseOfPostIncrementedValue is true.
1285 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1286   return Val.isUseOfPostIncrementedValue;
1287 }
1288
1289 /// isNonConstantNegative - Return true if the specified scev is negated, but
1290 /// not a constant.
1291 static bool isNonConstantNegative(const SCEVHandle &Expr) {
1292   SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1293   if (!Mul) return false;
1294   
1295   // If there is a constant factor, it will be first.
1296   SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1297   if (!SC) return false;
1298   
1299   // Return true if the value is negative, this matches things like (-42 * V).
1300   return SC->getValue()->getValue().isNegative();
1301 }
1302
1303 // CollectIVUsers - Transform our list of users and offsets to a bit more
1304 // complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1305 // of the strided accesses, as well as the old information from Uses. We
1306 // progressively move information from the Base field to the Imm field, until
1307 // we eventually have the full access expression to rewrite the use.
1308 SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1309                                               IVUsersOfOneStride &Uses,
1310                                               Loop *L,
1311                                               bool &AllUsesAreAddresses,
1312                                               bool &AllUsesAreOutsideLoop,
1313                                        std::vector<BasedUser> &UsersToProcess) {
1314   UsersToProcess.reserve(Uses.Users.size());
1315   for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
1316     UsersToProcess.push_back(BasedUser(Uses.Users[i], SE));
1317     
1318     // Move any loop variant operands from the offset field to the immediate
1319     // field of the use, so that we don't try to use something before it is
1320     // computed.
1321     MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1322                                     UsersToProcess.back().Imm, L, SE);
1323     assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1324            "Base value is not loop invariant!");
1325   }
1326
1327   // We now have a whole bunch of uses of like-strided induction variables, but
1328   // they might all have different bases.  We want to emit one PHI node for this
1329   // stride which we fold as many common expressions (between the IVs) into as
1330   // possible.  Start by identifying the common expressions in the base values 
1331   // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1332   // "A+B"), emit it to the preheader, then remove the expression from the
1333   // UsersToProcess base values.
1334   SCEVHandle CommonExprs =
1335     RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1336
1337   // Next, figure out what we can represent in the immediate fields of
1338   // instructions.  If we can represent anything there, move it to the imm
1339   // fields of the BasedUsers.  We do this so that it increases the commonality
1340   // of the remaining uses.
1341   unsigned NumPHI = 0;
1342   bool HasAddress = false;
1343   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1344     // If the user is not in the current loop, this means it is using the exit
1345     // value of the IV.  Do not put anything in the base, make sure it's all in
1346     // the immediate field to allow as much factoring as possible.
1347     if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1348       UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1349                                              UsersToProcess[i].Base);
1350       UsersToProcess[i].Base = 
1351         SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1352     } else {
1353       // Not all uses are outside the loop.
1354       AllUsesAreOutsideLoop = false; 
1355
1356       // Addressing modes can be folded into loads and stores.  Be careful that
1357       // the store is through the expression, not of the expression though.
1358       bool isPHI = false;
1359       bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1360                                     UsersToProcess[i].OperandValToReplace);
1361       if (isa<PHINode>(UsersToProcess[i].Inst)) {
1362         isPHI = true;
1363         ++NumPHI;
1364       }
1365
1366       if (isAddress)
1367         HasAddress = true;
1368      
1369       // If this use isn't an address, then not all uses are addresses.
1370       if (!isAddress && !isPHI)
1371         AllUsesAreAddresses = false;
1372       
1373       MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1374                           UsersToProcess[i].Imm, isAddress, L, SE);
1375     }
1376   }
1377
1378   // If one of the use is a PHI node and all other uses are addresses, still
1379   // allow iv reuse. Essentially we are trading one constant multiplication
1380   // for one fewer iv.
1381   if (NumPHI > 1)
1382     AllUsesAreAddresses = false;
1383     
1384   // There are no in-loop address uses.
1385   if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1386     AllUsesAreAddresses = false;
1387
1388   return CommonExprs;
1389 }
1390
1391 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1392 /// is valid and profitable for the given set of users of a stride. In
1393 /// full strength-reduction mode, all addresses at the current stride are
1394 /// strength-reduced all the way down to pointer arithmetic.
1395 ///
1396 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1397                                    const std::vector<BasedUser> &UsersToProcess,
1398                                    const Loop *L,
1399                                    bool AllUsesAreAddresses,
1400                                    SCEVHandle Stride) {
1401   if (!EnableFullLSRMode)
1402     return false;
1403
1404   // The heuristics below aim to avoid increasing register pressure, but
1405   // fully strength-reducing all the addresses increases the number of
1406   // add instructions, so don't do this when optimizing for size.
1407   // TODO: If the loop is large, the savings due to simpler addresses
1408   // may oughtweight the costs of the extra increment instructions.
1409   if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1410     return false;
1411
1412   // TODO: For now, don't do full strength reduction if there could
1413   // potentially be greater-stride multiples of the current stride
1414   // which could reuse the current stride IV.
1415   if (StrideOrder.back() != Stride)
1416     return false;
1417
1418   // Iterate through the uses to find conditions that automatically rule out
1419   // full-lsr mode.
1420   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1421     SCEV *Base = UsersToProcess[i].Base;
1422     SCEV *Imm = UsersToProcess[i].Imm;
1423     // If any users have a loop-variant component, they can't be fully
1424     // strength-reduced.
1425     if (Imm && !Imm->isLoopInvariant(L))
1426       return false;
1427     // If there are to users with the same base and the difference between
1428     // the two Imm values can't be folded into the address, full
1429     // strength reduction would increase register pressure.
1430     do {
1431       SCEV *CurImm = UsersToProcess[i].Imm;
1432       if ((CurImm || Imm) && CurImm != Imm) {
1433         if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1434         if (!Imm)       Imm = SE->getIntegerSCEV(0, Stride->getType());
1435         const Instruction *Inst = UsersToProcess[i].Inst;
1436         const Type *UseTy = getAccessType(Inst);
1437         SCEVHandle Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1438         if (!Diff->isZero() &&
1439             (!AllUsesAreAddresses ||
1440              !fitsInAddressMode(Diff, UseTy, TLI, /*HasBaseReg=*/true)))
1441           return false;
1442       }
1443     } while (++i != e && Base == UsersToProcess[i].Base);
1444   }
1445
1446   // If there's exactly one user in this stride, fully strength-reducing it
1447   // won't increase register pressure. If it's starting from a non-zero base,
1448   // it'll be simpler this way.
1449   if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1450     return true;
1451
1452   // Otherwise, if there are any users in this stride that don't require
1453   // a register for their base, full strength-reduction will increase
1454   // register pressure.
1455   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1456     if (UsersToProcess[i].Base->isZero())
1457       return false;
1458
1459   // Otherwise, go for it.
1460   return true;
1461 }
1462
1463 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1464 /// with the specified start and step values in the specified loop.
1465 ///
1466 /// If NegateStride is true, the stride should be negated by using a
1467 /// subtract instead of an add.
1468 ///
1469 /// Return the created phi node.
1470 ///
1471 static PHINode *InsertAffinePhi(SCEVHandle Start, SCEVHandle Step,
1472                                 const Loop *L,
1473                                 const TargetData *TD,
1474                                 SCEVExpander &Rewriter) {
1475   assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1476   assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1477
1478   BasicBlock *Header = L->getHeader();
1479   BasicBlock *Preheader = L->getLoopPreheader();
1480   BasicBlock *LatchBlock = L->getLoopLatch();
1481   const Type *Ty = Start->getType();
1482   if (isa<PointerType>(Ty)) Ty = TD->getIntPtrType();
1483
1484   PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1485   PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1486                   Preheader);
1487
1488   // If the stride is negative, insert a sub instead of an add for the
1489   // increment.
1490   bool isNegative = isNonConstantNegative(Step);
1491   SCEVHandle IncAmount = Step;
1492   if (isNegative)
1493     IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1494
1495   // Insert an add instruction right before the terminator corresponding
1496   // to the back-edge.
1497   Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1498                                         Preheader->getTerminator());
1499   Instruction *IncV;
1500   if (isNegative) {
1501     IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1502                                      LatchBlock->getTerminator());
1503   } else {
1504     IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1505                                      LatchBlock->getTerminator());
1506   }
1507   if (!isa<ConstantInt>(StepV)) ++NumVariable;
1508
1509   PN->addIncoming(IncV, LatchBlock);
1510
1511   ++NumInserted;
1512   return PN;
1513 }
1514
1515 static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1516   // We want to emit code for users inside the loop first.  To do this, we
1517   // rearrange BasedUser so that the entries at the end have
1518   // isUseOfPostIncrementedValue = false, because we pop off the end of the
1519   // vector (so we handle them first).
1520   std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1521                  PartitionByIsUseOfPostIncrementedValue);
1522
1523   // Sort this by base, so that things with the same base are handled
1524   // together.  By partitioning first and stable-sorting later, we are
1525   // guaranteed that within each base we will pop off users from within the
1526   // loop before users outside of the loop with a particular base.
1527   //
1528   // We would like to use stable_sort here, but we can't.  The problem is that
1529   // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1530   // we don't have anything to do a '<' comparison on.  Because we think the
1531   // number of uses is small, do a horrible bubble sort which just relies on
1532   // ==.
1533   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1534     // Get a base value.
1535     SCEVHandle Base = UsersToProcess[i].Base;
1536
1537     // Compact everything with this base to be consecutive with this one.
1538     for (unsigned j = i+1; j != e; ++j) {
1539       if (UsersToProcess[j].Base == Base) {
1540         std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1541         ++i;
1542       }
1543     }
1544   }
1545 }
1546
1547 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1548 /// UsersToProcess, meaning lowering addresses all the way down to direct
1549 /// pointer arithmetic.
1550 ///
1551 void
1552 LoopStrengthReduce::PrepareToStrengthReduceFully(
1553                                         std::vector<BasedUser> &UsersToProcess,
1554                                         SCEVHandle Stride,
1555                                         SCEVHandle CommonExprs,
1556                                         const Loop *L,
1557                                         SCEVExpander &PreheaderRewriter) {
1558   DOUT << "  Fully reducing all users\n";
1559
1560   // Rewrite the UsersToProcess records, creating a separate PHI for each
1561   // unique Base value.
1562   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1563     // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1564     // pick the first Imm value here to start with, and adjust it for the
1565     // other uses.
1566     SCEVHandle Imm = UsersToProcess[i].Imm;
1567     SCEVHandle Base = UsersToProcess[i].Base;
1568     SCEVHandle Start = SE->getAddExpr(CommonExprs, Base, Imm);
1569     PHINode *Phi = InsertAffinePhi(Start, Stride, L, TD,
1570                                    PreheaderRewriter);
1571     // Loop over all the users with the same base.
1572     do {
1573       UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1574       UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1575       UsersToProcess[i].Phi = Phi;
1576       assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1577              "ShouldUseFullStrengthReductionMode should reject this!");
1578     } while (++i != e && Base == UsersToProcess[i].Base);
1579   }
1580 }
1581
1582 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1583 /// given users to share.
1584 ///
1585 void
1586 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1587                                          std::vector<BasedUser> &UsersToProcess,
1588                                          SCEVHandle Stride,
1589                                          SCEVHandle CommonExprs,
1590                                          Value *CommonBaseV,
1591                                          const Loop *L,
1592                                          SCEVExpander &PreheaderRewriter) {
1593   DOUT << "  Inserting new PHI:\n";
1594
1595   PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1596                                  Stride, L, TD,
1597                                  PreheaderRewriter);
1598
1599   // Remember this in case a later stride is multiple of this.
1600   IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1601
1602   // All the users will share this new IV.
1603   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1604     UsersToProcess[i].Phi = Phi;
1605
1606   DOUT << "    IV=";
1607   DEBUG(WriteAsOperand(*DOUT, Phi, /*PrintType=*/false));
1608   DOUT << "\n";
1609 }
1610
1611 /// PrepareToStrengthReduceWithNewPhi - Prepare for the given users to reuse
1612 /// an induction variable with a stride that is a factor of the current
1613 /// induction variable.
1614 ///
1615 void
1616 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1617                                          std::vector<BasedUser> &UsersToProcess,
1618                                          Value *CommonBaseV,
1619                                          const IVExpr &ReuseIV,
1620                                          Instruction *PreInsertPt) {
1621   DOUT << "  Rewriting in terms of existing IV of STRIDE " << *ReuseIV.Stride
1622        << " and BASE " << *ReuseIV.Base << "\n";
1623
1624   // All the users will share the reused IV.
1625   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1626     UsersToProcess[i].Phi = ReuseIV.PHI;
1627
1628   Constant *C = dyn_cast<Constant>(CommonBaseV);
1629   if (C &&
1630       (!C->isNullValue() &&
1631        !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1632                          TLI, false)))
1633     // We want the common base emitted into the preheader! This is just
1634     // using cast as a copy so BitCast (no-op cast) is appropriate
1635     CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1636                                   "commonbase", PreInsertPt);
1637 }
1638
1639 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1640                                     const Type *AccessTy,
1641                                    std::vector<BasedUser> &UsersToProcess,
1642                                    const TargetLowering *TLI) {
1643   SmallVector<Instruction*, 16> AddrModeInsts;
1644   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1645     if (UsersToProcess[i].isUseOfPostIncrementedValue)
1646       continue;
1647     ExtAddrMode AddrMode =
1648       AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1649                                    AccessTy, UsersToProcess[i].Inst,
1650                                    AddrModeInsts, *TLI);
1651     if (GV && GV != AddrMode.BaseGV)
1652       return false;
1653     if (Offset && !AddrMode.BaseOffs)
1654       // FIXME: How to accurate check it's immediate offset is folded.
1655       return false;
1656     AddrModeInsts.clear();
1657   }
1658   return true;
1659 }
1660
1661 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1662 /// stride of IV.  All of the users may have different starting values, and this
1663 /// may not be the only stride.
1664 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1665                                                       IVUsersOfOneStride &Uses,
1666                                                       Loop *L) {
1667   // If all the users are moved to another stride, then there is nothing to do.
1668   if (Uses.Users.empty())
1669     return;
1670
1671   // Keep track if every use in UsersToProcess is an address. If they all are,
1672   // we may be able to rewrite the entire collection of them in terms of a
1673   // smaller-stride IV.
1674   bool AllUsesAreAddresses = true;
1675
1676   // Keep track if every use of a single stride is outside the loop.  If so,
1677   // we want to be more aggressive about reusing a smaller-stride IV; a
1678   // multiply outside the loop is better than another IV inside.  Well, usually.
1679   bool AllUsesAreOutsideLoop = true;
1680
1681   // Transform our list of users and offsets to a bit more complex table.  In
1682   // this new vector, each 'BasedUser' contains 'Base' the base of the
1683   // strided accessas well as the old information from Uses.  We progressively
1684   // move information from the Base field to the Imm field, until we eventually
1685   // have the full access expression to rewrite the use.
1686   std::vector<BasedUser> UsersToProcess;
1687   SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1688                                           AllUsesAreOutsideLoop,
1689                                           UsersToProcess);
1690
1691   // Sort the UsersToProcess array so that users with common bases are
1692   // next to each other.
1693   SortUsersToProcess(UsersToProcess);
1694
1695   // If we managed to find some expressions in common, we'll need to carry
1696   // their value in a register and add it in for each use. This will take up
1697   // a register operand, which potentially restricts what stride values are
1698   // valid.
1699   bool HaveCommonExprs = !CommonExprs->isZero();
1700
1701   const Type *ReplacedTy = CommonExprs->getType();
1702   if (isa<PointerType>(ReplacedTy)) ReplacedTy = TD->getIntPtrType();
1703
1704   // If all uses are addresses, consider sinking the immediate part of the
1705   // common expression back into uses if they can fit in the immediate fields.
1706   if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1707     SCEVHandle NewCommon = CommonExprs;
1708     SCEVHandle Imm = SE->getIntegerSCEV(0, ReplacedTy);
1709     MoveImmediateValues(TLI, Type::VoidTy, NewCommon, Imm, true, L, SE);
1710     if (!Imm->isZero()) {
1711       bool DoSink = true;
1712
1713       // If the immediate part of the common expression is a GV, check if it's
1714       // possible to fold it into the target addressing mode.
1715       GlobalValue *GV = 0;
1716       if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
1717         GV = dyn_cast<GlobalValue>(SU->getValue());
1718       int64_t Offset = 0;
1719       if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
1720         Offset = SC->getValue()->getSExtValue();
1721       if (GV || Offset)
1722         // Pass VoidTy as the AccessTy to be conservative, because
1723         // there could be multiple access types among all the uses.
1724         DoSink = IsImmFoldedIntoAddrMode(GV, Offset, Type::VoidTy,
1725                                          UsersToProcess, TLI);
1726
1727       if (DoSink) {
1728         DOUT << "  Sinking " << *Imm << " back down into uses\n";
1729         for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1730           UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1731         CommonExprs = NewCommon;
1732         HaveCommonExprs = !CommonExprs->isZero();
1733         ++NumImmSunk;
1734       }
1735     }
1736   }
1737
1738   // Now that we know what we need to do, insert the PHI node itself.
1739   //
1740   DOUT << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1741        << *Stride << ":\n"
1742        << "  Common base: " << *CommonExprs << "\n";
1743
1744   SCEVExpander Rewriter(*SE, *LI, *TD);
1745   SCEVExpander PreheaderRewriter(*SE, *LI, *TD);
1746
1747   BasicBlock  *Preheader = L->getLoopPreheader();
1748   Instruction *PreInsertPt = Preheader->getTerminator();
1749   BasicBlock *LatchBlock = L->getLoopLatch();
1750
1751   Value *CommonBaseV = ConstantInt::get(ReplacedTy, 0);
1752
1753   SCEVHandle RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1754   IVExpr   ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1755                    SE->getIntegerSCEV(0, Type::Int32Ty),
1756                    0);
1757
1758   /// Choose a strength-reduction strategy and prepare for it by creating
1759   /// the necessary PHIs and adjusting the bookkeeping.
1760   if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1761                                          AllUsesAreAddresses, Stride)) {
1762     PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1763                                  PreheaderRewriter);
1764   } else {
1765     // Emit the initial base value into the loop preheader.
1766     CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1767                                                   PreInsertPt);
1768
1769     // If all uses are addresses, check if it is possible to reuse an IV with a
1770     // stride that is a factor of this stride. And that the multiple is a number
1771     // that can be encoded in the scale field of the target addressing mode. And
1772     // that we will have a valid instruction after this substition, including
1773     // the immediate field, if any.
1774     RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1775                                     AllUsesAreOutsideLoop,
1776                                     Stride, ReuseIV, ReplacedTy,
1777                                     UsersToProcess);
1778     if (isa<SCEVConstant>(RewriteFactor) &&
1779         cast<SCEVConstant>(RewriteFactor)->isZero())
1780       PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1781                                         CommonBaseV, L, PreheaderRewriter);
1782     else
1783       PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1784                                                ReuseIV, PreInsertPt);
1785   }
1786
1787   // Process all the users now, replacing their strided uses with
1788   // strength-reduced forms.  This outer loop handles all bases, the inner
1789   // loop handles all users of a particular base.
1790   while (!UsersToProcess.empty()) {
1791     SCEVHandle Base = UsersToProcess.back().Base;
1792     Instruction *Inst = UsersToProcess.back().Inst;
1793
1794     // Emit the code for Base into the preheader.
1795     Value *BaseV = 0;
1796     if (!Base->isZero()) {
1797       BaseV = PreheaderRewriter.expandCodeFor(Base, Base->getType(),
1798                                               PreInsertPt);
1799
1800       DOUT << "  INSERTING code for BASE = " << *Base << ":";
1801       if (BaseV->hasName())
1802         DOUT << " Result value name = %" << BaseV->getNameStr();
1803       DOUT << "\n";
1804
1805       // If BaseV is a non-zero constant, make sure that it gets inserted into
1806       // the preheader, instead of being forward substituted into the uses.  We
1807       // do this by forcing a BitCast (noop cast) to be inserted into the
1808       // preheader in this case.
1809       if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false)) {
1810         // We want this constant emitted into the preheader! This is just
1811         // using cast as a copy so BitCast (no-op cast) is appropriate
1812         BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1813                                 PreInsertPt);       
1814       }
1815     }
1816
1817     // Emit the code to add the immediate offset to the Phi value, just before
1818     // the instructions that we identified as using this stride and base.
1819     do {
1820       // FIXME: Use emitted users to emit other users.
1821       BasedUser &User = UsersToProcess.back();
1822
1823       DOUT << "    Examining use ";
1824       DEBUG(WriteAsOperand(*DOUT, UsersToProcess.back().OperandValToReplace,
1825                            /*PrintType=*/false));
1826       DOUT << " in Inst: " << *Inst;
1827
1828       // If this instruction wants to use the post-incremented value, move it
1829       // after the post-inc and use its value instead of the PHI.
1830       Value *RewriteOp = User.Phi;
1831       if (User.isUseOfPostIncrementedValue) {
1832         RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1833
1834         // If this user is in the loop, make sure it is the last thing in the
1835         // loop to ensure it is dominated by the increment.
1836         if (L->contains(User.Inst->getParent()))
1837           User.Inst->moveBefore(LatchBlock->getTerminator());
1838       }
1839       if (RewriteOp->getType() != ReplacedTy) {
1840         Instruction::CastOps opcode =
1841           CastInst::getCastOpcode(RewriteOp, false, ReplacedTy, false);
1842         assert(opcode != Instruction::SExt &&
1843                opcode != Instruction::ZExt &&
1844                "Unexpected widening cast!");
1845         RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1846       }
1847
1848       SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
1849
1850       // If we had to insert new instructions for RewriteOp, we have to
1851       // consider that they may not have been able to end up immediately
1852       // next to RewriteOp, because non-PHI instructions may never precede
1853       // PHI instructions in a block. In this case, remember where the last
1854       // instruction was inserted so that if we're replacing a different
1855       // PHI node, we can use the later point to expand the final
1856       // RewriteExpr.
1857       Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
1858       if (RewriteOp == User.Phi) NewBasePt = 0;
1859
1860       // Clear the SCEVExpander's expression map so that we are guaranteed
1861       // to have the code emitted where we expect it.
1862       Rewriter.clear();
1863
1864       // If we are reusing the iv, then it must be multiplied by a constant
1865       // factor to take advantage of the addressing mode scale component.
1866       if (!RewriteFactor->isZero()) {
1867         // If we're reusing an IV with a nonzero base (currently this happens
1868         // only when all reuses are outside the loop) subtract that base here.
1869         // The base has been used to initialize the PHI node but we don't want
1870         // it here.
1871         if (!ReuseIV.Base->isZero()) {
1872           SCEVHandle typedBase = ReuseIV.Base;
1873           if (RewriteExpr->getType()->getPrimitiveSizeInBits() !=
1874               ReuseIV.Base->getType()->getPrimitiveSizeInBits()) {
1875             // It's possible the original IV is a larger type than the new IV,
1876             // in which case we have to truncate the Base.  We checked in
1877             // RequiresTypeConversion that this is valid.
1878             assert (RewriteExpr->getType()->getPrimitiveSizeInBits() <
1879                     ReuseIV.Base->getType()->getPrimitiveSizeInBits() &&
1880                     "Unexpected lengthening conversion!");
1881             typedBase = SE->getTruncateExpr(ReuseIV.Base, 
1882                                             RewriteExpr->getType());
1883           }
1884           RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1885         }
1886
1887         // Multiply old variable, with base removed, by new scale factor.
1888         RewriteExpr = SE->getMulExpr(RewriteFactor,
1889                                      RewriteExpr);
1890
1891         // The common base is emitted in the loop preheader. But since we
1892         // are reusing an IV, it has not been used to initialize the PHI node.
1893         // Add it to the expression used to rewrite the uses.
1894         // When this use is outside the loop, we earlier subtracted the
1895         // common base, and are adding it back here.  Use the same expression
1896         // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1897         if (!CommonExprs->isZero()) {
1898           if (L->contains(User.Inst->getParent()))
1899             RewriteExpr = SE->getAddExpr(RewriteExpr,
1900                                        SE->getUnknown(CommonBaseV));
1901           else
1902             RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1903         }
1904       }
1905
1906       // Now that we know what we need to do, insert code before User for the
1907       // immediate and any loop-variant expressions.
1908       if (BaseV)
1909         // Add BaseV to the PHI value if needed.
1910         RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1911
1912       User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1913                                           Rewriter, L, this,
1914                                           DeadInsts);
1915
1916       // Mark old value we replaced as possibly dead, so that it is eliminated
1917       // if we just replaced the last use of that value.
1918       DeadInsts.push_back(cast<Instruction>(User.OperandValToReplace));
1919
1920       UsersToProcess.pop_back();
1921       ++NumReduced;
1922
1923       // If there are any more users to process with the same base, process them
1924       // now.  We sorted by base above, so we just have to check the last elt.
1925     } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1926     // TODO: Next, find out which base index is the most common, pull it out.
1927   }
1928
1929   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1930   // different starting values, into different PHIs.
1931 }
1932
1933 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1934 /// set the IV user and stride information and return true, otherwise return
1935 /// false.
1936 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
1937                                        const SCEVHandle *&CondStride) {
1938   for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1939        ++Stride) {
1940     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
1941     IVUsesByStride.find(StrideOrder[Stride]);
1942     assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1943     
1944     for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1945          E = SI->second.Users.end(); UI != E; ++UI)
1946       if (UI->User == Cond) {
1947         // NOTE: we could handle setcc instructions with multiple uses here, but
1948         // InstCombine does it as well for simple uses, it's not clear that it
1949         // occurs enough in real life to handle.
1950         CondUse = &*UI;
1951         CondStride = &SI->first;
1952         return true;
1953       }
1954   }
1955   return false;
1956 }    
1957
1958 namespace {
1959   // Constant strides come first which in turns are sorted by their absolute
1960   // values. If absolute values are the same, then positive strides comes first.
1961   // e.g.
1962   // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1963   struct StrideCompare {
1964     const TargetData *TD;
1965     explicit StrideCompare(const TargetData *td) : TD(td) {}
1966
1967     bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1968       SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1969       SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1970       if (LHSC && RHSC) {
1971         int64_t  LV = LHSC->getValue()->getSExtValue();
1972         int64_t  RV = RHSC->getValue()->getSExtValue();
1973         uint64_t ALV = (LV < 0) ? -LV : LV;
1974         uint64_t ARV = (RV < 0) ? -RV : RV;
1975         if (ALV == ARV) {
1976           if (LV != RV)
1977             return LV > RV;
1978         } else {
1979           return ALV < ARV;
1980         }
1981
1982         // If it's the same value but different type, sort by bit width so
1983         // that we emit larger induction variables before smaller
1984         // ones, letting the smaller be re-written in terms of larger ones.
1985         return TD->getTypeSizeInBits(RHS->getType()) <
1986                TD->getTypeSizeInBits(LHS->getType());
1987       }
1988       return LHSC && !RHSC;
1989     }
1990   };
1991 }
1992
1993 /// ChangeCompareStride - If a loop termination compare instruction is the
1994 /// only use of its stride, and the compaison is against a constant value,
1995 /// try eliminate the stride by moving the compare instruction to another
1996 /// stride and change its constant operand accordingly. e.g.
1997 ///
1998 /// loop:
1999 /// ...
2000 /// v1 = v1 + 3
2001 /// v2 = v2 + 1
2002 /// if (v2 < 10) goto loop
2003 /// =>
2004 /// loop:
2005 /// ...
2006 /// v1 = v1 + 3
2007 /// if (v1 < 30) goto loop
2008 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
2009                                                 IVStrideUse* &CondUse,
2010                                                 const SCEVHandle* &CondStride) {
2011   if (StrideOrder.size() < 2 ||
2012       IVUsesByStride[*CondStride].Users.size() != 1)
2013     return Cond;
2014   const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
2015   if (!SC) return Cond;
2016
2017   ICmpInst::Predicate Predicate = Cond->getPredicate();
2018   int64_t CmpSSInt = SC->getValue()->getSExtValue();
2019   unsigned BitWidth = TD->getTypeSizeInBits((*CondStride)->getType());
2020   uint64_t SignBit = 1ULL << (BitWidth-1);
2021   const Type *CmpTy = Cond->getOperand(0)->getType();
2022   const Type *NewCmpTy = NULL;
2023   unsigned TyBits = TD->getTypeSizeInBits(CmpTy);
2024   unsigned NewTyBits = 0;
2025   SCEVHandle *NewStride = NULL;
2026   Value *NewCmpLHS = NULL;
2027   Value *NewCmpRHS = NULL;
2028   int64_t Scale = 1;
2029   SCEVHandle NewOffset = SE->getIntegerSCEV(0, UIntPtrTy);
2030
2031   if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
2032     int64_t CmpVal = C->getValue().getSExtValue();
2033
2034     // Check stride constant and the comparision constant signs to detect
2035     // overflow.
2036     if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
2037       return Cond;
2038
2039     // Look for a suitable stride / iv as replacement.
2040     for (unsigned i = 0, e = StrideOrder.size(); i != e; ++i) {
2041       std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
2042         IVUsesByStride.find(StrideOrder[i]);
2043       if (!isa<SCEVConstant>(SI->first))
2044         continue;
2045       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2046       if (abs(SSInt) <= abs(CmpSSInt) || (SSInt % CmpSSInt) != 0)
2047         continue;
2048
2049       Scale = SSInt / CmpSSInt;
2050       int64_t NewCmpVal = CmpVal * Scale;
2051       APInt Mul = APInt(BitWidth, NewCmpVal);
2052       // Check for overflow.
2053       if (Mul.getSExtValue() != NewCmpVal)
2054         continue;
2055
2056       // Watch out for overflow.
2057       if (ICmpInst::isSignedPredicate(Predicate) &&
2058           (CmpVal & SignBit) != (NewCmpVal & SignBit))
2059         continue;
2060
2061       if (NewCmpVal == CmpVal)
2062         continue;
2063       // Pick the best iv to use trying to avoid a cast.
2064       NewCmpLHS = NULL;
2065       for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2066              E = SI->second.Users.end(); UI != E; ++UI) {
2067         NewCmpLHS = UI->OperandValToReplace;
2068         if (NewCmpLHS->getType() == CmpTy)
2069           break;
2070       }
2071       if (!NewCmpLHS)
2072         continue;
2073
2074       NewCmpTy = NewCmpLHS->getType();
2075       NewTyBits = TD->getTypeSizeInBits(NewCmpTy);
2076       if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
2077         // Check if it is possible to rewrite it using
2078         // an iv / stride of a smaller integer type.
2079         bool TruncOk = false;
2080         if (NewCmpTy->isInteger()) {
2081           unsigned Bits = NewTyBits;
2082           if (ICmpInst::isSignedPredicate(Predicate))
2083             --Bits;
2084           uint64_t Mask = (1ULL << Bits) - 1;
2085           if (((uint64_t)NewCmpVal & Mask) == (uint64_t)NewCmpVal)
2086             TruncOk = true;
2087         }
2088         if (!TruncOk)
2089           continue;
2090       }
2091
2092       // Don't rewrite if use offset is non-constant and the new type is
2093       // of a different type.
2094       // FIXME: too conservative?
2095       if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->Offset))
2096         continue;
2097
2098       bool AllUsesAreAddresses = true;
2099       bool AllUsesAreOutsideLoop = true;
2100       std::vector<BasedUser> UsersToProcess;
2101       SCEVHandle CommonExprs = CollectIVUsers(SI->first, SI->second, L,
2102                                               AllUsesAreAddresses,
2103                                               AllUsesAreOutsideLoop,
2104                                               UsersToProcess);
2105       // Avoid rewriting the compare instruction with an iv of new stride
2106       // if it's likely the new stride uses will be rewritten using the
2107       // stride of the compare instruction.
2108       if (AllUsesAreAddresses &&
2109           ValidStride(!CommonExprs->isZero(), Scale, UsersToProcess))
2110         continue;
2111
2112       // If scale is negative, use swapped predicate unless it's testing
2113       // for equality.
2114       if (Scale < 0 && !Cond->isEquality())
2115         Predicate = ICmpInst::getSwappedPredicate(Predicate);
2116
2117       NewStride = &StrideOrder[i];
2118       if (!isa<PointerType>(NewCmpTy))
2119         NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
2120       else {
2121         NewCmpRHS = ConstantInt::get(UIntPtrTy, NewCmpVal);
2122         NewCmpRHS = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr,
2123                                                  NewCmpRHS, NewCmpTy);
2124       }
2125       NewOffset = TyBits == NewTyBits
2126         ? SE->getMulExpr(CondUse->Offset,
2127                          SE->getConstant(ConstantInt::get(CmpTy, Scale)))
2128         : SE->getConstant(ConstantInt::get(NewCmpTy,
2129           cast<SCEVConstant>(CondUse->Offset)->getValue()->getSExtValue()*Scale));
2130       break;
2131     }
2132   }
2133
2134   // Forgo this transformation if it the increment happens to be
2135   // unfortunately positioned after the condition, and the condition
2136   // has multiple uses which prevent it from being moved immediately
2137   // before the branch. See
2138   // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2139   // for an example of this situation.
2140   if (!Cond->hasOneUse()) {
2141     for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2142          I != E; ++I)
2143       if (I == NewCmpLHS)
2144         return Cond;
2145   }
2146
2147   if (NewCmpRHS) {
2148     // Create a new compare instruction using new stride / iv.
2149     ICmpInst *OldCond = Cond;
2150     // Insert new compare instruction.
2151     Cond = new ICmpInst(Predicate, NewCmpLHS, NewCmpRHS,
2152                         L->getHeader()->getName() + ".termcond",
2153                         OldCond);
2154
2155     // Remove the old compare instruction. The old indvar is probably dead too.
2156     DeadInsts.push_back(cast<Instruction>(CondUse->OperandValToReplace));
2157     SE->deleteValueFromRecords(OldCond);
2158     OldCond->replaceAllUsesWith(Cond);
2159     OldCond->eraseFromParent();
2160
2161     IVUsesByStride[*CondStride].Users.pop_back();
2162     IVUsesByStride[*NewStride].addUser(NewOffset, Cond, NewCmpLHS);
2163     CondUse = &IVUsesByStride[*NewStride].Users.back();
2164     CondStride = NewStride;
2165     ++NumEliminated;
2166   }
2167
2168   return Cond;
2169 }
2170
2171 /// OptimizeSMax - Rewrite the loop's terminating condition if it uses
2172 /// an smax computation.
2173 ///
2174 /// This is a narrow solution to a specific, but acute, problem. For loops
2175 /// like this:
2176 ///
2177 ///   i = 0;
2178 ///   do {
2179 ///     p[i] = 0.0;
2180 ///   } while (++i < n);
2181 ///
2182 /// where the comparison is signed, the trip count isn't just 'n', because
2183 /// 'n' could be negative. And unfortunately this can come up even for loops
2184 /// where the user didn't use a C do-while loop. For example, seemingly
2185 /// well-behaved top-test loops will commonly be lowered like this:
2186 //
2187 ///   if (n > 0) {
2188 ///     i = 0;
2189 ///     do {
2190 ///       p[i] = 0.0;
2191 ///     } while (++i < n);
2192 ///   }
2193 ///
2194 /// and then it's possible for subsequent optimization to obscure the if
2195 /// test in such a way that indvars can't find it.
2196 ///
2197 /// When indvars can't find the if test in loops like this, it creates a
2198 /// signed-max expression, which allows it to give the loop a canonical
2199 /// induction variable:
2200 ///
2201 ///   i = 0;
2202 ///   smax = n < 1 ? 1 : n;
2203 ///   do {
2204 ///     p[i] = 0.0;
2205 ///   } while (++i != smax);
2206 ///
2207 /// Canonical induction variables are necessary because the loop passes
2208 /// are designed around them. The most obvious example of this is the
2209 /// LoopInfo analysis, which doesn't remember trip count values. It
2210 /// expects to be able to rediscover the trip count each time it is
2211 /// needed, and it does this using a simple analyis that only succeeds if
2212 /// the loop has a canonical induction variable.
2213 ///
2214 /// However, when it comes time to generate code, the maximum operation
2215 /// can be quite costly, especially if it's inside of an outer loop.
2216 ///
2217 /// This function solves this problem by detecting this type of loop and
2218 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2219 /// the instructions for the maximum computation.
2220 ///
2221 ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
2222                                            IVStrideUse* &CondUse) {
2223   // Check that the loop matches the pattern we're looking for.
2224   if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2225       Cond->getPredicate() != CmpInst::ICMP_NE)
2226     return Cond;
2227
2228   SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2229   if (!Sel || !Sel->hasOneUse()) return Cond;
2230
2231   SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2232   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2233     return Cond;
2234   SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2235
2236   // Add one to the backedge-taken count to get the trip count.
2237   SCEVHandle IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
2238
2239   // Check for a max calculation that matches the pattern.
2240   SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
2241   if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
2242
2243   SCEVHandle SMaxLHS = SMax->getOperand(0);
2244   SCEVHandle SMaxRHS = SMax->getOperand(1);
2245   if (!SMaxLHS || SMaxLHS != One) return Cond;
2246
2247   // Check the relevant induction variable for conformance to
2248   // the pattern.
2249   SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2250   SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2251   if (!AR || !AR->isAffine() ||
2252       AR->getStart() != One ||
2253       AR->getStepRecurrence(*SE) != One)
2254     return Cond;
2255
2256   assert(AR->getLoop() == L &&
2257          "Loop condition operand is an addrec in a different loop!");
2258
2259   // Check the right operand of the select, and remember it, as it will
2260   // be used in the new comparison instruction.
2261   Value *NewRHS = 0;
2262   if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
2263     NewRHS = Sel->getOperand(1);
2264   else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
2265     NewRHS = Sel->getOperand(2);
2266   if (!NewRHS) return Cond;
2267
2268   // Ok, everything looks ok to change the condition into an SLT or SGE and
2269   // delete the max calculation.
2270   ICmpInst *NewCond =
2271     new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
2272                    CmpInst::ICMP_SLT :
2273                    CmpInst::ICMP_SGE,
2274                  Cond->getOperand(0), NewRHS, "scmp", Cond);
2275
2276   // Delete the max calculation instructions.
2277   SE->deleteValueFromRecords(Cond);
2278   Cond->replaceAllUsesWith(NewCond);
2279   Cond->eraseFromParent();
2280   Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2281   SE->deleteValueFromRecords(Sel);
2282   Sel->eraseFromParent();
2283   if (Cmp->use_empty()) {
2284     SE->deleteValueFromRecords(Cmp);
2285     Cmp->eraseFromParent();
2286   }
2287   CondUse->User = NewCond;
2288   return NewCond;
2289 }
2290
2291 /// OptimizeShadowIV - If IV is used in a int-to-float cast
2292 /// inside the loop then try to eliminate the cast opeation.
2293 void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2294
2295   SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2296   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2297     return;
2298
2299   for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e;
2300        ++Stride) {
2301     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
2302       IVUsesByStride.find(StrideOrder[Stride]);
2303     assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
2304     if (!isa<SCEVConstant>(SI->first))
2305       continue;
2306
2307     for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2308            E = SI->second.Users.end(); UI != E; /* empty */) {
2309       std::vector<IVStrideUse>::iterator CandidateUI = UI;
2310       ++UI;
2311       Instruction *ShadowUse = CandidateUI->User;
2312       const Type *DestTy = NULL;
2313
2314       /* If shadow use is a int->float cast then insert a second IV
2315          to eliminate this cast.
2316
2317            for (unsigned i = 0; i < n; ++i) 
2318              foo((double)i);
2319
2320          is transformed into
2321
2322            double d = 0.0;
2323            for (unsigned i = 0; i < n; ++i, ++d) 
2324              foo(d);
2325       */
2326       if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->User))
2327         DestTy = UCast->getDestTy();
2328       else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->User))
2329         DestTy = SCast->getDestTy();
2330       if (!DestTy) continue;
2331
2332       if (TLI) {
2333         /* If target does not support DestTy natively then do not apply
2334            this transformation. */
2335         MVT DVT = TLI->getValueType(DestTy);
2336         if (!TLI->isTypeLegal(DVT)) continue;
2337       }
2338
2339       PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2340       if (!PH) continue;
2341       if (PH->getNumIncomingValues() != 2) continue;
2342
2343       const Type *SrcTy = PH->getType();
2344       int Mantissa = DestTy->getFPMantissaWidth();
2345       if (Mantissa == -1) continue; 
2346       if ((int)TD->getTypeSizeInBits(SrcTy) > Mantissa)
2347         continue;
2348
2349       unsigned Entry, Latch;
2350       if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2351         Entry = 0;
2352         Latch = 1;
2353       } else {
2354         Entry = 1;
2355         Latch = 0;
2356       }
2357         
2358       ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2359       if (!Init) continue;
2360       ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2361
2362       BinaryOperator *Incr = 
2363         dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2364       if (!Incr) continue;
2365       if (Incr->getOpcode() != Instruction::Add
2366           && Incr->getOpcode() != Instruction::Sub)
2367         continue;
2368
2369       /* Initialize new IV, double d = 0.0 in above example. */
2370       ConstantInt *C = NULL;
2371       if (Incr->getOperand(0) == PH)
2372         C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2373       else if (Incr->getOperand(1) == PH)
2374         C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2375       else
2376         continue;
2377
2378       if (!C) continue;
2379
2380       /* Add new PHINode. */
2381       PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2382
2383       /* create new increment. '++d' in above example. */
2384       ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2385       BinaryOperator *NewIncr = 
2386         BinaryOperator::Create(Incr->getOpcode(),
2387                                NewPH, CFP, "IV.S.next.", Incr);
2388
2389       NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2390       NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2391
2392       /* Remove cast operation */
2393       SE->deleteValueFromRecords(ShadowUse);
2394       ShadowUse->replaceAllUsesWith(NewPH);
2395       ShadowUse->eraseFromParent();
2396       SI->second.Users.erase(CandidateUI);
2397       NumShadow++;
2398       break;
2399     }
2400   }
2401 }
2402
2403 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2404 // uses in the loop, look to see if we can eliminate some, in favor of using
2405 // common indvars for the different uses.
2406 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2407   // TODO: implement optzns here.
2408
2409   OptimizeShadowIV(L);
2410
2411   // Finally, get the terminating condition for the loop if possible.  If we
2412   // can, we want to change it to use a post-incremented version of its
2413   // induction variable, to allow coalescing the live ranges for the IV into
2414   // one register value.
2415   PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
2416   BasicBlock  *Preheader = L->getLoopPreheader();
2417   BasicBlock *LatchBlock =
2418    SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
2419   BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
2420   if (!TermBr || TermBr->isUnconditional() || 
2421       !isa<ICmpInst>(TermBr->getCondition()))
2422     return;
2423   ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2424
2425   // Search IVUsesByStride to find Cond's IVUse if there is one.
2426   IVStrideUse *CondUse = 0;
2427   const SCEVHandle *CondStride = 0;
2428
2429   if (!FindIVUserForCond(Cond, CondUse, CondStride))
2430     return; // setcc doesn't use the IV.
2431
2432   // If the trip count is computed in terms of an smax (due to ScalarEvolution
2433   // being unable to find a sufficient guard, for example), change the loop
2434   // comparison to use SLT instead of NE.
2435   Cond = OptimizeSMax(L, Cond, CondUse);
2436
2437   // If possible, change stride and operands of the compare instruction to
2438   // eliminate one stride.
2439   Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
2440
2441   // It's possible for the setcc instruction to be anywhere in the loop, and
2442   // possible for it to have multiple users.  If it is not immediately before
2443   // the latch block branch, move it.
2444   if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2445     if (Cond->hasOneUse()) {   // Condition has a single use, just move it.
2446       Cond->moveBefore(TermBr);
2447     } else {
2448       // Otherwise, clone the terminating condition and insert into the loopend.
2449       Cond = cast<ICmpInst>(Cond->clone());
2450       Cond->setName(L->getHeader()->getName() + ".termcond");
2451       LatchBlock->getInstList().insert(TermBr, Cond);
2452       
2453       // Clone the IVUse, as the old use still exists!
2454       IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
2455                                          CondUse->OperandValToReplace);
2456       CondUse = &IVUsesByStride[*CondStride].Users.back();
2457     }
2458   }
2459
2460   // If we get to here, we know that we can transform the setcc instruction to
2461   // use the post-incremented version of the IV, allowing us to coalesce the
2462   // live ranges for the IV correctly.
2463   CondUse->Offset = SE->getMinusSCEV(CondUse->Offset, *CondStride);
2464   CondUse->isUseOfPostIncrementedValue = true;
2465   Changed = true;
2466 }
2467
2468 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
2469
2470   LI = &getAnalysis<LoopInfo>();
2471   DT = &getAnalysis<DominatorTree>();
2472   SE = &getAnalysis<ScalarEvolution>();
2473   TD = &getAnalysis<TargetData>();
2474   UIntPtrTy = TD->getIntPtrType();
2475   Changed = false;
2476
2477   // Find all uses of induction variables in this loop, and categorize
2478   // them by stride.  Start by finding all of the PHI nodes in the header for
2479   // this loop.  If they are induction variables, inspect their uses.
2480   SmallPtrSet<Instruction*,16> Processed;   // Don't reprocess instructions.
2481   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
2482     AddUsersIfInteresting(I, L, Processed);
2483
2484   if (!IVUsesByStride.empty()) {
2485 #ifndef NDEBUG
2486     DOUT << "\nLSR on \"" << L->getHeader()->getParent()->getNameStart()
2487          << "\" ";
2488     DEBUG(L->dump());
2489 #endif
2490
2491     // Sort the StrideOrder so we process larger strides first.
2492     std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare(TD));
2493
2494     // Optimize induction variables.  Some indvar uses can be transformed to use
2495     // strides that will be needed for other purposes.  A common example of this
2496     // is the exit test for the loop, which can often be rewritten to use the
2497     // computation of some other indvar to decide when to terminate the loop.
2498     OptimizeIndvars(L);
2499
2500     // FIXME: We can widen subreg IV's here for RISC targets.  e.g. instead of
2501     // doing computation in byte values, promote to 32-bit values if safe.
2502
2503     // FIXME: Attempt to reuse values across multiple IV's.  In particular, we
2504     // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2505     // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2506     // Need to be careful that IV's are all the same type.  Only works for
2507     // intptr_t indvars.
2508
2509     // IVsByStride keeps IVs for one particular loop.
2510     assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
2511
2512     // Note: this processes each stride/type pair individually.  All users
2513     // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2514     // Also, note that we iterate over IVUsesByStride indirectly by using
2515     // StrideOrder. This extra layer of indirection makes the ordering of
2516     // strides deterministic - not dependent on map order.
2517     for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
2518       std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
2519         IVUsesByStride.find(StrideOrder[Stride]);
2520       assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
2521       StrengthReduceStridedIVUsers(SI->first, SI->second, L);
2522     }
2523   }
2524
2525   // We're done analyzing this loop; release all the state we built up for it.
2526   IVUsesByStride.clear();
2527   IVsByStride.clear();
2528   StrideOrder.clear();
2529
2530   // Clean up after ourselves
2531   if (!DeadInsts.empty()) {
2532     DeleteTriviallyDeadInstructions();
2533
2534     BasicBlock::iterator I = L->getHeader()->begin();
2535     while (PHINode *PN = dyn_cast<PHINode>(I++)) {
2536       // At this point, we know that we have killed one or more IV users.
2537       // It is worth checking to see if the cannonical indvar is also
2538       // dead, so that we can remove it as well.
2539       //
2540       // We can remove a PHI if it is on a cycle in the def-use graph
2541       // where each node in the cycle has degree one, i.e. only one use,
2542       // and is an instruction with no side effects.
2543       //
2544       // FIXME: this needs to eliminate an induction variable even if it's being
2545       // compared against some value to decide loop termination.
2546       if (!PN->hasOneUse())
2547         continue;
2548       
2549       SmallPtrSet<PHINode *, 4> PHIs;
2550       for (Instruction *J = dyn_cast<Instruction>(*PN->use_begin());
2551            J && J->hasOneUse() && !J->mayWriteToMemory();
2552            J = dyn_cast<Instruction>(*J->use_begin())) {
2553         // If we find the original PHI, we've discovered a cycle.
2554         if (J == PN) {
2555           // Break the cycle and mark the PHI for deletion.
2556           SE->deleteValueFromRecords(PN);
2557           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
2558           DeadInsts.push_back(PN);
2559           Changed = true;
2560           break;
2561         }
2562         // If we find a PHI more than once, we're on a cycle that
2563         // won't prove fruitful.
2564         if (isa<PHINode>(J) && !PHIs.insert(cast<PHINode>(J)))
2565           break;
2566       }
2567     }
2568     DeleteTriviallyDeadInstructions();
2569   }
2570   return Changed;
2571 }