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