LLVM API Documentation

LoopStrengthReduce.cpp

Go to the documentation of this file.
00001 //===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass performs a strength reduction on array references inside loops that
00011 // have as one or more of their components the loop induction variable.  This is
00012 // accomplished by creating a new Value to hold the initial value of the array
00013 // access for the first iteration, and then creating a new GEP instruction in
00014 // the loop to increment the value by the appropriate amount.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #define DEBUG_TYPE "loop-reduce"
00019 #include "llvm/Transforms/Scalar.h"
00020 #include "llvm/Constants.h"
00021 #include "llvm/Instructions.h"
00022 #include "llvm/IntrinsicInst.h"
00023 #include "llvm/Type.h"
00024 #include "llvm/DerivedTypes.h"
00025 #include "llvm/Analysis/Dominators.h"
00026 #include "llvm/Analysis/LoopInfo.h"
00027 #include "llvm/Analysis/LoopPass.h"
00028 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00029 #include "llvm/Support/CFG.h"
00030 #include "llvm/Support/GetElementPtrTypeIterator.h"
00031 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00032 #include "llvm/Transforms/Utils/Local.h"
00033 #include "llvm/Target/TargetData.h"
00034 #include "llvm/ADT/SmallPtrSet.h"
00035 #include "llvm/ADT/Statistic.h"
00036 #include "llvm/Support/Debug.h"
00037 #include "llvm/Support/Compiler.h"
00038 #include "llvm/Target/TargetLowering.h"
00039 #include <algorithm>
00040 #include <set>
00041 using namespace llvm;
00042 
00043 STATISTIC(NumReduced ,    "Number of GEPs strength reduced");
00044 STATISTIC(NumInserted,    "Number of PHIs inserted");
00045 STATISTIC(NumVariable,    "Number of PHIs with variable strides");
00046 STATISTIC(NumEliminated,  "Number of strides eliminated");
00047 STATISTIC(NumShadow,      "Number of Shadow IVs optimized");
00048 
00049 namespace {
00050 
00051   struct BasedUser;
00052 
00053   /// IVStrideUse - Keep track of one use of a strided induction variable, where
00054   /// the stride is stored externally.  The Offset member keeps track of the 
00055   /// offset from the IV, User is the actual user of the operand, and
00056   /// 'OperandValToReplace' is the operand of the User that is the use.
00057   struct VISIBILITY_HIDDEN IVStrideUse {
00058     SCEVHandle Offset;
00059     Instruction *User;
00060     Value *OperandValToReplace;
00061 
00062     // isUseOfPostIncrementedValue - True if this should use the
00063     // post-incremented version of this IV, not the preincremented version.
00064     // This can only be set in special cases, such as the terminating setcc
00065     // instruction for a loop or uses dominated by the loop.
00066     bool isUseOfPostIncrementedValue;
00067     
00068     IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
00069       : Offset(Offs), User(U), OperandValToReplace(O),
00070         isUseOfPostIncrementedValue(false) {}
00071   };
00072   
00073   /// IVUsersOfOneStride - This structure keeps track of all instructions that
00074   /// have an operand that is based on the trip count multiplied by some stride.
00075   /// The stride for all of these users is common and kept external to this
00076   /// structure.
00077   struct VISIBILITY_HIDDEN IVUsersOfOneStride {
00078     /// Users - Keep track of all of the users of this stride as well as the
00079     /// initial value and the operand that uses the IV.
00080     std::vector<IVStrideUse> Users;
00081     
00082     void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
00083       Users.push_back(IVStrideUse(Offset, User, Operand));
00084     }
00085   };
00086 
00087   /// IVInfo - This structure keeps track of one IV expression inserted during
00088   /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
00089   /// well as the PHI node and increment value created for rewrite.
00090   struct VISIBILITY_HIDDEN IVExpr {
00091     SCEVHandle  Stride;
00092     SCEVHandle  Base;
00093     PHINode    *PHI;
00094     Value      *IncV;
00095 
00096     IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
00097            Value *incv)
00098       : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
00099   };
00100 
00101   /// IVsOfOneStride - This structure keeps track of all IV expression inserted
00102   /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
00103   struct VISIBILITY_HIDDEN IVsOfOneStride {
00104     std::vector<IVExpr> IVs;
00105 
00106     void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
00107                Value *IncV) {
00108       IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
00109     }
00110   };
00111 
00112   class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
00113     LoopInfo *LI;
00114     DominatorTree *DT;
00115     ScalarEvolution *SE;
00116     const TargetData *TD;
00117     const Type *UIntPtrTy;
00118     bool Changed;
00119 
00120     /// IVUsesByStride - Keep track of all uses of induction variables that we
00121     /// are interested in.  The key of the map is the stride of the access.
00122     std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
00123 
00124     /// IVsByStride - Keep track of all IVs that have been inserted for a
00125     /// particular stride.
00126     std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
00127 
00128     /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
00129     /// We use this to iterate over the IVUsesByStride collection without being
00130     /// dependent on random ordering of pointers in the process.
00131     SmallVector<SCEVHandle, 16> StrideOrder;
00132 
00133     /// GEPlist - A list of the GEP's that have been remembered in the SCEV
00134     /// data structures.  SCEV does not know to update these when the operands
00135     /// of the GEP are changed, which means we cannot leave them live across
00136     /// loops.
00137     SmallVector<GetElementPtrInst *, 16> GEPlist;
00138 
00139     /// CastedValues - As we need to cast values to uintptr_t, this keeps track
00140     /// of the casted version of each value.  This is accessed by
00141     /// getCastedVersionOf.
00142     DenseMap<Value*, Value*> CastedPointers;
00143 
00144     /// DeadInsts - Keep track of instructions we may have made dead, so that
00145     /// we can remove them after we are done working.
00146     SmallVector<Instruction*, 16> DeadInsts;
00147 
00148     /// TLI - Keep a pointer of a TargetLowering to consult for determining
00149     /// transformation profitability.
00150     const TargetLowering *TLI;
00151 
00152   public:
00153     static char ID; // Pass ID, replacement for typeid
00154     explicit LoopStrengthReduce(const TargetLowering *tli = NULL) : 
00155       LoopPass(&ID), TLI(tli) {
00156     }
00157 
00158     bool runOnLoop(Loop *L, LPPassManager &LPM);
00159 
00160     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00161       // We split critical edges, so we change the CFG.  However, we do update
00162       // many analyses if they are around.
00163       AU.addPreservedID(LoopSimplifyID);
00164       AU.addPreserved<LoopInfo>();
00165       AU.addPreserved<DominanceFrontier>();
00166       AU.addPreserved<DominatorTree>();
00167 
00168       AU.addRequiredID(LoopSimplifyID);
00169       AU.addRequired<LoopInfo>();
00170       AU.addRequired<DominatorTree>();
00171       AU.addRequired<TargetData>();
00172       AU.addRequired<ScalarEvolution>();
00173       AU.addPreserved<ScalarEvolution>();
00174     }
00175     
00176     /// getCastedVersionOf - Return the specified value casted to uintptr_t.
00177     ///
00178     Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
00179 private:
00180     bool AddUsersIfInteresting(Instruction *I, Loop *L,
00181                                SmallPtrSet<Instruction*,16> &Processed);
00182     SCEVHandle GetExpressionSCEV(Instruction *E);
00183     ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
00184                                   IVStrideUse* &CondUse,
00185                                   const SCEVHandle* &CondStride);
00186     void OptimizeIndvars(Loop *L);
00187 
00188     /// OptimizeShadowIV - If IV is used in a int-to-float cast
00189     /// inside the loop then try to eliminate the cast opeation.
00190     void OptimizeShadowIV(Loop *L);
00191 
00192     /// OptimizeSMax - Rewrite the loop's terminating condition
00193     /// if it uses an smax computation.
00194     ICmpInst *OptimizeSMax(Loop *L, ICmpInst *Cond,
00195                            IVStrideUse* &CondUse);
00196 
00197     bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
00198                            const SCEVHandle *&CondStride);
00199     bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
00200     SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
00201                              IVExpr&, const Type*,
00202                              const std::vector<BasedUser>& UsersToProcess);
00203     bool ValidStride(bool, int64_t,
00204                      const std::vector<BasedUser>& UsersToProcess);
00205     SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
00206                               IVUsersOfOneStride &Uses,
00207                               Loop *L,
00208                               bool &AllUsesAreAddresses,
00209                               bool &AllUsesAreOutsideLoop,
00210                               std::vector<BasedUser> &UsersToProcess);
00211     void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
00212                                       IVUsersOfOneStride &Uses,
00213                                       Loop *L, bool isOnlyStride);
00214     void DeleteTriviallyDeadInstructions();
00215   };
00216 }
00217 
00218 char LoopStrengthReduce::ID = 0;
00219 static RegisterPass<LoopStrengthReduce>
00220 X("loop-reduce", "Loop Strength Reduction");
00221 
00222 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
00223   return new LoopStrengthReduce(TLI);
00224 }
00225 
00226 /// getCastedVersionOf - Return the specified value casted to uintptr_t. This
00227 /// assumes that the Value* V is of integer or pointer type only.
00228 ///
00229 Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode, 
00230                                               Value *V) {
00231   if (V->getType() == UIntPtrTy) return V;
00232   if (Constant *CB = dyn_cast<Constant>(V))
00233     return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
00234 
00235   Value *&New = CastedPointers[V];
00236   if (New) return New;
00237   
00238   New = SCEVExpander::InsertCastOfTo(opcode, V, UIntPtrTy);
00239   DeadInsts.push_back(cast<Instruction>(New));
00240   return New;
00241 }
00242 
00243 
00244 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
00245 /// specified set are trivially dead, delete them and see if this makes any of
00246 /// their operands subsequently dead.
00247 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
00248   if (DeadInsts.empty()) return;
00249   
00250   // Sort the deadinsts list so that we can trivially eliminate duplicates as we
00251   // go.  The code below never adds a non-dead instruction to the worklist, but
00252   // callers may not be so careful.
00253   array_pod_sort(DeadInsts.begin(), DeadInsts.end());
00254 
00255   // Drop duplicate instructions and those with uses.
00256   for (unsigned i = 0, e = DeadInsts.size()-1; i < e; ++i) {
00257     Instruction *I = DeadInsts[i];
00258     if (!I->use_empty()) DeadInsts[i] = 0;
00259     while (i != e && DeadInsts[i+1] == I)
00260       DeadInsts[++i] = 0;
00261   }
00262   
00263   while (!DeadInsts.empty()) {
00264     Instruction *I = DeadInsts.back();
00265     DeadInsts.pop_back();
00266     
00267     if (I == 0 || !isInstructionTriviallyDead(I))
00268       continue;
00269 
00270     SE->deleteValueFromRecords(I);
00271 
00272     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
00273       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
00274         *OI = 0;
00275         if (U->use_empty())
00276           DeadInsts.push_back(U);
00277       }
00278     }
00279     
00280     I->eraseFromParent();
00281     Changed = true;
00282   }
00283 }
00284 
00285 
00286 /// GetExpressionSCEV - Compute and return the SCEV for the specified
00287 /// instruction.
00288 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp) {
00289   // Pointer to pointer bitcast instructions return the same value as their
00290   // operand.
00291   if (BitCastInst *BCI = dyn_cast<BitCastInst>(Exp)) {
00292     if (SE->hasSCEV(BCI) || !isa<Instruction>(BCI->getOperand(0)))
00293       return SE->getSCEV(BCI);
00294     SCEVHandle R = GetExpressionSCEV(cast<Instruction>(BCI->getOperand(0)));
00295     SE->setSCEV(BCI, R);
00296     return R;
00297   }
00298 
00299   // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
00300   // If this is a GEP that SE doesn't know about, compute it now and insert it.
00301   // If this is not a GEP, or if we have already done this computation, just let
00302   // SE figure it out.
00303   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
00304   if (!GEP || SE->hasSCEV(GEP))
00305     return SE->getSCEV(Exp);
00306     
00307   // Analyze all of the subscripts of this getelementptr instruction, looking
00308   // for uses that are determined by the trip count of the loop.  First, skip
00309   // all operands the are not dependent on the IV.
00310 
00311   // Build up the base expression.  Insert an LLVM cast of the pointer to
00312   // uintptr_t first.
00313   SCEVHandle GEPVal = SE->getUnknown(
00314       getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
00315 
00316   gep_type_iterator GTI = gep_type_begin(GEP);
00317   
00318   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
00319        i != e; ++i, ++GTI) {
00320     // If this is a use of a recurrence that we can analyze, and it comes before
00321     // Op does in the GEP operand list, we will handle this when we process this
00322     // operand.
00323     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
00324       const StructLayout *SL = TD->getStructLayout(STy);
00325       unsigned Idx = cast<ConstantInt>(*i)->getZExtValue();
00326       uint64_t Offset = SL->getElementOffset(Idx);
00327       GEPVal = SE->getAddExpr(GEPVal,
00328                              SE->getIntegerSCEV(Offset, UIntPtrTy));
00329     } else {
00330       unsigned GEPOpiBits = 
00331         (*i)->getType()->getPrimitiveSizeInBits();
00332       unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
00333       Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ? 
00334           Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
00335             Instruction::BitCast));
00336       Value *OpVal = getCastedVersionOf(opcode, *i);
00337       SCEVHandle Idx = SE->getSCEV(OpVal);
00338 
00339       uint64_t TypeSize = TD->getTypePaddedSize(GTI.getIndexedType());
00340       if (TypeSize != 1)
00341         Idx = SE->getMulExpr(Idx,
00342                             SE->getConstant(ConstantInt::get(UIntPtrTy,
00343                                                              TypeSize)));
00344       GEPVal = SE->getAddExpr(GEPVal, Idx);
00345     }
00346   }
00347 
00348   SE->setSCEV(GEP, GEPVal);
00349   GEPlist.push_back(GEP);
00350   return GEPVal;
00351 }
00352 
00353 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a 
00354 /// subexpression that is an AddRec from a loop other than L.  An outer loop 
00355 /// of L is OK, but not an inner loop nor a disjoint loop.
00356 static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
00357   // This is very common, put it first.
00358   if (isa<SCEVConstant>(S))
00359     return false;
00360   if (SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
00361     for (unsigned int i=0; i< AE->getNumOperands(); i++)
00362       if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
00363         return true;
00364     return false;
00365   }
00366   if (SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
00367     if (const Loop *newLoop = AE->getLoop()) {
00368       if (newLoop == L)
00369         return false;
00370       // if newLoop is an outer loop of L, this is OK.
00371       if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
00372         return false;
00373     }
00374     return true;
00375   }
00376   if (SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
00377     return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
00378            containsAddRecFromDifferentLoop(DE->getRHS(), L);
00379 #if 0
00380   // SCEVSDivExpr has been backed out temporarily, but will be back; we'll 
00381   // need this when it is.
00382   if (SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
00383     return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
00384            containsAddRecFromDifferentLoop(DE->getRHS(), L);
00385 #endif
00386   if (SCEVTruncateExpr *TE = dyn_cast<SCEVTruncateExpr>(S))
00387     return containsAddRecFromDifferentLoop(TE->getOperand(), L);
00388   if (SCEVZeroExtendExpr *ZE = dyn_cast<SCEVZeroExtendExpr>(S))
00389     return containsAddRecFromDifferentLoop(ZE->getOperand(), L);
00390   if (SCEVSignExtendExpr *SE = dyn_cast<SCEVSignExtendExpr>(S))
00391     return containsAddRecFromDifferentLoop(SE->getOperand(), L);
00392   return false;
00393 }
00394 
00395 /// getSCEVStartAndStride - Compute the start and stride of this expression,
00396 /// returning false if the expression is not a start/stride pair, or true if it
00397 /// is.  The stride must be a loop invariant expression, but the start may be
00398 /// a mix of loop invariant and loop variant expressions.  The start cannot,
00399 /// however, contain an AddRec from a different loop, unless that loop is an
00400 /// outer loop of the current loop.
00401 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
00402                                   SCEVHandle &Start, SCEVHandle &Stride,
00403                                   ScalarEvolution *SE, DominatorTree *DT) {
00404   SCEVHandle TheAddRec = Start;   // Initialize to zero.
00405 
00406   // If the outer level is an AddExpr, the operands are all start values except
00407   // for a nested AddRecExpr.
00408   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
00409     for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
00410       if (SCEVAddRecExpr *AddRec =
00411              dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
00412         if (AddRec->getLoop() == L)
00413           TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
00414         else
00415           return false;  // Nested IV of some sort?
00416       } else {
00417         Start = SE->getAddExpr(Start, AE->getOperand(i));
00418       }
00419         
00420   } else if (isa<SCEVAddRecExpr>(SH)) {
00421     TheAddRec = SH;
00422   } else {
00423     return false;  // not analyzable.
00424   }
00425   
00426   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
00427   if (!AddRec || AddRec->getLoop() != L) return false;
00428   
00429   // FIXME: Generalize to non-affine IV's.
00430   if (!AddRec->isAffine()) return false;
00431 
00432   // If Start contains an SCEVAddRecExpr from a different loop, other than an
00433   // outer loop of the current loop, reject it.  SCEV has no concept of 
00434   // operating on one loop at a time so don't confuse it with such expressions.
00435   if (containsAddRecFromDifferentLoop(Start, L))
00436     return false;
00437 
00438   Start = SE->getAddExpr(Start, AddRec->getOperand(0));
00439   
00440   if (!isa<SCEVConstant>(AddRec->getOperand(1))) {
00441     // If stride is an instruction, make sure it dominates the loop header.
00442     // Otherwise we could end up with a use before def situation.
00443     if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(AddRec->getOperand(1))) {
00444       if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
00445         BasicBlock *StrideBB = I->getParent();
00446         BasicBlock *Preheader = L->getLoopPreheader();
00447         if (!DT->dominates(StrideBB, Preheader))
00448           return false;
00449       }
00450     }
00451 
00452     DOUT << "[" << L->getHeader()->getName()
00453          << "] Variable stride: " << *AddRec << "\n";
00454   }
00455 
00456   Stride = AddRec->getOperand(1);
00457   return true;
00458 }
00459 
00460 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
00461 /// and now we need to decide whether the user should use the preinc or post-inc
00462 /// value.  If this user should use the post-inc version of the IV, return true.
00463 ///
00464 /// Choosing wrong here can break dominance properties (if we choose to use the
00465 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
00466 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
00467 /// should use the post-inc value).
00468 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
00469                                        Loop *L, DominatorTree *DT, Pass *P,
00470                                       SmallVectorImpl<Instruction*> &DeadInsts){
00471   // If the user is in the loop, use the preinc value.
00472   if (L->contains(User->getParent())) return false;
00473   
00474   BasicBlock *LatchBlock = L->getLoopLatch();
00475   
00476   // Ok, the user is outside of the loop.  If it is dominated by the latch
00477   // block, use the post-inc value.
00478   if (DT->dominates(LatchBlock, User->getParent()))
00479     return true;
00480 
00481   // There is one case we have to be careful of: PHI nodes.  These little guys
00482   // can live in blocks that do not dominate the latch block, but (since their
00483   // uses occur in the predecessor block, not the block the PHI lives in) should
00484   // still use the post-inc value.  Check for this case now.
00485   PHINode *PN = dyn_cast<PHINode>(User);
00486   if (!PN) return false;  // not a phi, not dominated by latch block.
00487   
00488   // Look at all of the uses of IV by the PHI node.  If any use corresponds to
00489   // a block that is not dominated by the latch block, give up and use the
00490   // preincremented value.
00491   unsigned NumUses = 0;
00492   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00493     if (PN->getIncomingValue(i) == IV) {
00494       ++NumUses;
00495       if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
00496         return false;
00497     }
00498 
00499   // Okay, all uses of IV by PN are in predecessor blocks that really are
00500   // dominated by the latch block.  Split the critical edges and use the
00501   // post-incremented value.
00502   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00503     if (PN->getIncomingValue(i) == IV) {
00504       SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P, false);
00505       // Splitting the critical edge can reduce the number of entries in this
00506       // PHI.
00507       e = PN->getNumIncomingValues();
00508       if (--NumUses == 0) break;
00509     }
00510 
00511   // PHI node might have become a constant value after SplitCriticalEdge.
00512   DeadInsts.push_back(User);
00513   
00514   return true;
00515 }
00516 
00517 /// isAddress - Returns true if the specified instruction is using the
00518 /// specified value as an address.
00519 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
00520   bool isAddress = isa<LoadInst>(Inst);
00521   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00522     if (SI->getOperand(1) == OperandVal)
00523       isAddress = true;
00524   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
00525     // Addressing modes can also be folded into prefetches and a variety
00526     // of intrinsics.
00527     switch (II->getIntrinsicID()) {
00528       default: break;
00529       case Intrinsic::prefetch:
00530       case Intrinsic::x86_sse2_loadu_dq:
00531       case Intrinsic::x86_sse2_loadu_pd:
00532       case Intrinsic::x86_sse_loadu_ps:
00533       case Intrinsic::x86_sse_storeu_ps:
00534       case Intrinsic::x86_sse2_storeu_pd:
00535       case Intrinsic::x86_sse2_storeu_dq:
00536       case Intrinsic::x86_sse2_storel_dq:
00537         if (II->getOperand(1) == OperandVal)
00538           isAddress = true;
00539         break;
00540     }
00541   }
00542   return isAddress;
00543 }
00544 
00545 /// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
00546 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
00547 /// return true.  Otherwise, return false.
00548 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
00549                                       SmallPtrSet<Instruction*,16> &Processed) {
00550   if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
00551     return false;   // Void and FP expressions cannot be reduced.
00552   if (!Processed.insert(I))
00553     return true;    // Instruction already handled.
00554   
00555   // Get the symbolic expression for this instruction.
00556   SCEVHandle ISE = GetExpressionSCEV(I);
00557   if (isa<SCEVCouldNotCompute>(ISE)) return false;
00558   
00559   // Get the start and stride for this expression.
00560   SCEVHandle Start = SE->getIntegerSCEV(0, ISE->getType());
00561   SCEVHandle Stride = Start;
00562   if (!getSCEVStartAndStride(ISE, L, Start, Stride, SE, DT))
00563     return false;  // Non-reducible symbolic expression, bail out.
00564 
00565   std::vector<Instruction *> IUsers;
00566   // Collect all I uses now because IVUseShouldUsePostIncValue may 
00567   // invalidate use_iterator.
00568   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
00569     IUsers.push_back(cast<Instruction>(*UI));
00570 
00571   for (unsigned iused_index = 0, iused_size = IUsers.size(); 
00572        iused_index != iused_size; ++iused_index) {
00573 
00574     Instruction *User = IUsers[iused_index];
00575 
00576     // Do not infinitely recurse on PHI nodes.
00577     if (isa<PHINode>(User) && Processed.count(User))
00578       continue;
00579 
00580     // Descend recursively, but not into PHI nodes outside the current loop.
00581     // It's important to see the entire expression outside the loop to get
00582     // choices that depend on addressing mode use right, although we won't
00583     // consider references ouside the loop in all cases.
00584     // If User is already in Processed, we don't want to recurse into it again,
00585     // but do want to record a second reference in the same instruction.
00586     bool AddUserToIVUsers = false;
00587     if (LI->getLoopFor(User->getParent()) != L) {
00588       if (isa<PHINode>(User) || Processed.count(User) ||
00589           !AddUsersIfInteresting(User, L, Processed)) {
00590         DOUT << "FOUND USER in other loop: " << *User
00591              << "   OF SCEV: " << *ISE << "\n";
00592         AddUserToIVUsers = true;
00593       }
00594     } else if (Processed.count(User) || 
00595                !AddUsersIfInteresting(User, L, Processed)) {
00596       DOUT << "FOUND USER: " << *User
00597            << "   OF SCEV: " << *ISE << "\n";
00598       AddUserToIVUsers = true;
00599     }
00600 
00601     if (AddUserToIVUsers) {
00602       IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
00603       if (StrideUses.Users.empty())     // First occurrence of this stride?
00604         StrideOrder.push_back(Stride);
00605       
00606       // Okay, we found a user that we cannot reduce.  Analyze the instruction
00607       // and decide what to do with it.  If we are a use inside of the loop, use
00608       // the value before incrementation, otherwise use it after incrementation.
00609       if (IVUseShouldUsePostIncValue(User, I, L, DT, this, DeadInsts)) {
00610         // The value used will be incremented by the stride more than we are
00611         // expecting, so subtract this off.
00612         SCEVHandle NewStart = SE->getMinusSCEV(Start, Stride);
00613         StrideUses.addUser(NewStart, User, I);
00614         StrideUses.Users.back().isUseOfPostIncrementedValue = true;
00615         DOUT << "   USING POSTINC SCEV, START=" << *NewStart<< "\n";
00616       } else {        
00617         StrideUses.addUser(Start, User, I);
00618       }
00619     }
00620   }
00621   return true;
00622 }
00623 
00624 namespace {
00625   /// BasedUser - For a particular base value, keep information about how we've
00626   /// partitioned the expression so far.
00627   struct BasedUser {
00628     /// SE - The current ScalarEvolution object.
00629     ScalarEvolution *SE;
00630 
00631     /// Base - The Base value for the PHI node that needs to be inserted for
00632     /// this use.  As the use is processed, information gets moved from this
00633     /// field to the Imm field (below).  BasedUser values are sorted by this
00634     /// field.
00635     SCEVHandle Base;
00636     
00637     /// Inst - The instruction using the induction variable.
00638     Instruction *Inst;
00639 
00640     /// OperandValToReplace - The operand value of Inst to replace with the
00641     /// EmittedBase.
00642     Value *OperandValToReplace;
00643 
00644     /// Imm - The immediate value that should be added to the base immediately
00645     /// before Inst, because it will be folded into the imm field of the
00646     /// instruction.
00647     SCEVHandle Imm;
00648 
00649     // isUseOfPostIncrementedValue - True if this should use the
00650     // post-incremented version of this IV, not the preincremented version.
00651     // This can only be set in special cases, such as the terminating setcc
00652     // instruction for a loop and uses outside the loop that are dominated by
00653     // the loop.
00654     bool isUseOfPostIncrementedValue;
00655     
00656     BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
00657       : SE(se), Base(IVSU.Offset), Inst(IVSU.User), 
00658         OperandValToReplace(IVSU.OperandValToReplace), 
00659         Imm(SE->getIntegerSCEV(0, Base->getType())), 
00660         isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
00661 
00662     // Once we rewrite the code to insert the new IVs we want, update the
00663     // operands of Inst to use the new expression 'NewBase', with 'Imm' added
00664     // to it.
00665     void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
00666                                         Instruction *InsertPt,
00667                                        SCEVExpander &Rewriter, Loop *L, Pass *P,
00668                                       SmallVectorImpl<Instruction*> &DeadInsts);
00669     
00670     Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase, 
00671                                        SCEVExpander &Rewriter,
00672                                        Instruction *IP, Loop *L);
00673     void dump() const;
00674   };
00675 }
00676 
00677 void BasedUser::dump() const {
00678   cerr << " Base=" << *Base;
00679   cerr << " Imm=" << *Imm;
00680   cerr << "   Inst: " << *Inst;
00681 }
00682 
00683 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase, 
00684                                               SCEVExpander &Rewriter,
00685                                               Instruction *IP, Loop *L) {
00686   // Figure out where we *really* want to insert this code.  In particular, if
00687   // the user is inside of a loop that is nested inside of L, we really don't
00688   // want to insert this expression before the user, we'd rather pull it out as
00689   // many loops as possible.
00690   LoopInfo &LI = Rewriter.getLoopInfo();
00691   Instruction *BaseInsertPt = IP;
00692   
00693   // Figure out the most-nested loop that IP is in.
00694   Loop *InsertLoop = LI.getLoopFor(IP->getParent());
00695   
00696   // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
00697   // the preheader of the outer-most loop where NewBase is not loop invariant.
00698   if (L->contains(IP->getParent()))
00699     while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
00700       BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
00701       InsertLoop = InsertLoop->getParentLoop();
00702     }
00703   
00704   // If there is no immediate value, skip the next part.
00705   if (Imm->isZero())
00706     return Rewriter.expandCodeFor(NewBase, BaseInsertPt);
00707 
00708   Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
00709 
00710   // If we are inserting the base and imm values in the same block, make sure to
00711   // adjust the IP position if insertion reused a result.
00712   if (IP == BaseInsertPt)
00713     IP = Rewriter.getInsertionPoint();
00714   
00715   // Always emit the immediate (if non-zero) into the same block as the user.
00716   SCEVHandle NewValSCEV = SE->getAddExpr(SE->getUnknown(Base), Imm);
00717   return Rewriter.expandCodeFor(NewValSCEV, IP);
00718   
00719 }
00720 
00721 
00722 // Once we rewrite the code to insert the new IVs we want, update the
00723 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
00724 // to it. NewBasePt is the last instruction which contributes to the
00725 // value of NewBase in the case that it's a diffferent instruction from
00726 // the PHI that NewBase is computed from, or null otherwise.
00727 //
00728 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
00729                                                Instruction *NewBasePt,
00730                                       SCEVExpander &Rewriter, Loop *L, Pass *P,
00731                                       SmallVectorImpl<Instruction*> &DeadInsts){
00732   if (!isa<PHINode>(Inst)) {
00733     // By default, insert code at the user instruction.
00734     BasicBlock::iterator InsertPt = Inst;
00735     
00736     // However, if the Operand is itself an instruction, the (potentially
00737     // complex) inserted code may be shared by many users.  Because of this, we
00738     // want to emit code for the computation of the operand right before its old
00739     // computation.  This is usually safe, because we obviously used to use the
00740     // computation when it was computed in its current block.  However, in some
00741     // cases (e.g. use of a post-incremented induction variable) the NewBase
00742     // value will be pinned to live somewhere after the original computation.
00743     // In this case, we have to back off.
00744     //
00745     // If this is a use outside the loop (which means after, since it is based
00746     // on a loop indvar) we use the post-incremented value, so that we don't
00747     // artificially make the preinc value live out the bottom of the loop. 
00748     if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
00749       if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
00750         InsertPt = NewBasePt;
00751         ++InsertPt;
00752       } else if (Instruction *OpInst
00753                  = dyn_cast<Instruction>(OperandValToReplace)) {
00754         InsertPt = OpInst;
00755         while (isa<PHINode>(InsertPt)) ++InsertPt;
00756       }
00757     }
00758     Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
00759     // Adjust the type back to match the Inst. Note that we can't use InsertPt
00760     // here because the SCEVExpander may have inserted the instructions after
00761     // that point, in its efforts to avoid inserting redundant expressions.
00762     if (isa<PointerType>(OperandValToReplace->getType())) {
00763       NewVal = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr,
00764                                             NewVal,
00765                                             OperandValToReplace->getType());
00766     }
00767     // Replace the use of the operand Value with the new Phi we just created.
00768     Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
00769     DOUT << "    CHANGED: IMM =" << *Imm;
00770     DOUT << "  \tNEWBASE =" << *NewBase;
00771     DOUT << "  \tInst = " << *Inst;
00772     return;
00773   }
00774   
00775   // PHI nodes are more complex.  We have to insert one copy of the NewBase+Imm
00776   // expression into each operand block that uses it.  Note that PHI nodes can
00777   // have multiple entries for the same predecessor.  We use a map to make sure
00778   // that a PHI node only has a single Value* for each predecessor (which also
00779   // prevents us from inserting duplicate code in some blocks).
00780   DenseMap<BasicBlock*, Value*> InsertedCode;
00781   PHINode *PN = cast<PHINode>(Inst);
00782   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00783     if (PN->getIncomingValue(i) == OperandValToReplace) {
00784       // If the original expression is outside the loop, put the replacement
00785       // code in the same place as the original expression,
00786       // which need not be an immediate predecessor of this PHI.  This way we 
00787       // need only one copy of it even if it is referenced multiple times in
00788       // the PHI.  We don't do this when the original expression is inside the
00789       // loop because multiple copies sometimes do useful sinking of code in
00790       // that case(?).
00791       Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
00792       if (L->contains(OldLoc->getParent())) {
00793         // If this is a critical edge, split the edge so that we do not insert
00794         // the code on all predecessor/successor paths.  We do this unless this
00795         // is the canonical backedge for this loop, as this can make some
00796         // inserted code be in an illegal position.
00797         BasicBlock *PHIPred = PN->getIncomingBlock(i);
00798         if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
00799             (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
00800 
00801           // First step, split the critical edge.
00802           SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
00803 
00804           // Next step: move the basic block.  In particular, if the PHI node
00805           // is outside of the loop, and PredTI is in the loop, we want to
00806           // move the block to be immediately before the PHI block, not
00807           // immediately after PredTI.
00808           if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
00809             BasicBlock *NewBB = PN->getIncomingBlock(i);
00810             NewBB->moveBefore(PN->getParent());
00811           }
00812 
00813           // Splitting the edge can reduce the number of PHI entries we have.
00814           e = PN->getNumIncomingValues();
00815         }
00816       }
00817       Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
00818       if (!Code) {
00819         // Insert the code into the end of the predecessor block.
00820         Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
00821                                 PN->getIncomingBlock(i)->getTerminator() :
00822                                 OldLoc->getParent()->getTerminator();
00823         Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
00824 
00825         // Adjust the type back to match the PHI. Note that we can't use
00826         // InsertPt here because the SCEVExpander may have inserted its
00827         // instructions after that point, in its efforts to avoid inserting
00828         // redundant expressions.
00829         if (isa<PointerType>(PN->getType())) {
00830           Code = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr,
00831                                               Code,
00832                                               PN->getType());
00833         }
00834       }
00835       
00836       // Replace the use of the operand Value with the new Phi we just created.
00837       PN->setIncomingValue(i, Code);
00838       Rewriter.clear();
00839     }
00840   }
00841 
00842   // PHI node might have become a constant value after SplitCriticalEdge.
00843   DeadInsts.push_back(Inst);
00844 
00845   DOUT << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst;
00846 }
00847 
00848 
00849 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
00850 /// mode, and does not need to be put in a register first.
00851 static bool fitsInAddressMode(const SCEVHandle &V, const Type *UseTy,
00852                              const TargetLowering *TLI, bool HasBaseReg) {
00853   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
00854     int64_t VC = SC->getValue()->getSExtValue();
00855     if (TLI) {
00856       TargetLowering::AddrMode AM;
00857       AM.BaseOffs = VC;
00858       AM.HasBaseReg = HasBaseReg;
00859       return TLI->isLegalAddressingMode(AM, UseTy);
00860     } else {
00861       // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
00862       return (VC > -(1 << 16) && VC < (1 << 16)-1);
00863     }
00864   }
00865 
00866   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
00867     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
00868       if (TLI && CE->getOpcode() == Instruction::PtrToInt) {
00869         Constant *Op0 = CE->getOperand(0);
00870         if (GlobalValue *GV = dyn_cast<GlobalValue>(Op0)) {
00871           TargetLowering::AddrMode AM;
00872           AM.BaseGV = GV;
00873           AM.HasBaseReg = HasBaseReg;
00874           return TLI->isLegalAddressingMode(AM, UseTy);
00875         }
00876       }
00877   return false;
00878 }
00879 
00880 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
00881 /// loop varying to the Imm operand.
00882 static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
00883                                             Loop *L, ScalarEvolution *SE) {
00884   if (Val->isLoopInvariant(L)) return;  // Nothing to do.
00885   
00886   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
00887     std::vector<SCEVHandle> NewOps;
00888     NewOps.reserve(SAE->getNumOperands());
00889     
00890     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
00891       if (!SAE->getOperand(i)->isLoopInvariant(L)) {
00892         // If this is a loop-variant expression, it must stay in the immediate
00893         // field of the expression.
00894         Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
00895       } else {
00896         NewOps.push_back(SAE->getOperand(i));
00897       }
00898 
00899     if (NewOps.empty())
00900       Val = SE->getIntegerSCEV(0, Val->getType());
00901     else
00902       Val = SE->getAddExpr(NewOps);
00903   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
00904     // Try to pull immediates out of the start value of nested addrec's.
00905     SCEVHandle Start = SARE->getStart();
00906     MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
00907     
00908     std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
00909     Ops[0] = Start;
00910     Val = SE->getAddRecExpr(Ops, SARE->getLoop());
00911   } else {
00912     // Otherwise, all of Val is variant, move the whole thing over.
00913     Imm = SE->getAddExpr(Imm, Val);
00914     Val = SE->getIntegerSCEV(0, Val->getType());
00915   }
00916 }
00917 
00918 
00919 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
00920 /// that can fit into the immediate field of instructions in the target.
00921 /// Accumulate these immediate values into the Imm value.
00922 static void MoveImmediateValues(const TargetLowering *TLI,
00923                                 Instruction *User,
00924                                 SCEVHandle &Val, SCEVHandle &Imm,
00925                                 bool isAddress, Loop *L,
00926                                 ScalarEvolution *SE) {
00927   const Type *UseTy = User->getType();
00928   if (StoreInst *SI = dyn_cast<StoreInst>(User))
00929     UseTy = SI->getOperand(0)->getType();
00930 
00931   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
00932     std::vector<SCEVHandle> NewOps;
00933     NewOps.reserve(SAE->getNumOperands());
00934     
00935     for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
00936       SCEVHandle NewOp = SAE->getOperand(i);
00937       MoveImmediateValues(TLI, User, NewOp, Imm, isAddress, L, SE);
00938       
00939       if (!NewOp->isLoopInvariant(L)) {
00940         // If this is a loop-variant expression, it must stay in the immediate
00941         // field of the expression.
00942         Imm = SE->getAddExpr(Imm, NewOp);
00943       } else {
00944         NewOps.push_back(NewOp);
00945       }
00946     }
00947 
00948     if (NewOps.empty())
00949       Val = SE->getIntegerSCEV(0, Val->getType());
00950     else
00951       Val = SE->getAddExpr(NewOps);
00952     return;
00953   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
00954     // Try to pull immediates out of the start value of nested addrec's.
00955     SCEVHandle Start = SARE->getStart();
00956     MoveImmediateValues(TLI, User, Start, Imm, isAddress, L, SE);
00957     
00958     if (Start != SARE->getStart()) {
00959       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
00960       Ops[0] = Start;
00961       Val = SE->getAddRecExpr(Ops, SARE->getLoop());
00962     }
00963     return;
00964   } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
00965     // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
00966     if (isAddress && fitsInAddressMode(SME->getOperand(0), UseTy, TLI, false) &&
00967         SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
00968 
00969       SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
00970       SCEVHandle NewOp = SME->getOperand(1);
00971       MoveImmediateValues(TLI, User, NewOp, SubImm, isAddress, L, SE);
00972       
00973       // If we extracted something out of the subexpressions, see if we can 
00974       // simplify this!
00975       if (NewOp != SME->getOperand(1)) {
00976         // Scale SubImm up by "8".  If the result is a target constant, we are
00977         // good.
00978         SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
00979         if (fitsInAddressMode(SubImm, UseTy, TLI, false)) {
00980           // Accumulate the immediate.
00981           Imm = SE->getAddExpr(Imm, SubImm);
00982           
00983           // Update what is left of 'Val'.
00984           Val = SE->getMulExpr(SME->getOperand(0), NewOp);
00985           return;
00986         }
00987       }
00988     }
00989   }
00990 
00991   // Loop-variant expressions must stay in the immediate field of the
00992   // expression.
00993   if ((isAddress && fitsInAddressMode(Val, UseTy, TLI, false)) ||
00994       !Val->isLoopInvariant(L)) {
00995     Imm = SE->getAddExpr(Imm, Val);
00996     Val = SE->getIntegerSCEV(0, Val->getType());
00997     return;
00998   }
00999 
01000   // Otherwise, no immediates to move.
01001 }
01002 
01003 
01004 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
01005 /// added together.  This is used to reassociate common addition subexprs
01006 /// together for maximal sharing when rewriting bases.
01007 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
01008                              SCEVHandle Expr,
01009                              ScalarEvolution *SE) {
01010   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
01011     for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
01012       SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
01013   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
01014     SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
01015     if (SARE->getOperand(0) == Zero) {
01016       SubExprs.push_back(Expr);
01017     } else {
01018       // Compute the addrec with zero as its base.
01019       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
01020       Ops[0] = Zero;   // Start with zero base.
01021       SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
01022       
01023 
01024       SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
01025     }
01026   } else if (!Expr->isZero()) {
01027     // Do not add zero.
01028     SubExprs.push_back(Expr);
01029   }
01030 }
01031 
01032 // This is logically local to the following function, but C++ says we have 
01033 // to make it file scope.
01034 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
01035 
01036 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
01037 /// the Uses, removing any common subexpressions, except that if all such
01038 /// subexpressions can be folded into an addressing mode for all uses inside
01039 /// the loop (this case is referred to as "free" in comments herein) we do
01040 /// not remove anything.  This looks for things like (a+b+c) and
01041 /// (a+c+d) and computes the common (a+c) subexpression.  The common expression
01042 /// is *removed* from the Bases and returned.
01043 static SCEVHandle 
01044 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
01045                                     ScalarEvolution *SE, Loop *L,
01046                                     const TargetLowering *TLI) {
01047   unsigned NumUses = Uses.size();
01048 
01049   // Only one use?  This is a very common case, so we handle it specially and
01050   // cheaply.
01051   SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
01052   SCEVHandle Result = Zero;
01053   SCEVHandle FreeResult = Zero;
01054   if (NumUses == 1) {
01055     // If the use is inside the loop, use its base, regardless of what it is:
01056     // it is clearly shared across all the IV's.  If the use is outside the loop
01057     // (which means after it) we don't want to factor anything *into* the loop,
01058     // so just use 0 as the base.
01059     if (L->contains(Uses[0].Inst->getParent()))
01060       std::swap(Result, Uses[0].Base);
01061     return Result;
01062   }
01063 
01064   // To find common subexpressions, count how many of Uses use each expression.
01065   // If any subexpressions are used Uses.size() times, they are common.
01066   // Also track whether all uses of each expression can be moved into an
01067   // an addressing mode "for free"; such expressions are left within the loop.
01068   // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
01069   std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
01070   
01071   // UniqueSubExprs - Keep track of all of the subexpressions we see in the
01072   // order we see them.
01073   std::vector<SCEVHandle> UniqueSubExprs;
01074 
01075   std::vector<SCEVHandle> SubExprs;
01076   unsigned NumUsesInsideLoop = 0;
01077   for (unsigned i = 0; i != NumUses; ++i) {
01078     // If the user is outside the loop, just ignore it for base computation.
01079     // Since the user is outside the loop, it must be *after* the loop (if it
01080     // were before, it could not be based on the loop IV).  We don't want users
01081     // after the loop to affect base computation of values *inside* the loop,
01082     // because we can always add their offsets to the result IV after the loop
01083     // is done, ensuring we get good code inside the loop.
01084     if (!L->contains(Uses[i].Inst->getParent()))
01085       continue;
01086     NumUsesInsideLoop++;
01087     
01088     // If the base is zero (which is common), return zero now, there are no
01089     // CSEs we can find.
01090     if (Uses[i].Base == Zero) return Zero;
01091 
01092     // If this use is as an address we may be able to put CSEs in the addressing
01093     // mode rather than hoisting them.
01094     bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
01095     // We may need the UseTy below, but only when isAddrUse, so compute it
01096     // only in that case.
01097     const Type *UseTy = 0;
01098     if (isAddrUse) {
01099       UseTy  = Uses[i].Inst->getType();
01100       if (StoreInst *SI = dyn_cast<StoreInst>(Uses[i].Inst))
01101         UseTy = SI->getOperand(0)->getType();
01102     }
01103 
01104     // Split the expression into subexprs.
01105     SeparateSubExprs(SubExprs, Uses[i].Base, SE);
01106     // Add one to SubExpressionUseData.Count for each subexpr present, and
01107     // if the subexpr is not a valid immediate within an addressing mode use,
01108     // set SubExpressionUseData.notAllUsesAreFree.  We definitely want to
01109     // hoist these out of the loop (if they are common to all uses).
01110     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
01111       if (++SubExpressionUseData[SubExprs[j]].Count == 1)
01112         UniqueSubExprs.push_back(SubExprs[j]);
01113       if (!isAddrUse || !fitsInAddressMode(SubExprs[j], UseTy, TLI, false))
01114         SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
01115     }
01116     SubExprs.clear();
01117   }
01118 
01119   // Now that we know how many times each is used, build Result.  Iterate over
01120   // UniqueSubexprs so that we have a stable ordering.
01121   for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
01122     std::map<SCEVHandle, SubExprUseData>::iterator I = 
01123        SubExpressionUseData.find(UniqueSubExprs[i]);
01124     assert(I != SubExpressionUseData.end() && "Entry not found?");
01125     if (I->second.Count == NumUsesInsideLoop) { // Found CSE! 
01126       if (I->second.notAllUsesAreFree)
01127         Result = SE->getAddExpr(Result, I->first);
01128       else 
01129         FreeResult = SE->getAddExpr(FreeResult, I->first);
01130     } else
01131       // Remove non-cse's from SubExpressionUseData.
01132       SubExpressionUseData.erase(I);
01133   }
01134 
01135   if (FreeResult != Zero) {
01136     // We have some subexpressions that can be subsumed into addressing
01137     // modes in every use inside the loop.  However, it's possible that
01138     // there are so many of them that the combined FreeResult cannot
01139     // be subsumed, or that the target cannot handle both a FreeResult
01140     // and a Result in the same instruction (for example because it would
01141     // require too many registers).  Check this.
01142     for (unsigned i=0; i<NumUses; ++i) {
01143       if (!L->contains(Uses[i].Inst->getParent()))
01144         continue;
01145       // We know this is an addressing mode use; if there are any uses that
01146       // are not, FreeResult would be Zero.
01147       const Type *UseTy = Uses[i].Inst->getType();
01148       if (StoreInst *SI = dyn_cast<StoreInst>(Uses[i].Inst))
01149         UseTy = SI->getOperand(0)->getType();
01150       if (!fitsInAddressMode(FreeResult, UseTy, TLI, Result!=Zero)) {
01151         // FIXME:  could split up FreeResult into pieces here, some hoisted
01152         // and some not.  There is no obvious advantage to this.
01153         Result = SE->getAddExpr(Result, FreeResult);
01154         FreeResult = Zero;
01155         break;
01156       }
01157     }
01158   }
01159 
01160   // If we found no CSE's, return now.
01161   if (Result == Zero) return Result;
01162   
01163   // If we still have a FreeResult, remove its subexpressions from
01164   // SubExpressionUseData.  This means they will remain in the use Bases.
01165   if (FreeResult != Zero) {
01166     SeparateSubExprs(SubExprs, FreeResult, SE);
01167     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
01168       std::map<SCEVHandle, SubExprUseData>::iterator I = 
01169          SubExpressionUseData.find(SubExprs[j]);
01170       SubExpressionUseData.erase(I);
01171     }
01172     SubExprs.clear();
01173   }
01174 
01175   // Otherwise, remove all of the CSE's we found from each of the base values.
01176   for (unsigned i = 0; i != NumUses; ++i) {
01177     // Uses outside the loop don't necessarily include the common base, but
01178     // the final IV value coming into those uses does.  Instead of trying to
01179     // remove the pieces of the common base, which might not be there,
01180     // subtract off the base to compensate for this.
01181     if (!L->contains(Uses[i].Inst->getParent())) {
01182       Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
01183       continue;
01184     }
01185 
01186     // Split the expression into subexprs.
01187     SeparateSubExprs(SubExprs, Uses[i].Base, SE);
01188 
01189     // Remove any common subexpressions.
01190     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
01191       if (SubExpressionUseData.count(SubExprs[j])) {
01192         SubExprs.erase(SubExprs.begin()+j);
01193         --j; --e;
01194       }
01195     
01196     // Finally, add the non-shared expressions together.
01197     if (SubExprs.empty())
01198       Uses[i].Base = Zero;
01199     else
01200       Uses[i].Base = SE->getAddExpr(SubExprs);
01201     SubExprs.clear();
01202   }
01203  
01204   return Result;
01205 }
01206 
01207 /// ValidStride - Check whether the given Scale is valid for all loads and 
01208 /// stores in UsersToProcess.
01209 ///
01210 bool LoopStrengthReduce::ValidStride(bool HasBaseReg,
01211                                int64_t Scale, 
01212                                const std::vector<BasedUser>& UsersToProcess) {
01213   if (!TLI)
01214     return true;
01215 
01216   for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
01217     // If this is a load or other access, pass the type of the access in.
01218     const Type *AccessTy = Type::VoidTy;
01219     if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
01220       AccessTy = SI->getOperand(0)->getType();
01221     else if (LoadInst *LI = dyn_cast<LoadInst>(UsersToProcess[i].Inst))
01222       AccessTy = LI->getType();
01223     else if (isa<PHINode>(UsersToProcess[i].Inst))
01224       continue;
01225     
01226     TargetLowering::AddrMode AM;
01227     if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
01228       AM.BaseOffs = SC->getValue()->getSExtValue();
01229     AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
01230     AM.Scale = Scale;
01231 
01232     // If load[imm+r*scale] is illegal, bail out.
01233     if (!TLI->isLegalAddressingMode(AM, AccessTy))
01234       return false;
01235   }
01236   return true;
01237 }
01238 
01239 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
01240 /// a nop.
01241 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
01242                                                 const Type *Ty2) {
01243   if (Ty1 == Ty2)
01244     return false;
01245   if (Ty1->canLosslesslyBitCastTo(Ty2))
01246     return false;
01247   if (TLI && TLI->isTruncateFree(Ty1, Ty2))
01248     return false;
01249   if (isa<PointerType>(Ty2) && Ty1->canLosslesslyBitCastTo(UIntPtrTy))
01250     return false;
01251   if (isa<PointerType>(Ty1) && Ty2->canLosslesslyBitCastTo(UIntPtrTy))
01252     return false;
01253   return true;
01254 }
01255 
01256 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
01257 /// of a previous stride and it is a legal value for the target addressing
01258 /// mode scale component and optional base reg. This allows the users of
01259 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
01260 /// reuse is possible.  Factors can be negative on same targets, e.g. ARM.
01261 ///
01262 /// If all uses are outside the loop, we don't require that all multiplies
01263 /// be folded into the addressing mode, nor even that the factor be constant; 
01264 /// a multiply (executed once) outside the loop is better than another IV 
01265 /// within.  Well, usually.
01266 SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
01267                                 bool AllUsesAreAddresses,
01268                                 bool AllUsesAreOutsideLoop,
01269                                 const SCEVHandle &Stride, 
01270                                 IVExpr &IV, const Type *Ty,
01271                                 const std::vector<BasedUser>& UsersToProcess) {
01272   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
01273     int64_t SInt = SC->getValue()->getSExtValue();
01274     for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
01275          ++NewStride) {
01276       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
01277                 IVsByStride.find(StrideOrder[NewStride]);
01278       if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
01279         continue;
01280       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
01281       if (SI->first != Stride &&
01282           (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
01283         continue;
01284       int64_t Scale = SInt / SSInt;
01285       // Check that this stride is valid for all the types used for loads and
01286       // stores; if it can be used for some and not others, we might as well use
01287       // the original stride everywhere, since we have to create the IV for it
01288       // anyway. If the scale is 1, then we don't need to worry about folding
01289       // multiplications.
01290       if (Scale == 1 ||
01291           (AllUsesAreAddresses &&
01292            ValidStride(HasBaseReg, Scale, UsersToProcess)))
01293         for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
01294                IE = SI->second.IVs.end(); II != IE; ++II)
01295           // FIXME: Only handle base == 0 for now.
01296           // Only reuse previous IV if it would not require a type conversion.
01297           if (II->Base->isZero() &&
01298               !RequiresTypeConversion(II->Base->getType(), Ty)) {
01299             IV = *II;
01300             return SE->getIntegerSCEV(Scale, Stride->getType());
01301           }
01302     }
01303   } else if (AllUsesAreOutsideLoop) {
01304     // Accept nonconstant strides here; it is really really right to substitute
01305     // an existing IV if we can.
01306     for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
01307          ++NewStride) {
01308       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
01309                 IVsByStride.find(StrideOrder[NewStride]);
01310       if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
01311         continue;
01312       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
01313       if (SI->first != Stride && SSInt != 1)
01314         continue;
01315       for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
01316              IE = SI->second.IVs.end(); II != IE; ++II)
01317         // Accept nonzero base here.
01318         // Only reuse previous IV if it would not require a type conversion.
01319         if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
01320           IV = *II;
01321           return Stride;
01322         }
01323     }
01324     // Special case, old IV is -1*x and this one is x.  Can treat this one as
01325     // -1*old.
01326     for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
01327          ++NewStride) {
01328       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
01329                 IVsByStride.find(StrideOrder[NewStride]);
01330       if (SI == IVsByStride.end()) 
01331         continue;
01332       if (SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
01333         if (SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
01334           if (Stride == ME->getOperand(1) &&
01335               SC->getValue()->getSExtValue() == -1LL)
01336             for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
01337                    IE = SI->second.IVs.end(); II != IE; ++II)
01338               // Accept nonzero base here.
01339               // Only reuse previous IV if it would not require type conversion.
01340               if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
01341                 IV = *II;
01342                 return SE->getIntegerSCEV(-1LL, Stride->getType());
01343               }
01344     }
01345   }
01346   return SE->getIntegerSCEV(0, Stride->getType());
01347 }
01348 
01349 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
01350 /// returns true if Val's isUseOfPostIncrementedValue is true.
01351 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
01352   return Val.isUseOfPostIncrementedValue;
01353 }
01354 
01355 /// isNonConstantNegative - Return true if the specified scev is negated, but
01356 /// not a constant.
01357 static bool isNonConstantNegative(const SCEVHandle &Expr) {
01358   SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
01359   if (!Mul) return false;
01360   
01361   // If there is a constant factor, it will be first.
01362   SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
01363   if (!SC) return false;
01364   
01365   // Return true if the value is negative, this matches things like (-42 * V).
01366   return SC->getValue()->getValue().isNegative();
01367 }
01368 
01369 // CollectIVUsers - Transform our list of users and offsets to a bit more
01370 // complex table. In this new vector, each 'BasedUser' contains 'Base', the base
01371 // of the strided accesses, as well as the old information from Uses. We
01372 // progressively move information from the Base field to the Imm field, until
01373 // we eventually have the full access expression to rewrite the use.
01374 SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
01375                                               IVUsersOfOneStride &Uses,
01376                                               Loop *L,
01377                                               bool &AllUsesAreAddresses,
01378                                               bool &AllUsesAreOutsideLoop,
01379                                        std::vector<BasedUser> &UsersToProcess) {
01380   UsersToProcess.reserve(Uses.Users.size());
01381   for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
01382     UsersToProcess.push_back(BasedUser(Uses.Users[i], SE));
01383     
01384     // Move any loop variant operands from the offset field to the immediate
01385     // field of the use, so that we don't try to use something before it is
01386     // computed.
01387     MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
01388                                     UsersToProcess.back().Imm, L, SE);
01389     assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
01390            "Base value is not loop invariant!");
01391   }
01392 
01393   // We now have a whole bunch of uses of like-strided induction variables, but
01394   // they might all have different bases.  We want to emit one PHI node for this
01395   // stride which we fold as many common expressions (between the IVs) into as
01396   // possible.  Start by identifying the common expressions in the base values 
01397   // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
01398   // "A+B"), emit it to the preheader, then remove the expression from the
01399   // UsersToProcess base values.
01400   SCEVHandle CommonExprs =
01401     RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
01402 
01403   // Next, figure out what we can represent in the immediate fields of
01404   // instructions.  If we can represent anything there, move it to the imm
01405   // fields of the BasedUsers.  We do this so that it increases the commonality
01406   // of the remaining uses.
01407   unsigned NumPHI = 0;
01408   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
01409     // If the user is not in the current loop, this means it is using the exit
01410     // value of the IV.  Do not put anything in the base, make sure it's all in
01411     // the immediate field to allow as much factoring as possible.
01412     if (!L->contains(UsersToProcess[i].Inst->getParent())) {
01413       UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
01414                                              UsersToProcess[i].Base);
01415       UsersToProcess[i].Base = 
01416         SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
01417     } else {
01418 
01419       // Addressing modes can be folded into loads and stores.  Be careful that
01420       // the store is through the expression, not of the expression though.
01421       bool isPHI = false;
01422       bool isAddress = isAddressUse(UsersToProcess[i].Inst,
01423                                     UsersToProcess[i].OperandValToReplace);
01424       if (isa<PHINode>(UsersToProcess[i].Inst)) {
01425         isPHI = true;
01426         ++NumPHI;
01427       }
01428 
01429       // Not all uses are outside the loop.
01430       AllUsesAreOutsideLoop = false; 
01431      
01432       // If this use isn't an address, then not all uses are addresses.
01433       if (!isAddress && !isPHI)
01434         AllUsesAreAddresses = false;
01435       
01436       MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
01437                           UsersToProcess[i].Imm, isAddress, L, SE);
01438     }
01439   }
01440 
01441   // If one of the use if a PHI node and all other uses are addresses, still
01442   // allow iv reuse. Essentially we are trading one constant multiplication
01443   // for one fewer iv.
01444   if (NumPHI > 1)
01445     AllUsesAreAddresses = false;
01446 
01447   return CommonExprs;
01448 }
01449 
01450 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
01451 /// stride of IV.  All of the users may have different starting values, and this
01452 /// may not be the only stride (we know it is if isOnlyStride is true).
01453 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
01454                                                       IVUsersOfOneStride &Uses,
01455                                                       Loop *L,
01456                                                       bool isOnlyStride) {
01457   // If all the users are moved to another stride, then there is nothing to do.
01458   if (Uses.Users.empty())
01459     return;
01460 
01461   // Keep track if every use in UsersToProcess is an address. If they all are,
01462   // we may be able to rewrite the entire collection of them in terms of a
01463   // smaller-stride IV.
01464   bool AllUsesAreAddresses = true;
01465 
01466   // Keep track if every use of a single stride is outside the loop.  If so,
01467   // we want to be more aggressive about reusing a smaller-stride IV; a
01468   // multiply outside the loop is better than another IV inside.  Well, usually.
01469   bool AllUsesAreOutsideLoop = true;
01470 
01471   // Transform our list of users and offsets to a bit more complex table.  In
01472   // this new vector, each 'BasedUser' contains 'Base' the base of the
01473   // strided accessas well as the old information from Uses.  We progressively
01474   // move information from the Base field to the Imm field, until we eventually
01475   // have the full access expression to rewrite the use.
01476   std::vector<BasedUser> UsersToProcess;
01477   SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
01478                                           AllUsesAreOutsideLoop,
01479                                           UsersToProcess);
01480 
01481   // If we managed to find some expressions in common, we'll need to carry
01482   // their value in a register and add it in for each use. This will take up
01483   // a register operand, which potentially restricts what stride values are
01484   // valid.
01485   bool HaveCommonExprs = !CommonExprs->isZero();
01486   
01487   // If all uses are addresses, check if it is possible to reuse an IV with a
01488   // stride that is a factor of this stride. And that the multiple is a number
01489   // that can be encoded in the scale field of the target addressing mode. And
01490   // that we will have a valid instruction after this substition, including the
01491   // immediate field, if any.
01492   PHINode *NewPHI = NULL;
01493   Value   *IncV   = NULL;
01494   IVExpr   ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
01495                    SE->getIntegerSCEV(0, Type::Int32Ty),
01496                    0, 0);
01497   SCEVHandle RewriteFactor = 
01498                   CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
01499                                   AllUsesAreOutsideLoop,
01500                                   Stride, ReuseIV, CommonExprs->getType(),
01501                                   UsersToProcess);
01502   if (!isa<SCEVConstant>(RewriteFactor) || 
01503       !cast<SCEVConstant>(RewriteFactor)->isZero()) {
01504     DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
01505          << " and BASE " << *ReuseIV.Base << " :\n";
01506     NewPHI = ReuseIV.PHI;
01507     IncV   = ReuseIV.IncV;
01508   }
01509 
01510   const Type *ReplacedTy = CommonExprs->getType();
01511   
01512   // Now that we know what we need to do, insert the PHI node itself.
01513   //
01514   DOUT << "INSERTING IV of TYPE " << *ReplacedTy << " of STRIDE "
01515        << *Stride << " and BASE " << *CommonExprs << ": ";
01516 
01517   SCEVExpander Rewriter(*SE, *LI);
01518   SCEVExpander PreheaderRewriter(*SE, *LI);
01519   
01520   BasicBlock  *Preheader = L->getLoopPreheader();
01521   Instruction *PreInsertPt = Preheader->getTerminator();
01522   Instruction *PhiInsertBefore = L->getHeader()->begin();
01523   
01524   BasicBlock *LatchBlock = L->getLoopLatch();
01525 
01526 
01527   // Emit the initial base value into the loop preheader.
01528   Value *CommonBaseV
01529     = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt);
01530 
01531   if (isa<SCEVConstant>(RewriteFactor) &&
01532       cast<SCEVConstant>(RewriteFactor)->isZero()) {
01533     // Create a new Phi for this base, and stick it in the loop header.
01534     NewPHI = PHINode::Create(ReplacedTy, "iv.", PhiInsertBefore);
01535     ++NumInserted;
01536   
01537     // Add common base to the new Phi node.
01538     NewPHI->addIncoming(CommonBaseV, Preheader);
01539 
01540     // If the stride is negative, insert a sub instead of an add for the
01541     // increment.
01542     bool isNegative = isNonConstantNegative(Stride);
01543     SCEVHandle IncAmount = Stride;
01544     if (isNegative)
01545       IncAmount = SE->getNegativeSCEV(Stride);
01546     
01547     // Insert the stride into the preheader.
01548     Value *StrideV = PreheaderRewriter.expandCodeFor(IncAmount, PreInsertPt);
01549     if (!isa<ConstantInt>(StrideV)) ++NumVariable;
01550 
01551     // Emit the increment of the base value before the terminator of the loop
01552     // latch block, and add it to the Phi node.
01553     SCEVHandle IncExp = SE->getUnknown(StrideV);
01554     if (isNegative)
01555       IncExp = SE->getNegativeSCEV(IncExp);
01556     IncExp = SE->getAddExpr(SE->getUnknown(NewPHI), IncExp);
01557   
01558     IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator());
01559     IncV->setName(NewPHI->getName()+".inc");
01560     NewPHI->addIncoming(IncV, LatchBlock);
01561 
01562     // Remember this in case a later stride is multiple of this.
01563     IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
01564     
01565     DOUT << " IV=%" << NewPHI->getNameStr() << " INC=%" << IncV->getNameStr();
01566   } else {
01567     Constant *C = dyn_cast<Constant>(CommonBaseV);
01568     if (!C ||
01569         (!C->isNullValue() &&
01570          !fitsInAddressMode(SE->getUnknown(CommonBaseV), ReplacedTy, 
01571                            TLI, false)))
01572       // We want the common base emitted into the preheader! This is just
01573       // using cast as a copy so BitCast (no-op cast) is appropriate
01574       CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(), 
01575                                     "commonbase", PreInsertPt);
01576   }
01577   DOUT << "\n";
01578 
01579   // We want to emit code for users inside the loop first.  To do this, we
01580   // rearrange BasedUser so that the entries at the end have
01581   // isUseOfPostIncrementedValue = false, because we pop off the end of the
01582   // vector (so we handle them first).
01583   std::partition(UsersToProcess.begin(), UsersToProcess.end(),
01584                  PartitionByIsUseOfPostIncrementedValue);
01585   
01586   // Sort this by base, so that things with the same base are handled
01587   // together.  By partitioning first and stable-sorting later, we are
01588   // guaranteed that within each base we will pop off users from within the
01589   // loop before users outside of the loop with a particular base.
01590   //
01591   // We would like to use stable_sort here, but we can't.  The problem is that
01592   // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
01593   // we don't have anything to do a '<' comparison on.  Because we think the
01594   // number of uses is small, do a horrible bubble sort which just relies on
01595   // ==.
01596   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
01597     // Get a base value.
01598     SCEVHandle Base = UsersToProcess[i].Base;
01599     
01600     // Compact everything with this base to be consecutive with this one.
01601     for (unsigned j = i+1; j != e; ++j) {
01602       if (UsersToProcess[j].Base == Base) {
01603         std::swap(UsersToProcess[i+1], UsersToProcess[j]);
01604         ++i;
01605       }
01606     }
01607   }
01608 
01609   // Process all the users now.  This outer loop handles all bases, the inner
01610   // loop handles all users of a particular base.
01611   while (!UsersToProcess.empty()) {
01612     SCEVHandle Base = UsersToProcess.back().Base;
01613 
01614     // Emit the code for Base into the preheader.
01615     Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt);
01616 
01617     DOUT << "  INSERTING code for BASE = " << *Base << ":";
01618     if (BaseV->hasName())
01619       DOUT << " Result value name = %" << BaseV->getNameStr();
01620     DOUT << "\n";
01621 
01622     // If BaseV is a constant other than 0, make sure that it gets inserted into
01623     // the preheader, instead of being forward substituted into the uses.  We do
01624     // this by forcing a BitCast (noop cast) to be inserted into the preheader 
01625     // in this case.
01626     if (Constant *C = dyn_cast<Constant>(BaseV)) {
01627       if (!C->isNullValue() && !fitsInAddressMode(Base, ReplacedTy, 
01628                                                  TLI, false)) {
01629         // We want this constant emitted into the preheader! This is just
01630         // using cast as a copy so BitCast (no-op cast) is appropriate
01631         BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
01632                                 PreInsertPt);       
01633       }
01634     }
01635 
01636     // Emit the code to add the immediate offset to the Phi value, just before
01637     // the instructions that we identified as using this stride and base.
01638     do {
01639       // FIXME: Use emitted users to emit other users.
01640       BasedUser &User = UsersToProcess.back();
01641 
01642       // If this instruction wants to use the post-incremented value, move it
01643       // after the post-inc and use its value instead of the PHI.
01644       Value *RewriteOp = NewPHI;
01645       if (User.isUseOfPostIncrementedValue) {
01646         RewriteOp = IncV;
01647 
01648         // If this user is in the loop, make sure it is the last thing in the
01649         // loop to ensure it is dominated by the increment.
01650         if (L->contains(User.Inst->getParent()))
01651           User.Inst->moveBefore(LatchBlock->getTerminator());
01652       }
01653       if (RewriteOp->getType() != ReplacedTy) {
01654         Instruction::CastOps opcode = Instruction::Trunc;
01655         if (ReplacedTy->getPrimitiveSizeInBits() ==
01656             RewriteOp->getType()->getPrimitiveSizeInBits())
01657           opcode = Instruction::BitCast;
01658         RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
01659       }
01660 
01661       SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
01662 
01663       // If we had to insert new instructions for RewriteOp, we have to
01664       // consider that they may not have been able to end up immediately
01665       // next to RewriteOp, because non-PHI instructions may never precede
01666       // PHI instructions in a block. In this case, remember where the last
01667       // instruction was inserted so that if we're replacing a different
01668       // PHI node, we can use the later point to expand the final
01669       // RewriteExpr.
01670       Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
01671       if (RewriteOp == NewPHI) NewBasePt = 0;
01672 
01673       // Clear the SCEVExpander's expression map so that we are guaranteed
01674       // to have the code emitted where we expect it.
01675       Rewriter.clear();
01676 
01677       // If we are reusing the iv, then it must be multiplied by a constant
01678       // factor to take advantage of the addressing mode scale component.
01679       if (!isa<SCEVConstant>(RewriteFactor) ||
01680           !cast<SCEVConstant>(RewriteFactor)->isZero()) {
01681         // If we're reusing an IV with a nonzero base (currently this happens
01682         // only when all reuses are outside the loop) subtract that base here.
01683         // The base has been used to initialize the PHI node but we don't want
01684         // it here.
01685         if (!ReuseIV.Base->isZero()) {
01686           SCEVHandle typedBase = ReuseIV.Base;
01687           if (RewriteExpr->getType()->getPrimitiveSizeInBits() !=
01688               ReuseIV.Base->getType()->getPrimitiveSizeInBits()) {
01689             // It's possible the original IV is a larger type than the new IV,
01690             // in which case we have to truncate the Base.  We checked in
01691             // RequiresTypeConversion that this is valid.
01692             assert (RewriteExpr->getType()->getPrimitiveSizeInBits() <
01693                     ReuseIV.Base->getType()->getPrimitiveSizeInBits() &&
01694                     "Unexpected lengthening conversion!");
01695             typedBase = SE->getTruncateExpr(ReuseIV.Base, 
01696                                             RewriteExpr->getType());
01697           }
01698           RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
01699         }
01700 
01701         // Multiply old variable, with base removed, by new scale factor.
01702         RewriteExpr = SE->getMulExpr(RewriteFactor,
01703                                      RewriteExpr);
01704 
01705         // The common base is emitted in the loop preheader. But since we
01706         // are reusing an IV, it has not been used to initialize the PHI node.
01707         // Add it to the expression used to rewrite the uses.
01708         // When this use is outside the loop, we earlier subtracted the
01709         // common base, and are adding it back here.  Use the same expression
01710         // as before, rather than CommonBaseV, so DAGCombiner will zap it.
01711         if (!isa<ConstantInt>(CommonBaseV) ||
01712             !cast<ConstantInt>(CommonBaseV)->isZero()) {
01713           if (L->contains(User.Inst->getParent()))
01714             RewriteExpr = SE->getAddExpr(RewriteExpr,
01715                                        SE->getUnknown(CommonBaseV));
01716           else
01717             RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
01718         }
01719       }
01720 
01721       // Now that we know what we need to do, insert code before User for the
01722       // immediate and any loop-variant expressions.
01723       if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
01724         // Add BaseV to the PHI value if needed.
01725         RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
01726 
01727       User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
01728                                           Rewriter, L, this,
01729                                           DeadInsts);
01730 
01731       // Mark old value we replaced as possibly dead, so that it is eliminated
01732       // if we just replaced the last use of that value.
01733       DeadInsts.push_back(cast<Instruction>(User.OperandValToReplace));
01734 
01735       UsersToProcess.pop_back();
01736       ++NumReduced;
01737 
01738       // If there are any more users to process with the same base, process them
01739       // now.  We sorted by base above, so we just have to check the last elt.
01740     } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
01741     // TODO: Next, find out which base index is the most common, pull it out.
01742   }
01743 
01744   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
01745   // different starting values, into different PHIs.
01746 }
01747 
01748 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
01749 /// set the IV user and stride information and return true, otherwise return
01750 /// false.
01751 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
01752                                        const SCEVHandle *&CondStride) {
01753   for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
01754        ++Stride) {
01755     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
01756     IVUsesByStride.find(StrideOrder[Stride]);
01757     assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
01758     
01759     for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
01760          E = SI->second.Users.end(); UI != E; ++UI)
01761       if (UI->User == Cond) {
01762         // NOTE: we could handle setcc instructions with multiple uses here, but
01763         // InstCombine does it as well for simple uses, it's not clear that it
01764         // occurs enough in real life to handle.
01765         CondUse = &*UI;
01766         CondStride = &SI->first;
01767         return true;
01768       }
01769   }
01770   return false;
01771 }    
01772 
01773 namespace {
01774   // Constant strides come first which in turns are sorted by their absolute
01775   // values. If absolute values are the same, then positive strides comes first.
01776   // e.g.
01777   // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
01778   struct StrideCompare {
01779     bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
01780       SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
01781       SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
01782       if (LHSC && RHSC) {
01783         int64_t  LV = LHSC->getValue()->getSExtValue();
01784         int64_t  RV = RHSC->getValue()->getSExtValue();
01785         uint64_t ALV = (LV < 0) ? -LV : LV;
01786         uint64_t ARV = (RV < 0) ? -RV : RV;
01787         if (ALV == ARV)
01788           return LV > RV;
01789         else
01790           return ALV < ARV;
01791       }
01792       return (LHSC && !RHSC);
01793     }
01794   };
01795 }
01796 
01797 /// ChangeCompareStride - If a loop termination compare instruction is the
01798 /// only use of its stride, and the compaison is against a constant value,
01799 /// try eliminate the stride by moving the compare instruction to another
01800 /// stride and change its constant operand accordingly. e.g.
01801 ///
01802 /// loop:
01803 /// ...
01804 /// v1 = v1 + 3
01805 /// v2 = v2 + 1
01806 /// if (v2 < 10) goto loop
01807 /// =>
01808 /// loop:
01809 /// ...
01810 /// v1 = v1 + 3
01811 /// if (v1 < 30) goto loop
01812 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
01813                                                 IVStrideUse* &CondUse,
01814                                                 const SCEVHandle* &CondStride) {
01815   if (StrideOrder.size() < 2 ||
01816       IVUsesByStride[*CondStride].Users.size() != 1)
01817     return Cond;
01818   const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
01819   if (!SC) return Cond;
01820   ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1));
01821   if (!C) return Cond;
01822 
01823   ICmpInst::Predicate Predicate = Cond->getPredicate();
01824   int64_t CmpSSInt = SC->getValue()->getSExtValue();
01825   int64_t CmpVal = C->getValue().getSExtValue();
01826   unsigned BitWidth = C->getValue().getBitWidth();
01827   uint64_t SignBit = 1ULL << (BitWidth-1);
01828   const Type *CmpTy = C->getType();
01829   const Type *NewCmpTy = NULL;
01830   unsigned TyBits = CmpTy->getPrimitiveSizeInBits();
01831   unsigned NewTyBits = 0;
01832   int64_t NewCmpVal = CmpVal;
01833   SCEVHandle *NewStride = NULL;
01834   Value *NewIncV = NULL;
01835   int64_t Scale = 1;
01836 
01837   // Check stride constant and the comparision constant signs to detect
01838   // overflow.
01839   if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
01840     return Cond;
01841 
01842   // Look for a suitable stride / iv as replacement.
01843   std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
01844   for (unsigned i = 0, e = StrideOrder.size(); i != e; ++i) {
01845     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
01846       IVUsesByStride.find(StrideOrder[i]);
01847     if (!isa<SCEVConstant>(SI->first))
01848       continue;
01849     int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
01850     if (abs(SSInt) <= abs(CmpSSInt) || (SSInt % CmpSSInt) != 0)
01851       continue;
01852 
01853     Scale = SSInt / CmpSSInt;
01854     NewCmpVal = CmpVal * Scale;
01855     APInt Mul = APInt(BitWidth, NewCmpVal);
01856     // Check for overflow.
01857     if (Mul.getSExtValue() != NewCmpVal) {
01858       NewCmpVal = CmpVal;
01859       continue;
01860     }
01861 
01862     // Watch out for overflow.
01863     if (ICmpInst::isSignedPredicate(Predicate) &&
01864         (CmpVal & SignBit) != (NewCmpVal & SignBit))
01865       NewCmpVal = CmpVal;
01866 
01867     if (NewCmpVal != CmpVal) {
01868       // Pick the best iv to use trying to avoid a cast.
01869       NewIncV = NULL;
01870       for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
01871              E = SI->second.Users.end(); UI != E; ++UI) {
01872         NewIncV = UI->OperandValToReplace;
01873         if (NewIncV->getType() == CmpTy)
01874           break;
01875       }
01876       if (!NewIncV) {
01877         NewCmpVal = CmpVal;
01878         continue;
01879       }
01880 
01881       NewCmpTy = NewIncV->getType();
01882       NewTyBits = isa<PointerType>(NewCmpTy)
01883         ? UIntPtrTy->getPrimitiveSizeInBits()
01884         : NewCmpTy->getPrimitiveSizeInBits();
01885       if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
01886         // Check if it is possible to rewrite it using
01887         // an iv / stride of a smaller integer type.
01888         bool TruncOk = false;
01889         if (NewCmpTy->isInteger()) {
01890           unsigned Bits = NewTyBits;
01891           if (ICmpInst::isSignedPredicate(Predicate))
01892             --Bits;
01893           uint64_t Mask = (1ULL << Bits) - 1;
01894           if (((uint64_t)NewCmpVal & Mask) == (uint64_t)NewCmpVal)
01895             TruncOk = true;
01896         }
01897         if (!TruncOk) {
01898           NewCmpVal = CmpVal;
01899           continue;
01900         }
01901       }
01902 
01903       // Don't rewrite if use offset is non-constant and the new type is
01904       // of a different type.
01905       // FIXME: too conservative?
01906       if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->Offset)) {
01907         NewCmpVal = CmpVal;
01908         continue;
01909       }
01910 
01911       bool AllUsesAreAddresses = true;
01912       bool AllUsesAreOutsideLoop = true;
01913       std::vector<BasedUser> UsersToProcess;
01914       SCEVHandle CommonExprs = CollectIVUsers(SI->first, SI->second, L,
01915                                               AllUsesAreAddresses,
01916                                               AllUsesAreOutsideLoop,
01917                                               UsersToProcess);
01918       // Avoid rewriting the compare instruction with an iv of new stride
01919       // if it's likely the new stride uses will be rewritten using the
01920       if (AllUsesAreAddresses &&
01921           ValidStride(!CommonExprs->isZero(), Scale, UsersToProcess)) {
01922         NewCmpVal = CmpVal;
01923         continue;
01924       }
01925 
01926       // If scale is negative, use swapped predicate unless it's testing
01927       // for equality.
01928       if (Scale < 0 && !Cond->isEquality())
01929         Predicate = ICmpInst::getSwappedPredicate(Predicate);
01930 
01931       NewStride = &StrideOrder[i];
01932       break;
01933     }
01934   }
01935 
01936   // Forgo this transformation if it the increment happens to be
01937   // unfortunately positioned after the condition, and the condition
01938   // has multiple uses which prevent it from being moved immediately
01939   // before the branch. See
01940   // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
01941   // for an example of this situation.
01942   if (!Cond->hasOneUse()) {
01943     for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
01944          I != E; ++I)
01945       if (I == NewIncV)
01946         return Cond;
01947   }
01948 
01949   if (NewCmpVal != CmpVal) {
01950     // Create a new compare instruction using new stride / iv.
01951     ICmpInst *OldCond = Cond;
01952     Value *RHS;
01953     if (!isa<PointerType>(NewCmpTy))
01954       RHS = ConstantInt::get(NewCmpTy, NewCmpVal);
01955     else {
01956       RHS = ConstantInt::get(UIntPtrTy, NewCmpVal);
01957       RHS = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr, RHS, NewCmpTy);
01958     }
01959     // Insert new compare instruction.
01960     Cond = new ICmpInst(Predicate, NewIncV, RHS,
01961                         L->getHeader()->getName() + ".termcond",
01962                         OldCond);
01963 
01964     // Remove the old compare instruction. The old indvar is probably dead too.
01965     DeadInsts.push_back(cast<Instruction>(CondUse->OperandValToReplace));
01966     SE->deleteValueFromRecords(OldCond);
01967     OldCond->replaceAllUsesWith(Cond);
01968     OldCond->eraseFromParent();
01969 
01970     IVUsesByStride[*CondStride].Users.pop_back();
01971     SCEVHandle NewOffset = TyBits == NewTyBits
01972       ? SE->getMulExpr(CondUse->Offset,
01973                        SE->getConstant(ConstantInt::get(CmpTy, Scale)))
01974       : SE->getConstant(ConstantInt::get(NewCmpTy,
01975         cast<SCEVConstant>(CondUse->Offset)->getValue()->getSExtValue()*Scale));
01976     IVUsesByStride[*NewStride].addUser(NewOffset, Cond, NewIncV);
01977     CondUse = &IVUsesByStride[*NewStride].Users.back();
01978     CondStride = NewStride;
01979     ++NumEliminated;
01980   }
01981 
01982   return Cond;
01983 }
01984 
01985 /// OptimizeSMax - Rewrite the loop's terminating condition if it uses
01986 /// an smax computation.
01987 ///
01988 /// This is a narrow solution to a specific, but acute, problem. For loops
01989 /// like this:
01990 ///
01991 ///   i = 0;
01992 ///   do {
01993 ///     p[i] = 0.0;
01994 ///   } while (++i < n);
01995 ///
01996 /// where the comparison is signed, the trip count isn't just 'n', because
01997 /// 'n' could be negative. And unfortunately this can come up even for loops
01998 /// where the user didn't use a C do-while loop. For example, seemingly
01999 /// well-behaved top-test loops will commonly be lowered like this:
02000 //
02001 ///   if (n > 0) {
02002 ///     i = 0;
02003 ///     do {
02004 ///       p[i] = 0.0;
02005 ///     } while (++i < n);
02006 ///   }
02007 ///
02008 /// and then it's possible for subsequent optimization to obscure the if
02009 /// test in such a way that indvars can't find it.
02010 ///
02011 /// When indvars can't find the if test in loops like this, it creates a
02012 /// signed-max expression, which allows it to give the loop a canonical
02013 /// induction variable:
02014 ///
02015 ///   i = 0;
02016 ///   smax = n < 1 ? 1 : n;
02017 ///   do {
02018 ///     p[i] = 0.0;
02019 ///   } while (++i != smax);
02020 ///
02021 /// Canonical induction variables are necessary because the loop passes
02022 /// are designed around them. The most obvious example of this is the
02023 /// LoopInfo analysis, which doesn't remember trip count values. It
02024 /// expects to be able to rediscover the trip count each time it is
02025 /// needed, and it does this using a simple analyis that only succeeds if
02026 /// the loop has a canonical induction variable.
02027 ///
02028 /// However, when it comes time to generate code, the maximum operation
02029 /// can be quite costly, especially if it's inside of an outer loop.
02030 ///
02031 /// This function solves this problem by detecting this type of loop and
02032 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
02033 /// the instructions for the maximum computation.
02034 ///
02035 ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
02036                                            IVStrideUse* &CondUse) {
02037   // Check that the loop matches the pattern we're looking for.
02038   if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
02039       Cond->getPredicate() != CmpInst::ICMP_NE)
02040     return Cond;
02041 
02042   SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
02043   if (!Sel || !Sel->hasOneUse()) return Cond;
02044 
02045   SCEVHandle IterationCount = SE->getIterationCount(L);
02046   if (isa<SCEVCouldNotCompute>(IterationCount))
02047     return Cond;
02048   SCEVHandle One = SE->getIntegerSCEV(1, IterationCount->getType());
02049 
02050   // Adjust for an annoying getIterationCount quirk.
02051   IterationCount = SE->getAddExpr(IterationCount, One);
02052 
02053   // Check for a max calculation that matches the pattern.
02054   SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
02055   if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
02056 
02057   SCEVHandle SMaxLHS = SMax->getOperand(0);
02058   SCEVHandle SMaxRHS = SMax->getOperand(1);
02059   if (!SMaxLHS || SMaxLHS != One) return Cond;
02060 
02061   // Check the relevant induction variable for conformance to
02062   // the pattern.
02063   SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
02064   SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
02065   if (!AR || !AR->isAffine() ||
02066       AR->getStart() != One ||
02067       AR->getStepRecurrence(*SE) != One)
02068     return Cond;
02069 
02070   // Check the right operand of the select, and remember it, as it will
02071   // be used in the new comparison instruction.
02072   Value *NewRHS = 0;
02073   if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
02074     NewRHS = Sel->getOperand(1);
02075   else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
02076     NewRHS = Sel->getOperand(2);
02077   if (!NewRHS) return Cond;
02078 
02079   // Ok, everything looks ok to change the condition into an SLT or SGE and
02080   // delete the max calculation.
02081   ICmpInst *NewCond =
02082     new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
02083                    CmpInst::ICMP_SLT :
02084                    CmpInst::ICMP_SGE,
02085                  Cond->getOperand(0), NewRHS, "scmp", Cond);
02086 
02087   // Delete the max calculation instructions.
02088   SE->deleteValueFromRecords(Cond);
02089   Cond->replaceAllUsesWith(NewCond);
02090   Cond->eraseFromParent();
02091   Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
02092   SE->deleteValueFromRecords(Sel);
02093   Sel->eraseFromParent();
02094   if (Cmp->use_empty()) {
02095     SE->deleteValueFromRecords(Cmp);
02096     Cmp->eraseFromParent();
02097   }
02098   CondUse->User = NewCond;
02099   return NewCond;
02100 }
02101 
02102 /// OptimizeShadowIV - If IV is used in a int-to-float cast
02103 /// inside the loop then try to eliminate the cast opeation.
02104 void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
02105 
02106   SCEVHandle IterationCount = SE->getIterationCount(L);
02107   if (isa<SCEVCouldNotCompute>(IterationCount))
02108     return;
02109 
02110   for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e;
02111        ++Stride) {
02112     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
02113       IVUsesByStride.find(StrideOrder[Stride]);
02114     assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
02115     if (!isa<SCEVConstant>(SI->first))
02116       continue;
02117 
02118     for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
02119            E = SI->second.Users.end(); UI != E; /* empty */) {
02120       std::vector<IVStrideUse>::iterator CandidateUI = UI;
02121       ++UI;
02122       Instruction *ShadowUse = CandidateUI->User;
02123       const Type *DestTy = NULL;
02124 
02125       /* If shadow use is a int->float cast then insert a second IV
02126          to eliminate this cast.
02127 
02128            for (unsigned i = 0; i < n; ++i) 
02129              foo((double)i);
02130 
02131          is transformed into
02132 
02133            double d = 0.0;
02134            for (unsigned i = 0; i < n; ++i, ++d) 
02135              foo(d);
02136       */
02137       if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->User))
02138         DestTy = UCast->getDestTy();
02139       else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->User))
02140         DestTy = SCast->getDestTy();
02141       if (!DestTy) continue;
02142 
02143       if (TLI) {
02144         /* If target does not support DestTy natively then do not apply
02145            this transformation. */
02146         MVT DVT = TLI->getValueType(DestTy);
02147         if (!TLI->isTypeLegal(DVT)) continue;
02148       }
02149 
02150       PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
02151       if (!PH) continue;
02152       if (PH->getNumIncomingValues() != 2) continue;
02153 
02154       const Type *SrcTy = PH->getType();
02155       int Mantissa = DestTy->getFPMantissaWidth();
02156       if (Mantissa == -1) continue; 
02157       if ((int)TD->getTypeSizeInBits(SrcTy) > Mantissa)
02158         continue;
02159 
02160       unsigned Entry, Latch;
02161       if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
02162         Entry = 0;
02163         Latch = 1;
02164       } else {
02165         Entry = 1;
02166         Latch = 0;
02167       }
02168         
02169       ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
02170       if (!Init) continue;
02171       ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
02172 
02173       BinaryOperator *Incr = 
02174         dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
02175       if (!Incr) continue;
02176       if (Incr->getOpcode() != Instruction::Add
02177           && Incr->getOpcode() != Instruction::Sub)
02178         continue;
02179 
02180       /* Initialize new IV, double d = 0.0 in above example. */
02181       ConstantInt *C = NULL;
02182       if (Incr->getOperand(0) == PH)
02183         C = dyn_cast<ConstantInt>(Incr->getOperand(1));
02184       else if (Incr->getOperand(1) == PH)
02185         C = dyn_cast<ConstantInt>(Incr->getOperand(0));
02186       else
02187         continue;
02188 
02189       if (!C) continue;
02190 
02191       /* Add new PHINode. */
02192       PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
02193 
02194       /* create new increment. '++d' in above example. */
02195       ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
02196       BinaryOperator *NewIncr = 
02197         BinaryOperator::Create(Incr->getOpcode(),
02198                                NewPH, CFP, "IV.S.next.", Incr);
02199 
02200       NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
02201       NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
02202 
02203       /* Remove cast operation */
02204       SE->deleteValueFromRecords(ShadowUse);
02205       ShadowUse->replaceAllUsesWith(NewPH);
02206       ShadowUse->eraseFromParent();
02207       SI->second.Users.erase(CandidateUI);
02208       NumShadow++;
02209       break;
02210     }
02211   }
02212 }
02213 
02214 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
02215 // uses in the loop, look to see if we can eliminate some, in favor of using
02216 // common indvars for the different uses.
02217 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
02218   // TODO: implement optzns here.
02219 
02220   OptimizeShadowIV(L);
02221 
02222   // Finally, get the terminating condition for the loop if possible.  If we
02223   // can, we want to change it to use a post-incremented version of its
02224   // induction variable, to allow coalescing the live ranges for the IV into
02225   // one register value.
02226   PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
02227   BasicBlock  *Preheader = L->getLoopPreheader();
02228   BasicBlock *LatchBlock =
02229    SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
02230   BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
02231   if (!TermBr || TermBr->isUnconditional() || 
02232       !isa<ICmpInst>(TermBr->getCondition()))
02233     return;
02234   ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
02235 
02236   // Search IVUsesByStride to find Cond's IVUse if there is one.
02237   IVStrideUse *CondUse = 0;
02238   const SCEVHandle *CondStride = 0;
02239 
02240   if (!FindIVUserForCond(Cond, CondUse, CondStride))
02241     return; // setcc doesn't use the IV.
02242 
02243   // If the trip count is computed in terms of an smax (due to ScalarEvolution
02244   // being unable to find a sufficient guard, for example), change the loop
02245   // comparison to use SLT instead of NE.
02246   Cond = OptimizeSMax(L, Cond, CondUse);
02247 
02248   // If possible, change stride and operands of the compare instruction to
02249   // eliminate one stride.
02250   Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
02251 
02252   // It's possible for the setcc instruction to be anywhere in the loop, and
02253   // possible for it to have multiple users.  If it is not immediately before
02254   // the latch block branch, move it.
02255   if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
02256     if (Cond->hasOneUse()) {   // Condition has a single use, just move it.
02257       Cond->moveBefore(TermBr);
02258     } else {
02259       // Otherwise, clone the terminating condition and insert into the loopend.
02260       Cond = cast<ICmpInst>(Cond->clone());
02261       Cond->setName(L->getHeader()->getName() + ".termcond");
02262       LatchBlock->getInstList().insert(TermBr, Cond);
02263       
02264       // Clone the IVUse, as the old use still exists!
02265       IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
02266                                          CondUse->OperandValToReplace);
02267       CondUse = &IVUsesByStride[*CondStride].Users.back();
02268     }
02269   }
02270 
02271   // If we get to here, we know that we can transform the setcc instruction to
02272   // use the post-incremented version of the IV, allowing us to coalesce the
02273   // live ranges for the IV correctly.
02274   CondUse->Offset = SE->getMinusSCEV(CondUse->Offset, *CondStride);
02275   CondUse->isUseOfPostIncrementedValue = true;
02276   Changed = true;
02277 }
02278 
02279 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
02280 
02281   LI = &getAnalysis<LoopInfo>();
02282   DT = &getAnalysis<DominatorTree>();
02283   SE = &getAnalysis<ScalarEvolution>();
02284   TD = &getAnalysis<TargetData>();
02285   UIntPtrTy = TD->getIntPtrType();
02286   Changed = false;
02287 
02288   // Find all uses of induction variables in this loop, and categorize
02289   // them by stride.  Start by finding all of the PHI nodes in the header for
02290   // this loop.  If they are induction variables, inspect their uses.
02291   SmallPtrSet<Instruction*,16> Processed;   // Don't reprocess instructions.
02292   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
02293     AddUsersIfInteresting(I, L, Processed);
02294 
02295   if (!IVUsesByStride.empty()) {
02296     // Optimize induction variables.  Some indvar uses can be transformed to use
02297     // strides that will be needed for other purposes.  A common example of this
02298     // is the exit test for the loop, which can often be rewritten to use the
02299     // computation of some other indvar to decide when to terminate the loop.
02300     OptimizeIndvars(L);
02301 
02302     // FIXME: We can widen subreg IV's here for RISC targets.  e.g. instead of
02303     // doing computation in byte values, promote to 32-bit values if safe.
02304 
02305     // FIXME: Attempt to reuse values across multiple IV's.  In particular, we
02306     // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
02307     // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
02308     // Need to be careful that IV's are all the same type.  Only works for
02309     // intptr_t indvars.
02310 
02311     // If we only have one stride, we can more aggressively eliminate some
02312     // things.
02313     bool HasOneStride = IVUsesByStride.size() == 1;
02314 
02315 #ifndef NDEBUG
02316     DOUT << "\nLSR on ";
02317     DEBUG(L->dump());
02318 #endif
02319 
02320     // IVsByStride keeps IVs for one particular loop.
02321     assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
02322 
02323     // Sort the StrideOrder so we process larger strides first.
02324     std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
02325 
02326     // Note: this processes each stride/type pair individually.  All users
02327     // passed into StrengthReduceStridedIVUsers have the same type AND stride.
02328     // Also, note that we iterate over IVUsesByStride indirectly by using
02329     // StrideOrder. This extra layer of indirection makes the ordering of
02330     // strides deterministic - not dependent on map order.
02331     for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
02332       std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
02333         IVUsesByStride.find(StrideOrder[Stride]);
02334       assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
02335       StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
02336     }
02337   }
02338 
02339   // We're done analyzing this loop; release all the state we built up for it.
02340   CastedPointers.clear();
02341   IVUsesByStride.clear();
02342   IVsByStride.clear();
02343   StrideOrder.clear();
02344   for (unsigned i=0; i<GEPlist.size(); i++)
02345     SE->deleteValueFromRecords(GEPlist[i]);
02346   GEPlist.clear();  
02347 
02348   // Clean up after ourselves
02349   if (!DeadInsts.empty()) {
02350     DeleteTriviallyDeadInstructions();
02351 
02352     BasicBlock::iterator I = L->getHeader()->begin();
02353     while (PHINode *PN = dyn_cast<PHINode>(I++)) {
02354       // At this point, we know that we have killed one or more IV users.
02355       // It is worth checking to see if the cannonical indvar is also
02356       // dead, so that we can remove it as well.
02357       //
02358       // We can remove a PHI if it is on a cycle in the def-use graph
02359       // where each node in the cycle has degree one, i.e. only one use,
02360       // and is an instruction with no side effects.
02361       //
02362       // FIXME: this needs to eliminate an induction variable even if it's being
02363       // compared against some value to decide loop termination.
02364       if (!PN->hasOneUse())
02365         continue;
02366       
02367       SmallPtrSet<PHINode *, 4> PHIs;
02368       for (Instruction *J = dyn_cast<Instruction>(*PN->use_begin());
02369            J && J->hasOneUse() && !J->mayWriteToMemory();
02370            J = dyn_cast<Instruction>(*J->use_begin())) {
02371         // If we find the original PHI, we've discovered a cycle.
02372         if (J == PN) {
02373           // Break the cycle and mark the PHI for deletion.
02374           SE->deleteValueFromRecords(PN);
02375           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
02376           DeadInsts.push_back(PN);
02377           Changed = true;
02378           break;
02379         }
02380         // If we find a PHI more than once, we're on a cycle that
02381         // won't prove fruitful.
02382         if (isa<PHINode>(J) && !PHIs.insert(cast<PHINode>(J)))
02383           break;
02384       }
02385     }
02386     DeleteTriviallyDeadInstructions();
02387   }
02388   return Changed;
02389 }